diff --git a/.gitignore b/.gitignore index 4b90e7b..e4cb8df 100644 --- a/.gitignore +++ b/.gitignore @@ -16,8 +16,8 @@ nuget/wwwroot/ # The browser CI installs for the browser tests. .playwright/ -# Work that belongs to a person: experiments, spikes and notes. -.local/ +# Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines. +.sandbox/ # npm's logs. npm-debug.log* diff --git a/CHANGELOG.md b/CHANGELOG.md index a1af7ba..0892662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - **An entry is dated when its release is cut,** and reads *Unreleased* until then. [Cutting a release](CONTRIBUTING.md#cut-a-release) tags its commit, and its packages are published from that tag. - **A change a caller can notice** is listed in the newest entry while it is unreleased. Once it is released, the change opens the next version's entry, and the sources declare that version in the same commit. + + +## `1.0.0-preview.4` + +*December 1, 2026 · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.3` · definition format 38* + +- An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, null where the element is laid out as no one box or as one of no size, and a watch follows every change of it. +- A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. +- A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. +- An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. +- Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. +- A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. +- DOMQL's module and its registry are created under the manifest Nexo makes of the module, which DOMQL's sources hold, so a start makes none of the checks it records: in Chromium, cold, DOMQL's import took about 33.5 ms where it took 43, and its first resolution and registrations about 2 ms more. DOMQL on a Nexo other than the one it was built against creates its module with every check, as before. +- `domql.connect(deliver)` carries this instance's operations across a boundary as messages: a host's requests in batches, each answered once its task ends, a watch's first snapshot among the answers, and each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. +- A host prepares its modules and queries ahead of time: `domql.prepare(modules, { scripts })` answers Nexo's manifest, and `createModule`, `registerModule`, `registerModuleLoader` and `query` take it as `manifest`, sparing the checks it records. In Chromium, cold, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4. + ## `1.0.0-preview.3` diff --git a/CLAUDE.md b/CLAUDE.md index 4e735c3..d868758 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,9 +10,9 @@ Read the documents that govern the affected contract: | Document | Authority | | --- | --- | -| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | Nexo's two contracts, at the release DOMQL builds against: the language's, what a query means, and the runtime's, how DOMQL as its host binds, resolves, evaluates and registers modules | +| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | Nexo's two contracts, at the release DOMQL builds against: the language's, what a query means, and the runtime's, how DOMQL as its host binds, resolves, evaluates and registers modules | | [DOMQL specification](spec/README.md) | DOMQL's module and DOMQL as host: queries, nodes and shadow trees, the built-in vocabulary, evaluation, watching, results, events, executions, and the public API, one document per subject | -| [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md) | How Nexo is built: its stages, modules, evaluation and tooling | +| [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md) | How Nexo is built: its stages, modules, evaluation and tooling | | [DOMQL design](docs/domql-design.md) | How DOMQL is built: its architecture, resolution, sessions, watching, comparing and patching, the C# half, and the decisions not taken | | [Status](docs/features-status.md) | What is implemented, the migration to Nexo, the planned capabilities, open decisions and deferred work | | [Decisions](docs/decisions.md) | Each decision taken without stopping to ask, with why and what was declined, for review | @@ -32,22 +32,24 @@ Use these sources rather than inventing scope, status or style rules. | `src/domql.js` | Entry point that composes the library's modules | | `src/Versions.mjs` | The versions DOMQL reports: its runtime release, the specification it follows, and the language its Nexo runtime follows | | `src/dom/` | Evaluation, watches, events, executions, observations, sessions and built-in implementations | +| `src/connections/` | A connection: DOMQL's operations carried across a boundary as messages, for a host whose code runs elsewhere | | `src/snapshots/` | Computing, comparing, dispatching and applying snapshot updates using identity metadata; no DOM access | -| `tests/` | Tests mirroring the source folders | -| `scripts/` | Bundling scripts, and the package's file lists and verification | +| `tests/` | Tests mirroring the source folders, and the change sets' conformance corpus in `tests/_conformance/`, which DOMQL.NET's tests read too | +| `scripts/` | Bundling scripts, the manifest of DOMQL's own module, and the package's file lists and verification | | `spec/` | The specification, one document per subject, indexed by `spec/README.md` | | `docs/` | The design, the status overview and the decisions | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | | `nuget/` | The package project, which distributes the bundle, and the library guide | -| `.local/` | Personal experiments, spikes, notes and benchmark baselines; ignored by Git | +| `.sandbox/` | Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines; ignored by Git | Add a folder when a new responsibility needs one. Keep dependencies in this direction: - `dom/` may depend on Nexo and `snapshots/`. - `snapshots/` may depend on Nexo. +- `connections/` may depend on Nexo, and reaches DOMQL through the instance its entry point gives it. -The language is Nexo, the package `@formaui-net/nexo`, which DOMQL imports by its name and installs from npm, at the release `package.json` declares as the lowest it works with and its lock installs, so a change reaches DOMQL only when that version moves to a release that holds it; with `NEXO_SOURCE` naming a checkout, `build.ps1` links that checkout's working tree in the package's place instead. A change to the language is made there, and a change DOMQL needs of it in both repositories together, with `NEXO_SOURCE` set, moving the version once Nexo releases it. Link Nexo's documents at the release's tag, as `https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md`, so they move with it; the link test reads them from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, named `formaui-net.Nexo`. +The language is Nexo, the package `@formaui-net/nexo`, which DOMQL imports by its name and installs from npm, at the release `package.json` declares as the lowest it works with and its lock installs, so a change reaches DOMQL only when that version moves to a release that holds it; with `NEXO_SOURCE` naming a checkout, `build.ps1` links that checkout's working tree in the package's place instead. A change to the language is made there, and a change DOMQL needs of it in both repositories together, with `NEXO_SOURCE` set, moving the version once Nexo releases it. Link Nexo's documents at the release's tag, as `https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md`, so they move with it; the link test reads them from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, named `formaui-net.Nexo`. Pass the window and document into DOM code; do not read globals there. Importing the language layer and resolving a query must work without a DOM. @@ -100,7 +102,7 @@ Tests mirror `src/` under `tests/`. Layout, geometry and browser-managed state b | `./build.ps1 -Browser` | Repository root | Gate including browser tests | | `./build.ps1 -Browser -Full` | Repository root | The full gate: the gate including browser tests, then the NuGet package packed and verified as consumers install it | -Every compiler warning is a build failure. Keep `*.bench.js` and `*.scale.js` beside the corresponding tests, store baselines in `.local/`, and record a measurement that decides something in the design, beside the decision it settles. +Every compiler warning is a build failure. Keep `*.bench.js` and `*.scale.js` beside the corresponding tests, store baselines in `.sandbox/`, and record a measurement that decides something in the design, beside the decision it settles. ## Documentation and versions diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29c45f7..de77ee3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ You'll need: - PowerShell to run the build scripts. - The .NET SDK pinned in `nuget/global.json`. -DOMQL is written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), which it installs from npm, `@formaui-net/nexo`, at the release `package.json` declares and its lock installs. Its link test reads Nexo's documents at that release's tag from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, so clone it beside this repository under the name the build looks for: +DOMQL is written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), which it installs from npm, `@formaui-net/nexo`, at the release `package.json` declares and its lock installs. Its link test reads Nexo's documents at that release's tag from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, so clone it beside this repository under the name the build looks for: ```sh git clone https://github.com/FormaUI/Nexo.git formaui-net.Nexo @@ -39,16 +39,18 @@ Run the full build from the repository root: | Location | Contents | | --- | --- | | `src/dom/` | DOM evaluation, observations, watches, events, executions and the dispatch table of host calls | +| `src/connections/` | A connection, which carries DOMQL's operations across a boundary as messages | | `src/snapshots/` | Snapshot comparison and updates | | `tests/` | Tests arranged to match the source folders | -| `scripts/` | Bundling scripts | +| `scripts/` | Bundling scripts, and the one that writes the manifest of DOMQL's own module, `npm run manifest` | | `nuget/` | Package project and library guide | | `spec/` | The specification, split by subject, with its index | | `docs/` | The design and the status overview | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | +| `.sandbox/` | Your own work that stays out of the repository, which Git ignores: experiments, notes, scratch and temporary files, and benchmark baselines | -The [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) defines the language and its runtime, and the [DOMQL specification](spec/README.md) the DOM vocabulary, how queries are carried out, and the public API. The [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md) and the [DOMQL design](docs/domql-design.md) set out how each is built. If a change affects either contract, update the relevant document before implementing it. The [status overview](docs/features-status.md) tracks what is implemented, what is being built, and what remains. +The [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) defines the language and its runtime, and the [DOMQL specification](spec/README.md) the DOM vocabulary, how queries are carried out, and the public API. The [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md) and the [DOMQL design](docs/domql-design.md) set out how each is built. If a change affects either contract, update the relevant document before implementing it. The [status overview](docs/features-status.md) tracks what is implemented, what is being built, and what remains. ## Develop a change @@ -80,12 +82,13 @@ The simulated DOM does not calculate layout. Run browser tests from the reposito You can also run `npm run test:browser` from `tests/`, and `npm run test:engines` for the tests run in each engine. -Two details to keep in mind: +Three details to keep in mind: - **Module registration persists.** A test that registers a module needs its own `domql` instance. Call `vi.resetModules()` and import it afresh so tests remain independent of execution order. +- **DOMQL's own module has a manifest.** After a change to its declarations, run `npm run manifest` from the repository root, which writes `src/dom/ModuleManifest.mjs` again; a test fails until it does. - **README examples are tested.** When you change an example in the package guide, update its fixture in `tests/_examples/` and the answer `tests/PackageReadme.test.js` expects. The repository README's examples run as they are written. -For performance changes, run `npm run bench` from `tests/` for simulated-DOM benchmarks and `npm run scale` for Chromium workloads: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers. Name a file to run one workload, as `npm run scale -- dom/OwnedWrites.scale.js`; each reports the machine's load as it ran, its own included, so compare runs made at a low load alone. Compare against a baseline, keep gains that repeat beyond measurement noise, and record a conclusion that decides something in the [design](docs/domql-design.md), beside the decision it settles. Report the memory a change retains apart from what it allocates: a bound can slow a case's allocation and still end growth that outlived disposal, as [D84](docs/decisions.md#d84) did. Benchmarks are separate from the build gate. +For performance changes, run `npm run bench` from `tests/` for simulated-DOM benchmarks and `npm run scale` for Chromium workloads: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers. Name a file to run one workload, as `npm run scale -- dom/OwnedWrites.scale.js`; each reports the machine's load as it ran, its own included, so compare runs made at a low load alone. Compare against a baseline kept in `.sandbox/`, keep gains that repeat beyond measurement noise, and record a conclusion that decides something in the [design](docs/domql-design.md), beside the decision it settles. Report the memory a change retains apart from what it allocates: a bound can slow a case's allocation and still end growth that outlived disposal, as [D84](docs/decisions.md#d84) did. Benchmarks are separate from the build gate. diff --git a/README.md b/README.md index 69ed0ae..69c13c1 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ **A declarative approach to managing the DOM.** -DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). +DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md). -> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.3`, implements DOMQL's specification `1.0.0-preview.1` on Nexo's language `1.0.0-preview.1`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). +> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.3`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). ## Features @@ -144,7 +144,7 @@ A JavaScript callback gives none of this by itself. A restricted JavaScript API, | --- | --- | | [Library guide](nuget/README.md) | Install DOMQL, learn the language by example and use the API | | [DOMQL specification](spec/README.md) | Queries, the DOM's vocabulary, evaluating and watching a query, its results, events, executions, and the API | -| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | The language DOMQL is written in, and its runtime, at the release DOMQL builds against | +| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | The language DOMQL is written in, and its runtime, at the release DOMQL builds against | | [Version history](VERSION-HISTORY.md) | Each version of DOMQL, with the features it added and what it changed | | [Changelog](CHANGELOG.md) | Each release of the packages and what it changed | | [Design](docs/domql-design.md) | How DOMQL is built, and the decisions it did not take | diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index c4403a4..cd253db 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -13,6 +13,70 @@ Each entry says what its version breaks: - **From `1.0.0-beta.1` until the first release candidate,** through the betas and the previews, a decision may be replaced where a demonstrated fault, an ambiguous contract or a measured cost justifies it, whether or not Forma has met it, as [D100](docs/decisions.md#d100) records. A version that breaks what the one before it allowed says, beside each break, how a query, a caller or a module migrates. - **From `1.0.0-rc.1` on,** nothing breaks before 2.0, as [FormaUI Versioning's stages](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/versions.md#stages) promise. + + +## `1.0.0-preview.2` + +*December 1, 2026 · Nexo language `1.0.0-preview.3` · definition format 38* + +```domql +box.layoutSize?.inline // the size layout gives the box along its line, a transform aside; NEXO3001 before, no such member +box.size // the box as it is drawn; watched, DOMQL3003 unless the watch accepts partial observation, accepted before though a transform went unheard +field.autofilled // watched: follows an animation the page's style starts on the field as it is filled or emptied; heard only input, change and reset before +root.first("a") // NEXO2018, now saying that a binding named root is read as ~root, as ~root.first("a") reads it +``` + +```js +await domql.query('box.layoutSize', { box }).evaluateAsync(); // { inline: 200, block: 50 } under scale(0.5), as laid out, once the browser reports it +domql.query('box.size', { box }).evaluate(); // { width: 100, height: 25 } under scale(0.5), as drawn, as before +domql.query('box.size', { box }).watch(); // DOMQL3003; a watch that missed every transform before +domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // the box as drawn, a transform missed until another change is observed +``` + +```js +{ name: 'destinations', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'navigation', result: 'Request', answers: 'String?' } // an event source answered; NEXO4030 before + +const destination = await deliver('destinations', request); // the first subscription's answer, as String?; undefined before, whatever its handler returned +``` + +```js +const manifest = domql.prepare([{ name: 'Charts', contents }], { scripts: [{ script: 'import Charts\npanel:palette', types: { panel: 'Domql.Element' } }] }); // Charts and its query checked once; a TypeError before, no such function + +domql.registerModule(domql.createModule('Charts', contents, { manifest }), { manifest }); // created and registered without the checks the manifest records; each option left unread before +domql.query('import Charts\npanel:palette', { panel }, { manifest }); // read from the manifest, neither parsed nor resolved; NEXO2048 before, an option the bindings take none of +``` + +```js +const connection = domql.connect(deliveries => host.receiveAsync(deliveries)); // a connection across a boundary; a TypeError before, no such function + +await connection.requestAsync([{ request: 'watch', handle: 1, owner: 'panel', query: { key: 'n', text: 'panel.children.count' }, bindings: { panel } }]); // [{ snapshot: 3 }] +``` + +DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, which Nexo's release `1.0.0-preview.4` carries, as [D114](docs/decisions.md#d114) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-3) sets out its own changes by version; the one below is the one a query meets. + +**Vocabulary** + +- [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box or as a box of no size, 0 by 0, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) and [D117](docs/decisions.md#d117) record. +- [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. +- [`autofilled`](spec/vocabulary.md#state-element-autofilled) observes `animationstart` and `animationcancel` on its field too, so a page whose style starts an animation on a field as the browser fills or empties it is followed, as [D112](docs/decisions.md#d112) records. + +**Queries** + +- A `root` written where no object expression encloses it, NEXO2018, and one read other than through its fields, NEXO3012 and NEXO3017, say that a binding named root is read as `~root`. + +**Modules** + +- [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. +- [Modules and queries are prepared ahead of time](spec/vocabulary.md#extension-modules-manifests): `domql.prepare(modules, { scripts })` checks modules, as `domql.createModule` takes them, registered after DOMQL's own, and resolves queries, as `domql.query` takes them, answering Nexo's manifest. `domql.createModule`, `domql.registerModule`, `domql.registerModuleLoader` and `domql.query` take it as `manifest`, and an operation run directly beside `types`, each sparing the checks it records, as [D116](docs/decisions.md#d116) records. A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, and a loader's options that are no object with `DOMQL2013`. + +**Connections** + +- [A connection](spec/connections.md), `domql.connect(deliver)`, carries this instance's operations across a boundary as messages. A host's requests cross in batches, each answered once its task ends, and each task's deliveries cross together: a watch's paced by the acknowledgment of the one before it, its change sets joined meanwhile, and an event behind nothing. A query crosses as its text once, and by its key after. `DOMQL2022` to `DOMQL2025` refuse what a connection can't carry out, `DOMQL5026` closes one whose host acknowledges nothing, and `DOMQL5027` answers one that has closed, as [D118](docs/decisions.md#d118) records. + +**Breaking:** + +- A watch of `size` is refused unless it accepts partial observation, DOMQL3003. Watch `layoutSize` where the size as laid out is what it needs, reading `inline` and `block` for `width` and `height` along a horizontal line, or pass `acceptPartialObservation: true` to keep the box as drawn. + ## `1.0.0-preview.1` @@ -75,13 +139,13 @@ const updates = { changes: 'observable', reads: 'maintained', observations: [{ t typeOf: value => undefined // NEXO5002 as a binding asks it; answer null ``` -DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and `1.0.0-beta.41`, as [D76](docs/decisions.md#d76), [D87](docs/decisions.md#d87) and [D108](docs/decisions.md#d108) record, and follows its rule that a property names what its receiver is, has or is in, and a function does work: DOMQL's states are properties, as D87 records, and its executions are named by their verbs, as [D88](docs/decisions.md#d88) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/LANGUAGE-HISTORY.md#v1-0-0-preview-1) sets out its own changes by version; those below are the ones a query, a caller and a module meet. +DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and `1.0.0-beta.41`, as [D76](docs/decisions.md#d76), [D87](docs/decisions.md#d87) and [D108](docs/decisions.md#d108) record, and follows its rule that a property names what its receiver is, has or is in, and a function does work: DOMQL's states are properties, as D87 records, and its executions are named by their verbs, as [D88](docs/decisions.md#d88) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-1) sets out its own changes by version; those below are the ones a query, a caller and a module meet. **Vocabulary** - [Focus is followed into open shadow roots](spec/vocabulary.md#observations-types): `focused`, `focusWithin`, `activeElement` and a selector testing focus report a move between two elements of one open shadow root, which they missed, since its events reach no further than the root, and the focused element's removal, which Firefox and WebKit fire no event for, as [D90](docs/decisions.md#d90) records. - [`scroll`'s offset](spec/vocabulary.md#property-element-scroll) runs as the box's style says, a reversed flex container's included, and stays within its range, so an elastic overscroll past either end reads as that end. -- [States](spec/vocabulary.md#states) are Boolean properties, read without a call, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: an element's `disabled`, `readonly`, `textEditable`, `focusWithin`, `displayed`, `focusable`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible`, and the ARIA view's `checked` and `disabled`, each a function before. +- [States](spec/vocabulary.md#states) are Boolean properties, read without a call, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: an element's `disabled`, `readonly`, `textEditable`, `focusWithin`, `displayed`, `focusable`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible`, and the ARIA view's `checked` and `disabled`, each a function before. - Five states take new names as they become properties: an element's `hover` and `focus` are `hovered` and `focused`, the document's `focus` is `focused`, and the window's `share` and `clipboard` are `canShare` and `hasClipboard`. - A state is read through its module as before, `Domql.checked(it)`, and filtered by with a body, `rows.where(it.checked)`; a reference to one, `rows.where(Domql.checked)`, is refused (NEXO3076), since only a function has one. @@ -90,7 +154,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and - Nexo's own members that make a value of their receiver are functions: a number's `round()`, `floor()`, `ceiling()`, `truncate()` and `abs()`, a text's `trim()`, `lowercase()` and `uppercase()`, and a list's `reverse()`, `distinct()` and `flatten()`, each a property before. - A letter right after a number makes one invalid token, NEXO1000, so `1else` is refused, where it read as `1` and `else`. - A number is written in hexadecimal, octal or binary too, `0xFF`, `0o17` and `0b1010`, and a `_` may stand between two digits of any number, `1_000_000`, where `0xFF` read as `0` and a member written without its dot, NEXO1011. -- [`and` and `or`](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#logical-expressions-negations-and-groups-type) share a type only where their value is used: `it.attached and "here" or "away"` is a `String`, where it was refused. +- [`and` and `or`](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/expressions.md#logical-expressions-negations-and-groups-type) share a type only where their value is used: `it.attached and "here" or "away"` is a `String`, where it was refused. - A conversion of a value of `Any` converts by the type the value turns out to be, failing with NEXO5053 where nothing converts it, where it was refused at resolution. - A computed name through a namespace reads as it does after `@`: `Domql.["window"]` is `Domql.window`. - [A query declares its bindings' types](spec/queries.md#making-a-query-declared-types), `domql.query(text, bindings, { types })`, capturing data as a module's structured type, a map as a dictionary, where every binding was typed from its value. @@ -116,7 +180,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and **Results** - [A selection](spec/queries.md#selecting-a-result) steps into a dictionary's `entries` and a pair's `key` and `value`, the form [a result holds them](spec/results.md#results-collections) in, where a path into either was refused. -- `domql.format` writes a negated number literal as the number, `-(-1)` as `1`, a call's arguments after a block's `end` on lines of their own, and an empty line between a body's last local and its `return`, at every level, as Nexo's [canonical bodies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/definition.md#bodies-definition-and-canonical-text) set out. +- `domql.format` writes a negated number literal as the number, `-(-1)` as `1`, a call's arguments after a block's `end` on lines of their own, and an empty line between a body's last local and its `return`, at every level, as Nexo's [canonical bodies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/definition.md#bodies-definition-and-canonical-text) set out. - Data a result holds nesting deeper than 1,000 levels is refused, NEXO5052, and a `sum` or a `sequence` no finite number holds, NEXO5020. **Modules** @@ -124,7 +188,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and - [A delivery inside a handler](spec/behaviors.md#behaviors-occurrences) reaches every subscription before the one around it goes on, so a later subscription hears it first, and [an acknowledgment](spec/behaviors.md#behaviors-acknowledgment) rejects at the first failure while others may still be applying the occurrence, as [D93](docs/decisions.md#d93) records; neither changed, the specification promised more. - [A kept value beside an outside writer](spec/vocabulary.md#execution-element-owned-writes-yielding) is judged by a heuristic, and [a committed position](spec/vocabulary.md#execution-element-owned-writes-framework) is let go of once its host confirms the render, not the occurrence's acknowledgment, as [D94](docs/decisions.md#d94) records. - [A transient measurement's read](spec/vocabulary.md#extension-modules-environment) is synchronous and writes nothing, and [a module's state per document](spec/vocabulary.md#extension-modules-state-per-document) is one for each copy of its code, as [D98](docs/decisions.md#d98) and [D99](docs/decisions.md#d99) record. -- [A member reading maintained values](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md) declares a result that can be null, NEXO4071, since it reads as null until its first sample arrives. +- [A member reading maintained values](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md) declares a result that can be null, NEXO4071, since it reads as null until its first sample arrives. - A module's `typeOf` answering nothing is a fault, NEXO5002. - A fixed parameter is required and takes no default, NEXO4072, and an observation takes no expression or predicate parameter, NEXO4055. - A module error names a declaration only by a name that is a string. @@ -645,7 +709,7 @@ DOMQL moves to Nexo's language `1.0.0-beta.15`, which settles what Nexo's status - **Membership compares by key equality alone.** `contains`, `indexOf`, `distinct` and `distinctBy` take numbers, strings, Booleans, references and null, so a list of elements works as before, and one of objects, lists or values of `Any` is refused (NEXO3083), where it was compared by identity. - **A result path is checked wherever it is given,** so `select` refuses a malformed path as it did, and steps into an object's own fields and a list's items alone. - **A module's declarations name Nexo's own types qualified,** as `Nexo.Number`, where the module declares a type of that name. -- **Conditions Nexo told apart by message have codes of their own,** NEXO5043 to NEXO5050 among them, as [Nexo's language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/LANGUAGE-HISTORY.md) records. +- **Conditions Nexo told apart by message have codes of their own,** NEXO5043 to NEXO5050 among them, as [Nexo's language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md) records. **Breaking:** a query that tested membership in a list of objects, lists or values of `Any` is refused; test a key field instead, as `items.any(it.id == id)`. diff --git a/docs/decisions.md b/docs/decisions.md index 94b21da..ea4fe28 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -409,7 +409,7 @@ Each entry is one of three kinds: - **Kind:** Contract. - **Decision:** `on(type, options?)` takes a second, optional positional argument, a `Listening { capture }`, so `on("click", { capture = true })` listens as the event is captured on its way to its target, and `on("click")` as before, at the target and as it bubbles. It listens passively either way, for observing alone, as [D2](#d2) has it. - **Why:** - - A member's argument form is positional or options, never both, and `on("click")` keeps its form, so the option is a structured value its parameter constructs from the object expression written there, as Nexo's [constructing a structure](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#types-constructing-a-structure) sets out. + - A member's argument form is positional or options, never both, and `on("click")` keeps its form, so the option is a structured value its parameter constructs from the object expression written there, as Nexo's [constructing a structure](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#types-constructing-a-structure) sets out. - A structure leaves room for another listening option without changing the argument form, which would break every subscription. - Listening in the capture phase at an ancestor observes an event before any listener nearer its target runs, so a listener there that stops it hides nothing. - **Declined:** @@ -705,6 +705,7 @@ Each entry is one of three kinds: - **Decision:** The C# half (A1) is out of the current work until the owner designs it. The design's section and the status's outline stay as where that design starts. Editor tooling, which is Nexo's, waits for Nexo's design too. - **Why:** The outline names an API and an adapter, but leaves open what a host with a transport of its own takes from it, how a result maps onto records a field discriminates, and how text is checked without a parser in .NET. Those are the owner's to design. - **Declined:** Building it from the outline, which would settle those questions without the owner. +- **Replaced** by [D119](#d119), as the owner directed that DOMQL's transport is the one its hosts use. @@ -930,7 +931,7 @@ Each entry is one of three kinds: *November 2, 2026* - **Kind:** Contract. -- **Decision:** A host call's function argument reaches its implementation as a kept function, which Nexo's language `1.0.0-beta.20` designed for DOMQL ([C13](features-status.md#planned-extension-contract)), as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d49) record. DOMQL ends it as the execution keeping it ends: a continuous execution's instance ending or accepting other arguments, a once execution's answer settling, a subscription ending. Each call counts as an evaluation of the instance's, so what it reads reads alone. +- **Decision:** A host call's function argument reaches its implementation as a kept function, which Nexo's language `1.0.0-beta.20` designed for DOMQL ([C13](features-status.md#planned-extension-contract)), as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d49) record. DOMQL ends it as the execution keeping it ends: a continuous execution's instance ending or accepting other arguments, a once execution's answer settling, a subscription ending. Each call counts as an evaluation of the instance's, so what it reads reads alone. - **Why:** - A running behavior keeps a test of what it hears, as a route's condition, and calls it inside each event's dispatch; data alone left every such test a protocol of the module's own. - DOMQL alone knows when what it started ends, so it disposes each prepared call then, and a call after that fails with Nexo's code, where it would read a page the caller has moved on from. @@ -1156,7 +1157,7 @@ Each entry is one of three kinds: - **Why:** - Every planned capability is implemented or declined but A1 and A5's queue. What callers use today, the JavaScript half, is complete. - The C# half is a client of that contract. It maps results onto records, drives the operations the JavaScript half offers, and carries across the boundary the order that half already keeps ([D69](#d69)). The questions D46 leaves open are its own: a host's own transport, records a field discriminates, and checking text without a parser in .NET. Should its design need more of the JavaScript half, that is an addition, which a beta allows. - - Nexo holds the same stance: it is in its beta, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d27) record, while its tooling waits for its design, as its [status](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#tooling) records. + - Nexo holds the same stance: it is in its beta, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d27) record, while its tooling waits for its design, as its [status](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#tooling) records. - A caller reads `domql.info.versions` to learn what it can rely on. A beta runtime implementing an alpha specification would promise a stability its contract's version denies. - **Declined:** - Waiting for the C# half. Its design has not started, and the JavaScript half would go without a promise until it ends. @@ -1190,7 +1191,7 @@ Each entry is one of three kinds: - **Kind:** Process. - **Decision:** `nexo.release` pins a release of Nexo, `1.0.0-beta.1` first, and the build extracts the tree of its tag, `v1.0.0-beta.1`, where `nexo.commit` pinned a commit. Every link into Nexo names that tag, so the links move with the pin, `main` among the links it replaces. A link to another commit is a record of the past. - **Why:** - - Nexo now advances its language once per release and cuts each release as a signed tag, as its [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d66) records, so a release is what DOMQL can rely on. + - Nexo now advances its language once per release and cuts each release as a signed tag, as its [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d66) records, so a release is what DOMQL can rely on. - A commit pin named one fix, and moving it rewrote a hash in 81 places across 21 documents. - A link to Nexo's `main` changes under DOMQL's documents, unseen. - **Declined:** Waiting for Nexo's packages on a registry, which would keep DOMQL on a commit until they are published; the packages remain the next step, as [consuming the language](features-status.md#consuming-nexo) sets out. @@ -1220,7 +1221,7 @@ Each entry is one of three kinds: - A release is a signed tag, `v` and its version, on the commit that dates its changelog entry. Its packages are published from that tag. - `1.0.0-beta.2` is the first version collected so. The versions before it stand as they were declared. - **Why:** - - A version a caller relies on is one a release fixes, and DOMQL's version history and Nexo's language history now follow one rule, as Nexo's [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d66) records. + - A version a caller relies on is one a release fixes, and DOMQL's version history and Nexo's language history now follow one rule, as Nexo's [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d66) records. - It narrows [D75](#d75)'s rule that each version advances for its own reason: the specification version's reason is now a release whose contract changed. - **Declined:** Dating a release when its packages are published, which leaves a caller nothing to pin until a registry holds them; DOMQL's packages wait for Nexo's anyway. @@ -1236,7 +1237,7 @@ Each entry is one of three kinds: - Until then, a change fixes, explains, speeds up or documents, or meets a requirement. A feature lands only where Forma's scripts need it, as a decision records. - **Why:** - The beta promised no breaking redesign, but said nothing about when breaks end. - - DOMQL's contract holds Nexo's language, so it can be no more settled than Nexo, which waits for its own 1.0 as its [D67](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d67) records. + - DOMQL's contract holds Nexo's language, so it can be no more settled than Nexo, which waits for its own 1.0 as its [D67](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d67) records. - The planned capabilities came from reading Forma's scripts, so running them is the test of DOMQL's contract. - **Declined:** - Making the C# half a requirement, which would hold 1.0 for a design the owner hasn't decided is needed. @@ -1252,7 +1253,7 @@ Each entry is one of three kinds: - **Decision:** From `1.0.0-beta.1` on, each entry of the [version history](../VERSION-HISTORY.md) leads with examples of what its version changed: a query's in a `domql` block, a caller's or a module's in a `js` block. Each line's comment says what it does at that version and what it did before. The entry's list follows them as the reference. Each example is run at its version when its entry is written; the gate doesn't run them. - **Why:** - The list states each change precisely, but a caller migrating needs the line to write. - - Nexo's language history follows the same rule, as its [D70](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d70) records, and running its examples found what `1.0.0-beta.2`'s entry here misstated: a chain's limit counts terms, and a grouped chain is written `a + b + (c + d)`. + - Nexo's language history follows the same rule, as its [D70](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d70) records, and running its examples found what `1.0.0-beta.2`'s entry here misstated: a chain's limit counts terms, and a grouped chain is written `a + b + (c + d)`. - **Declined:** Running the history's examples in the gate, which would make a record of the past change with later versions. @@ -1262,7 +1263,7 @@ Each entry is one of three kinds: *November 3, 2026* - **Kind:** Contract. -- **Decision:** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, which Nexo's `createBindings` binds as its [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/bindings.md#runtime-bindings) do. Every binding made from the query keeps the types, `with`'s, an execution's update and a reaction's, and the query keeps a copy of them. +- **Decision:** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, which Nexo's `createBindings` binds as its [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/bindings.md#runtime-bindings) do. Every binding made from the query keeps the types, `with`'s, an execution's update and a reaction's, and the query keeps a copy of them. - **Why:** - It is the feature the 1.0 freeze allows, as [D80](#d80) records: replacing Forma's scripts needs it. Forma's input router binds its routes as `List` and its overrides as a dictionary of structures, and its culture coordinator binds its starting state as a structure. Data typed from itself is of no module's type, so each was refused (NEXO3042), and routes whose families carry different fields could not be bound at all. - Nexo already captures data as a declared type, a map as a dictionary and a set as a list, and checks it, so DOMQL passes the types through and adds no rule of its own. @@ -1344,7 +1345,7 @@ Each entry is one of three kinds: - **Kind:** Contract, approved by the owner. - **Decision:** - - DOMQL moves to Nexo's language `1.0.0-beta.41`, whose release is Nexo's `1.0.0-beta.2`, and follows its rule that a property names what its receiver is, has or is in, and a function does work, as Nexo's [D77](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d77) records. + - DOMQL moves to Nexo's language `1.0.0-beta.41`, whose release is Nexo's `1.0.0-beta.2`, and follows its rule that a property names what its receiver is, has or is in, and a function does work, as Nexo's [D77](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d77) records. - Every state DOMQL declares is a Boolean property, read without a call, `it.checked`: an element's `disabled`, `readonly`, `textEditable`, `focused`, `focusWithin`, `displayed`, `focusable`, `hovered`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible` and `focused`, the window's `canShare` and `hasClipboard`, and the ARIA view's `checked` and `disabled`. Each was a Boolean function. - Five take new names as they become properties: @@ -1655,7 +1656,7 @@ Each entry is one of three kinds: *November 5, 2026* - **Kind:** Contract, approved. -- **Decision:** `nexo.release` pins Nexo's release `1.0.0-preview.1`, of language `1.0.0-preview.1`, and DOMQL's documents link to Nexo's at its tag. DOMQL's `1.0.0-preview.1` describes DOMQL on that language, so `domql.format` writes an empty line between a body's last local and its `return`, as Nexo's [D83](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d83) records. +- **Decision:** `nexo.release` pins Nexo's release `1.0.0-preview.1`, of language `1.0.0-preview.1`, and DOMQL's documents link to Nexo's at its tag. DOMQL's `1.0.0-preview.1` describes DOMQL on that language, so `domql.format` writes an empty line between a body's last local and its `return`, as Nexo's [D83](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d83) records. - **Why:** - DOMQL's first release runs on a released Nexo, and Nexo's first preview is its newest release. - The language changed nothing a query relies on: a body's canonical text changes, and reads back as the same definition. @@ -1697,3 +1698,194 @@ Each entry is one of three kinds: - Publishing an npm package of `1.0.0-preview.1` from another commit, which would give a fixed release a package its full gate never built. - Waiting for the NuGet package to depend on Nexo's as well, which changes how a .NET application serves the language, and which [consuming the language](features-status.md#consuming-nexo) plans on its own. - Moving npm's `latest` to a preview, so the package's page shows it rather than the deprecated placeholder that holds `latest` until 1.0: a pre-release would become the default install, which [FormaUI Versioning's publication](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/packages.md#publication) forbids. npm's page shows the version `latest` names, so it shows the placeholder's deprecation, as `npm install @formaui-net/domql` warns, naming `@preview`. + + + +## D111 — `size` is the box as drawn, and `layoutSize` the box as laid out + +*November 30, 2026* + +- **Kind:** Contract, correcting a fault; a feature Forma's scripts need, as [what 1.0 requires](features-status.md#what-1-0-requires) allows. +- **Decision:** + - `size` stays the border box as it is drawn, transforms applied, as `rect` measures it, and is partly observable. It misses a transform or an animation, its own or an ancestor's, and the size of an inline box. + - `layoutSize`, a new member, is the border box as layout gives it, along the writing mode's axes: `LogicalSize { inline, block }`. It reads a maintained observation of its own, `layoutSize`, which samples the browser's resize observation, so it is observable. It is null where the element is laid out as no one box, or, as [D117](#d117) records, as a box of no size, and pending until the browser's first report. Chromium, Firefox and WebKit each make one for a box of any size, a hidden or a detached element included, as they lay the page out, so an element of a hidden document waits until the document is shown, as one `intersects` reads does. +- **Why:** + - `size` read `getClientRects()`, the box as drawn, but its one observation was the resize observer, which reports the box as laid out. A transform changed `size` with nothing observing it, while the specification called it observable. In Chromium, a watch of `size` stayed at 200×50 after `scale(0.5)`, where a refresh read 100×25. + - Forma's stepper reads a box's size from C# to decide whether its steps' names fit. It needs the size layout gives the box, along its writing mode, which no member answered. + - A maintained member waits for the browser's first report, so a watch's first snapshot is the size as laid out. A script that read the box as drawn first, then corrected it, sent a wrong size and a second crossing under a transform. +- **Breaks:** a watch of `size` is refused unless it accepts partial observation (`DOMQL3003`). It migrates by accepting partial observation, or by watching `layoutSize`, where the size as laid out is what it needs. +- **Declined:** + - Making `size` the box as laid out. A synchronous read can't give the untransformed, fractional border box for every box, and `size` would then disagree with `rect`. + - A maintained `size`. `evaluate` would answer null for it until the browser's first report, breaking every synchronous read of it. + + + +## D112 — `autofilled` follows an animation the page starts on a filled field + +*November 30, 2026* + +- **Kind:** Contract, extending [D17](#d17); a feature Forma's scripts need. +- **Decision:** `autofilled` also observes `animationstart` and `animationcancel` on its field. A page whose style starts an animation on a field as the browser fills or empties it, as a rule for `:autofill` naming one does, is then followed. It stays partly observable: a fill with no event and no such animation is still missed. +- **Why:** + - Forma now watches whether a field is autofilled from C#, to render its filled state. It relies on its own stylesheet's animation on `:autofill`, the one signal a browser gives for a fill it makes as the page loads. + - The observation reads only what the page's own style already does, so DOMQL still writes no stylesheet, as D17 requires. In Node, a watch of a field whose `:autofill` match changed with each animation reported `[false, true, false]`. +- **Declined:** an observation of DOMQL's own that writes the animation rule into the page, which D17 declined. + + + +## D113 — An event source can be answered + +*November 30, 2026* + +- **Kind:** Contract, extending [D50](#d50); a feature Forma's scripts need. +- **Decision:** + - An event source may declare `answers`, the type of an answer, written as a declared binding's type is. DOMQL keeps it beside the source's request kind and gives Nexo the declaration without it. + - Each subscription's handler answers an occurrence with what it returns, or with what the promise it returns fulfils with. + - `deliver`'s promise fulfils, once every subscription has applied the occurrence, with the first subscription's answer, captured as the declared type through DOMQL's registry, as a binding of that type is. The other subscriptions' answers are not taken, so a subscription that only observes, answering nothing, fails no delivery. + - An answer the type refuses rejects with `DOMQL5025`, located at the subscription, and goes to the window's error reporting. `answers` on anything but an event source, or other than a string, is refused with `DOMQL4016` as the module is created. + - A notation that names no type is refused as the first answer is captured, with `DOMQL5025`: Nexo reads a binding's type only where a value is bound, so creating the module checks no more than that it is a string. +- **Why:** + - Forma's culture coordinator now asks .NET for a page's address in a culture before it navigates, and waits for the value. As an occurrence and a command answering it, that was a second crossing and a correlation of its own. As one answered delivery, it is the one round trip it is today. + - The acknowledgment already settled as the handler's promise did; carrying its value adds no new path, only the value. + - The first subscription's answer is deterministic, since subscriptions are called in the order they subscribed. +- **Declined:** + - A command the subscriber sends back. It needs an identity for each question, and a second crossing. + - Every subscription's answer, as a list. No caller asks several subscribers one question, and a list would make every answer's type a list. + - An untyped answer. A behavior would check what .NET sends itself, where DOMQL captures every other value that crosses into a module by its declared type. + + + +## D114 — DOMQL builds against Nexo `1.0.0-preview.4` + +*November 30, 2026* + +- **Kind:** Contract, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** DOMQL depends on `@formaui-net/nexo` at `^1.0.0-preview.4`, which its lock installs, and its documents link to Nexo's at that tag. DOMQL's `1.0.0-preview.2` describes DOMQL on Nexo's language `1.0.0-preview.3`, which `domql.info.versions.language` reports. +- **Why:** + - Nexo's `1.0.0-preview.3` and `1.0.0-preview.4` check a module, its registration and a script once, ahead of time, and record the checks in a manifest a host keeps. DOMQL's start can't read one from a release without them. + - The language changes nothing a query relies on: a refusal of `root` says more, and the rest is Nexo's runtime, which DOMQL uses as a host. +- **Declined:** Waiting for Nexo's next language. Nothing DOMQL needs is waiting there. + + + +## D115 — DOMQL creates its own module under a manifest its build makes + +*November 30, 2026* + +- **Kind:** Implementation, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** + - DOMQL's sources hold `ModuleManifest`, the manifest `nexo.prepare` makes of DOMQL's own module, of the contents its dispatch table gives Nexo. + - `scripts/module-manifest.mjs` writes it, run as `npm run manifest`, and a test fails while it differs from the one the module's declarations give. + - DOMQL creates its module and its registry under it as it is imported. +- **Why:** + - Every start made the checks of DOMQL's module and of its registration, which its declarations alone decide, so its build can make them once. + - In Chromium, cold, over four alternating rounds of 11 runs, DOMQL's import took about 33.5 ms where it took 43. The first query's resolution and the first registrations took about 2 ms more, as Nexo resolves notations as they are first read. A start took about 50.5 ms where it took 58. + - Nexo reads a manifest of another implementation as holding no module, so a host that installs a later Nexo beside DOMQL's npm package starts as it did, every check made. +- **Declined:** + - Writing the manifest as the bundle is built. The npm package ships the sources, which must hold it. + - Preparing the module at import. It makes the very checks it would save. + + + +## D116 — A host prepares its modules and queries ahead of time + +*November 30, 2026* + +- **Kind:** Contract; a feature Forma's scripts need, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** + - `domql.prepare(modules, options)` answers the manifest Nexo makes of the modules given, as `domql.createModule` takes them, registered after DOMQL's own, and of the queries `options.scripts` gives, as `domql.query` takes them, each text read with `Domql` supplied. + - `domql.createModule`, `domql.registerModule` and `domql.registerModuleLoader` take Nexo's options, `manifest`, and give them to Nexo as they are. + - `domql.query` takes `manifest` beside `types`, reads its text from it and its resolutions, and every query `with` makes keeps it. An operation run directly takes it beside `types`. + - A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, since `domql.query` supplies `Domql` and reads none. `prepare` refuses a module declaring observation targets with `DOMQL4008`, as `registerModule` does. +- **Why:** + - Forma's scripts start on every page, and replacing them asks DOMQL to start as fast. Once DOMQL's own module is prepared ([D115](#d115)), a host's modules and its first queries are most of what a start checks. + - In Chromium, cold, over four alternating rounds of 11 runs, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4: 8.8 ms after DOMQL's import, where it was 17. + - The manifest is Nexo's, under Nexo's name, so a host reads one contract. DOMQL adds only what it supplies: its own module first, and the import `Domql`. +- **Declined:** + - DOMQL keeping the manifests it is given, so a query names none. A page holding several libraries' manifests would leave DOMQL to choose among them. + - Naming the option `moduleManifest`, as DOMQL's own module's is named. DOMQL gives the option to Nexo as it is, under Nexo's name. + - Compiling prepared queries to JavaScript. That waits for a measured need, as the start-up's direction set. + + + +## D117 — A box of no size has no `layoutSize` + +*November 30, 2026* + +- **Kind:** Contract, correcting a fault in [D111](#d111) before its release. +- **Decision:** `layoutSize` is null for a box of no size, 0 by 0, as it is where the element is laid out as no one box. +- **Why:** + - A resize observer reports a change of size alone, and measures a box of no size as it measures no box. A box of no size that is hidden, detached, made inline, or shown again resizes nothing it reports. + - In Chromium, a watch of an empty, absolutely positioned element stayed at `{ inline: 0, block: 0 }` after `display: none` and after it was detached, where a new evaluation read null. + - Read alike, the two are no change, so `layoutSize` stays observable, as D111 needs it to be. +- **Declined:** + - Partly observable `layoutSize`. Every watch of it would have to accept partial observation, which is what D111 made it to spare. + - Observing styles and attachment beside the resize observer. A stylesheet's rule hides a box with no observer reporting it, and observing every mutation of the tree would cost every watch of a size. + + + +## D118 — A connection carries DOMQL across a boundary + +*December 1, 2026* + +- **Kind:** Contract, meeting [what 1.0 requires](features-status.md#what-1-0-requires) of the C# half, by the owner's direction that DOMQL's transport is the one its hosts use. +- **Decision:** + - `domql.connect(deliver)` opens a [connection](../spec/connections.md). A host sends requests in batches, and each batch is answered once the task that carried it out has ended. + - A request that settles in that task answers final: a watch with its snapshot, an execution or an evaluation with its value. One still waiting answers pending, and its result is delivered. + - The deliveries of one task cross in one call. A watch's next delivery waits for the acknowledgment of its last, what arises meanwhile joined. An event never waits. + - A query crosses as its text once, and by its key after. Owners are strings, numbers or null, and generations are the host's. + - Where earlier batches have left 4,096 deliveries unacknowledged, the next batch closes the connection with `DOMQL5026`; one task of many deliveries crosses whole. +- **Why:** + - A host that calls once for each operation pays a call for each registration of a render. One batch for a turn pays one, whatever it starts. + - Answering at the task's end carries each watch's first snapshot, and each execution that settles at once, in the batch's own answer, with no call back. + - An event behind an acknowledgment was overtaken by a click ([D69](#d69)). Change sets compose ([D65](#d65)), so a watch that waits loses nothing. + - A host's message holds no object twice, so an owner it can name again is a string or a number. + - A host that acknowledges nothing would otherwise hold every occurrence. Closing fails explicitly, as A5 asks. +- **Declined:** + - A batch answered once every request settles. A slow execution would hold every watch's first snapshot. + - Every result as a delivery. An execution that settles at once would take two calls. + - A reference for each operation, which the host disposes in a call of its own. + + + +## D119 — The .NET half is DOMQL's own host of a connection + +*December 1, 2026* + +- **Moved** to [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, by [D120](#d120), whose records hold it as their D1. +- **Kind:** Contract, replacing [D46](#d46) by the owner's direction that DOMQL's transport is the one its hosts use. +- **Decision:** + - The .NET half ships in the NuGet package. `AddDomql` registers one `DomqlConnection` for each scope, through its `IJSRuntime`. + - Each turn's requests cross in one call, as the turn ends on its synchronization context. + - A watch keeps its copy as JSON, applies each change set by DOMQL's rules before it acknowledges the batch, and calls its handler after, one call at a time, with the latest result. + - An event's handler completes before its batch is acknowledged, and its answer answers the event source. + - A query maps its result onto a type through the serializer: source-generated type information, the serializer's options, or the JSON itself. + - Beyond 16 KB, a batch of deliveries crosses as a stream. `RefreshAsync` refreshes every watch once a host's connection to the browser resumes. +- **Why:** + - D46 left three questions to the owner's design: + - **A host with a transport of its own.** The owner's direction answers it: DOMQL's is the transport. + - **Records a field discriminates.** The serializer's polymorphism reads them, by the field the query names first. + - **Text checked without a parser in .NET.** The browser checks it, as the first request makes it there. A host's build checks its queries ahead of time with `domql.prepare` ([D116](#d116)). + - Acknowledging once a change set is applied keeps a slow handler from holding the next one, and no handler sees a copy partly applied. + - The conformance corpus, `tests/_conformance/change-sets.json`, holds each case's previous result, its change set and the result they give. DOMQL's JavaScript applier and the .NET half's pass all 19. + - A delivery may reach .NET before its request's answer, so a watch holds its deliveries until its answer arrives. +- **Declined:** + - `TryQuery`, checking text in .NET. A second parser would have to agree with Nexo's at every release. + - Acknowledging a watch's change once its handler completes. A slow handler would hold every change after it. + - A reconnection hook in the package. It would tie the package to one way of hosting .NET; `RefreshAsync` is the host's to call. + + + +## D120 — The .NET half is a project of its own + +*December 1, 2026* + +- **Kind:** Process, by the owner's direction. +- **Decision:** + - The .NET half moves to [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a repository of its own, with its own solution, workspace, gate, records and package, `formaui-net.DOMQL.NET`. Its types keep the namespace `Domql`. + - DOMQL keeps the [connection](../spec/connections.md), which any host across a boundary speaks, and the change sets' conformance corpus, which is part of its contract and which DOMQL.NET's tests read. + - DOMQL's NuGet package goes back to the bundle alone, with no dependency on Microsoft.JSInterop, and its gate runs no C# tests. The codes the .NET half reports, `DOMQL5028` to `DOMQL5030`, stay reserved for it. +- **Why:** + - DOMQL is a JavaScript library. Its gate, its package and its records had grown a .NET project, a C# test step and a dependency a JavaScript host never uses. + - The .NET half versions apart from DOMQL: a change to its API is no change to DOMQL's contract. +- **Declined:** Moving the connection too. DOMQL would keep no API for a host across a boundary, and DOMQL.NET would reach into DOMQL's internals. diff --git a/docs/domql-design.md b/docs/domql-design.md index fa15934..331e2dd 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -1,6 +1,6 @@ -# DOMQL Design v1.0.0-preview.1 +# DOMQL Design v1.0.0-preview.2 -The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.1` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. +The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.2` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. In this document: @@ -10,7 +10,7 @@ In this document: 4. [Watching](#watching) 5. [Comparing and patching](#comparing-and-patching) 6. [Host calls and their operations](#host-calls-and-their-operations) -7. [The C# half](#the-c-half) +7. [Connections](#connections) 8. [Decisions not taken](#decisions-not-taken) ## Architecture @@ -21,7 +21,7 @@ DOMQL is Nexo's host. It registers its module in a Nexo registry beside the modu | --- | --- | --- | | Entry point | Makes query objects from text or a definition, keeps their resolutions, registers modules, and composes the parts below into the public API | `domql.js` | | Query objects | A request's definition and bindings, through which every operation on it is carried out | `DomqlQuery` | -| The module | DOMQL's declarations, its types with their members within them, its recognition of the DOM's values, the implementations of its members and of its executions, the targets its owned writes hold, and the functions that start its observations, with what a selector reads | `BrowserVocabularyDeclarations`, `BrowserVocabularyImplementations`, `BrowserExecutionImplementations`, `OwnedWrites`, `BrowserObservationImplementations`, `Selectors`, `BrowserModule` | +| The module | DOMQL's declarations, the manifest Nexo makes of them, its types with their members within them, its recognition of the DOM's values, the implementations of its members and of its executions, the targets its owned writes hold, and the functions that start its observations, with what a selector reads | `BrowserVocabularyDeclarations`, `BrowserVocabularyImplementations`, `BrowserExecutionImplementations`, `OwnedWrites`, `BrowserObservationImplementations`, `Selectors`, `BrowserModule`, `ModuleManifest` | | Evaluation | Nexo's evaluator under hooks that record what an evaluation reads and hold the sessions that keep it observed | `QueryEvaluator`, `QueryEvaluation` | | Observations | Sessions on shared observations, each observation started on its first session and stopped with its last, and the mutation observers of DOMQL's own, which a transient measurement drains | `Observations`, `ObservationSession`, `SessionCache`, `MutationObservers` | | Frames | A window's animation frames, each running the writes module code asks for, then the reads, the evaluations of the watches scheduled by frame among them | `FrameSchedule` | @@ -33,6 +33,10 @@ DOMQL is Nexo's host. It registers its module in a Nexo registry beside the modu The DOM enters as late as it can. Making and resolving a query read no DOM, so they work in Node.js; code under `src/dom/` reads the window and the document it is given, never a global, and code under `src/snapshots/` reads no DOM at all, only the results and the metadata Nexo records beside them. Dependencies point one way: `dom/` depends on Nexo and `snapshots/`, and `snapshots/` on Nexo alone. +DOMQL creates its module, and the registry it registers it in, as it is imported, under `ModuleManifest`, the manifest Nexo makes of the module, so neither makes the checks of its declarations and their registration that the manifest records, as [Nexo's preparing modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-preparing) sets out. DOMQL's own checks of its host calls are made either way. `npm run manifest`, from the repository root, runs `scripts/module-manifest.mjs`, which writes the manifest as the dispatch table gives Nexo the module's contents. A test fails while the manifest the sources hold differs from the one the declarations give. Nexo reads a manifest another implementation made as holding no module, so DOMQL on a Nexo other than the one it was built against, as a host may install beside DOMQL's npm package, creates its module with every check. In Chromium, cold, the import took about 33.5 ms where it took 43, and the first query's resolution and the first registrations about 2 ms more, as Nexo resolves the module's notations as they are first read. [D115](decisions.md#d115) records the measurement. + +A host's manifest, which `domql.prepare` answers, is the one Nexo makes of DOMQL's module, the host's modules after it, and the host's queries, each text read with `Domql` supplied, so it holds DOMQL's module at the digest DOMQL's own manifest gives it. DOMQL gives `manifest` to Nexo as each operation takes it: `createModule`, `registerModule` and a loader's registration pass their options on, and a query keeps its manifest beside its types, gives it to `nexo.parse` as it reads its text, and to `registry.resolve` as it resolves, binding its values without it. The resolutions a query keeps for its definition are kept alike, whether Nexo read them from a manifest or resolved them. [D116](decisions.md#d116) records the measurement. + DOMQL's `typeOf` and its types' `isInstance` recognize a node by its `nodeType` and a window by its being its own `window`, never by a global's prototype, so a node of another window is recognized as one of the window a query runs in is. A node holds functions, which data never does, so data that names a `nodeType` is never taken for a node. ## Resolution @@ -64,7 +68,7 @@ A selector is read for what it tests by `Selectors`, a scan of its text that nee ## Comparing and patching -The comparer reads what Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results) records beside each value: the provenance of each item, the source the earliest projection it descends from read, by which a list is matched where Nexo classifies every item's provenance as a reference, each standing once; the origin of each value, which tells whether a number came from the same branch, operand or property as the number before it; and the tolerance it compares within. A result therefore holds data alone, and a change set never names an element. +The comparer reads what Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results) records beside each value: the provenance of each item, the source the earliest projection it descends from read, by which a list is matched where Nexo classifies every item's provenance as a reference, each standing once; the origin of each value, which tells whether a number came from the same branch, operand or property as the number before it; and the tolerance it compares within. A result therefore holds data alone, and a change set never names an element. The patcher computes the change set that takes one reconciled snapshot to the next, and applies change sets in place to live state. A watch keeps the metadata of the snapshot it holds for the next comparison, so `sourceOf` reads an item's provenance from it, walking the records of the fields and items along the path, and allocates nothing until a caller asks. @@ -91,7 +95,7 @@ Each operation makes one environment as it starts, frozen, holding its window, i A member reading the state a behavior offers is given Nexo with an implementation that wraps its own, adding the instance its environment's owner finds on its receiver, so Nexo calls it as any member. The `behavior` observation is kept beside the instances by the behavior's name and the receiver, its name alone since its identity can hold nothing of a module or an owner; a behavior of one name in two modules, or of two owners, tells both modules' observations, whose members read what changed for their own. An instance tells them as it starts, after its update, on both receivers where it moves, as it ends, and as its `notify` is called. -A subscription to a behavior's event source is kept beside the instances, by the module, the behavior and the source, then its owner and its receiver, and never by an instance, so it hears every instance there and outlives each. `deliver` closes over the instance's entry, whose receiver an update moves, so an occurrence goes to the receiver the instance runs on as it is delivered; the entry is marked ended as the instance ends, before its disposal runs. Delivering copies the receiver's subscriptions before handing the occurrence to the first, so one a handler adds or stops changes who hears the next occurrence, never this one, and joins their acknowledgments with `Promise.all` where more than one hears it; one subscription's acknowledgment is the delivery's own. In five paired rounds against the commit before it, in Chromium, a pointer move one subscription hears took 15 to 24% less time and allocated 13 to 19% less, about 0.5 µs and 450 bytes a move, and one four subscriptions hear measured within noise. An occurrence no subscription hears answers one rejection, `DOMQL5017` located at the behavior, made as the first is delivered and handled as it is made, and kept for the instance and its source until a subscription to the source listens for the instance's owner on its receiver, or the instance ends, since what it says is the same for each. An error made for each, whose stack Nexo writes as it makes it, had cost nearly all of the delivery: in five paired rounds against the commit before it, in Chromium, a pointer move no subscription hears took 0.20 µs rather than 13.95, and allocated 244 bytes rather than 4.7 KB. +A subscription to a behavior's event source is kept beside the instances, by the module, the behavior and the source, then its owner and its receiver, and never by an instance, so it hears every instance there and outlives each. `deliver` closes over the instance's entry, whose receiver an update moves, so an occurrence goes to the receiver the instance runs on as it is delivered; the entry is marked ended as the instance ends, before its disposal runs. Delivering copies the receiver's subscriptions before handing the occurrence to the first, so one a handler adds or stops changes who hears the next occurrence, never this one, and joins their acknowledgments with `Promise.all` where more than one hears it, fulfilling with the first's answer; one subscription's acknowledgment is the delivery's own. An answer is captured by the event listener of its subscription, as the type its source declares it answers, through the instance's registry, as a binding of that type is captured, so an answer reaches the behavior as data of that type, as every value crossing into module code does. In five paired rounds against the commit before it, in Chromium, a pointer move one subscription hears took 15 to 24% less time and allocated 13 to 19% less, about 0.5 µs and 450 bytes a move, and one four subscriptions hear measured within noise. An occurrence no subscription hears answers one rejection, `DOMQL5017` located at the behavior, made as the first is delivered and handled as it is made, and kept for the instance and its source until a subscription to the source listens for the instance's owner on its receiver, or the instance ends, since what it says is the same for each. An error made for each, whose stack Nexo writes as it makes it, had cost nearly all of the delivery: in five paired rounds against the commit before it, in Chromium, a pointer move no subscription hears took 0.20 µs rather than 13.95, and allocated 244 bytes rather than 4.7 KB. An event listener answers each event's acknowledgment from what its handler did: one promise, already fulfilled, shared by every event a handler applied as it returned, since it holds nothing of the event; a promise of its own only where the handler returned one, or the event waits while the listener starts, kept until it settles so disposal rejects it; and a rejected one, handled as it is made, where the event failed. In five paired rounds against the commit before it, projecting an event measured within the rounds' noise, a median of 111,000 events a second against 106,000 for one read of a panel; an acknowledgment of its own for every event had cost about a tenth. @@ -119,47 +123,38 @@ Nexo keeps a host call's function arguments open until the prepared call is disp An owned write's target is kept by `OwnedWrites`, one for each set of the module's implementations, so one instance of the library, as its registry and its observations are: by the element in a weak map, and by a key naming the target within it, as `attribute tabindex` or `class open`, the holders of each target in the order they began, the value the target held before the first, and the value DOMQL last wrote, which it reads back from the element after writing so the browser's serialization decides it. A holder that keeps its value observes its element's attribute with a mutation observer filtered to it, one for the holding, kept through every update that holds the same target and keeps it still, as [D85](decisions.md#d85) records, the `class` and `style` attributes for a class and a style property, and its child list and their text for its text, and writes its value again among the next animation frame's writes, through the environment's `frame`, rather than in the mutation's own microtask, so a frame watch reads the value kept in the frame it was written in. Having written again, it notes the attribute or the text as the other writer left it, from the target's `written`, and asks two frames more of the schedule. A change before the second runs that restores what it noted is an answer: the writer keeps a value of its own, in a microtask or a frame of its own, so the holder yields to it, writing nothing more until its next update, where two writers that each kept a value would alternate once a frame without end. A change that leaves anything else is a patch, a framework rendering the element again, and is undone as the first was. A text target writes the data of the element's one text node, finding the node again at each read and write, so a framework that rendered it keeps it. -## The C# half + + +## Connections -This section outlines the C# half, which waits for its design, as [the decisions](decisions.md#d46) record. +A host whose code runs elsewhere, as a .NET application's does, reaches DOMQL through a [connection](../spec/connections.md), as [D118](decisions.md#d118) records. [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, is DOMQL's host of one for .NET applications, as [D120](decisions.md#d120) records. -The C# half carries a watch to a .NET application, which starts a watch and receives its results; it is a caller that keeps its own copy of each result, as [keeping a copy of a result](../spec/results.md#results-keeping-a-copy) sets out. Its API follows the JavaScript one: +| Part | What it does | Source | +| --- | --- | --- | +| The connection | Carries a host's requests out in batches, answering each once its task ends, and sends the deliveries of each task together, a watch's paced by the acknowledgment of the one before it | `src/connections/Connection.mjs` | +| The conformance corpus | Each case a previous result, a change set and the result they give, which DOMQL's applier passes, and a host's that keeps a copy of a result | `tests/_conformance/change-sets.json` | -| C# | Meaning | -| --- | --- | -| `Domql.Query(text, bindings)`, `Domql.Query(text, bindings)`, and from a definition alike | Makes a query object, binding its parameters, as `domql.query` does | -| `Domql.TryQuery(…)`, `Domql.TryQuery(…)` | Attempts exactly what `Domql.Query` does, answering false with a diagnostic for a syntax or structure failure | -| `query.Definition` | The query's immutable definition, without its bindings | +### A task's requests and deliveries -C# writes text, and names the type its result maps onto, or none: +- **A batch's answers** settle once the task that carried its requests out has ended. A message posted to the window's own channel runs after that task's microtasks. +- **A watch evaluates first in a microtask,** so its snapshot answers its request, and so does an execution that settles at once, as a focus or an instant scroll does. +- **Deliveries are queued as they happen,** and a microtask sends the task's together. +- **Answers and deliveries race.** A transport may deliver a call the browser makes during a request's task before that request's answer, so a host holds a watch's deliveries until its answer arrives. -```csharp -public sealed record PanelState(double? Width, bool HasFocus); +### Watches -DomqlQuery typed = Domql.Query( - """ - panel { - width = it.size?.width, - hasFocus = it.focusWithin - } - """, - ("panel", panel)); +- **A watch in the browser** watches live state, so each change event carries its change set. Its first result answers its request, or is delivered whole. +- **One delivery in flight.** Each later delivery waits for the acknowledgment of the batch holding the one before it. What arises meanwhile is joined: change sets concatenated, since they compose ([D65](decisions.md#d65)), unless the snapshot whole is shorter; a snapshot whole in place of what waits before it; a failure kept in its place. -DomqlQuery untyped = Domql.Query("panel { size = it.size }", ("panel", panel)); -``` +### Events -A `DomqlQuery` answers a `T`, mapped by its declared contract, which matches the result's fields to the constructor parameters of `T` by name regardless of case, so a field `nearend` fills a parameter `NearEnd`, and reports an ambiguity where two fields differ only in case, since DOMQL itself tells them apart; a `DomqlQuery` answers a `DomqlSnapshot` giving structured access to its values. C# has no C# type standing for each vocabulary concept: a module contributes its declarations and implementations, and the text names what the query reads. `Domql.TryQuery` attempts exactly what `Domql.Query` does, making a query and checking the syntax and the structural rules that need no vocabulary, an empty object expression, a duplicate field and a reserved name among them, without resolving its vocabulary or evaluating anything, so a successful return means the query was made, not that it is ready to be carried out: a syntax or structure failure returns false with a diagnostic, and any other failure is thrown, never swallowed. A vocabulary failure, such as an unknown member, arrives when the query is resolved. C# cancels with a `CancellationToken` where JavaScript takes a `signal`. +- **An event is delivered as it happens.** It is never held behind a watch's acknowledgment, nor joined, as [D69](decisions.md#d69) requires. Its acknowledgment settles as the host's answer does. +- **A limit.** A batch sent while earlier ones have left 4,096 deliveries unacknowledged closes the connection; one task of many deliveries crosses whole, so a refresh of thousands of watches closes nothing. -Its adapter owns the synchronization: +### Queries and their keys -- **Live state by default.** It watches live state, and takes its baseline from the first ready event's `args.snapshot`. -- **One update at a time.** It queues the immutable changes after the baseline and delivers them in order, sending the next only once the receiving side acknowledges that the one before was applied completely. Acknowledgment follows application alone, never the application's handlers, and a failed delivery stops every further update of that watch. -- **One ordered queue.** Every handle of a connection, its watches' changes and its subscriptions' occurrences alike, sends through one queue, bounded, never coalescing an occurrence, and failing explicitly where it overflows, so the receiving side hears them in the [order](../spec/api.md#api-order-across-handles) the JavaScript side's handlers did. -- **No partial state.** No consumer observes a change set partly applied: access to the C# result during an update follows an explicit rule, a result whose application failed becomes unusable, and the application's handlers are notified once the update is applied. -- **Obsolete watches rejected.** The receiving side rejects a delivery from an obsolete watch before applying it, through a token of its own for the watch it follows. -- **Recovery from uncertainty.** Where applying an update throws, a call rejects, or a call times out leaving its outcome uncertain, the adapter first invalidates the old watch, so its late applications and acknowledgments change neither the replacement result nor the new queue, then disposes it and rebuilds the result from a fresh watch's baseline. Where the connection is lost with the components holding its results, their replacements start watches of their own; where it resumes with them, an update unanswered across the interruption is uncertain and recovered as a timeout is. -- **Handler failures reported, not retried.** An exception from an application handler is reported without restarting synchronization, since the state was already accepted. -- **One way of applying.** Its application of change sets passes a conformance corpus the JavaScript patcher passes too: each case a previous result, a change set and the result they give, reviewed independently of either applier, moves and escaped paths among them. +- **A query's key.** A host names a query by a key of its own, giving its text with the first request that needs it, and naming it by its key alone after. A query the browser refused is made by no key. +- **Many panes, one text.** A page of fifty panes, each watching one query, sends its text once. ## Decisions not taken diff --git a/docs/features-status.md b/docs/features-status.md index 043ef8b..ccf9e30 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -2,17 +2,17 @@ ## Current state -**DOMQL is in its preview, `1.0.0-preview.1`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.1`, definition version 38. The specification describes DOMQL's `1.0.0-preview.1`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** +**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.3`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined, the C# half's among them.** | Version | Implementation | Specification | | --- | --- | --- | -| DOMQL specification | `1.0.0-preview.1` | `1.0.0-preview.1` | -| Nexo language | `1.0.0-preview.1` | `1.0.0-preview.1` | +| DOMQL specification | `1.0.0-preview.2` | `1.0.0-preview.2` | +| Nexo language | `1.0.0-preview.3` | `1.0.0-preview.3` | | Definition format | 38 | 38 | -- **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.1`, which Nexo's release `1.0.0-preview.1` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108) and [D109](decisions.md#d109) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). +- **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.3`, which Nexo's release `1.0.0-preview.4` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108), [D109](decisions.md#d109) and [D114](decisions.md#d114) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). - **Packages.** The bundle and type declarations are built, with Nexo bundled inside `domql.js`. The npm package holds DOMQL's sources, which import Nexo's package, and the NuGet package the bundle. Both carry the runtime version, and `release.yml` publishes each from a release's tag: the NuGet package from `1.0.0-preview.1`, and the npm package from `1.0.0-preview.2`. -- **The C# half** waits for its design, as [D46](decisions.md#d46) records. +- **The C# half** is implemented: a [connection](../spec/connections.md) carries DOMQL's operations across a boundary, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, is DOMQL's host of one for .NET applications, as [D120](decisions.md#d120) records. The [specification](../spec/README.md) defines the contract, and the [design](domql-design.md) explains the architecture. The [version history](../VERSION-HISTORY.md) records what each version changed, and the [changelog](../CHANGELOG.md) each release of the packages. This file tracks DOMQL's implementation and its remaining work. "Implemented" means built and tested in the gate for the current implementation version; it does not imply that later specification changes are implemented. @@ -22,10 +22,10 @@ The [specification](../spec/README.md) defines the contract, and the [design](do | Work | State | | --- | --- | -| [The C# half](#the-c-half) | Waits for its design | -| [Planned capabilities](#planned-capabilities) | The C# half's alone remain, waiting for its design | -| [Release](#release) | Done: `1.0.0-preview.3`, whose npm package changes only the README it carries, is released | -| [What 1.0 requires](#what-1-0-requires) | Six requirements, two met | +| [The C# half](#the-c-half) | Implemented | +| [Planned capabilities](#planned-capabilities) | Each implemented or declined | +| [Release](#release) | Done: `1.0.0-preview.4`, on the specification `1.0.0-preview.2`, is released | +| [What 1.0 requires](#what-1-0-requires) | Six requirements, three met | - **A specification version collects the changes between two releases.** A change to DOMQL's contract joins the [version history](../VERSION-HISTORY.md)'s newest entry while it reads *Unreleased*, and opens the next version's entry once it is released, as [D79](decisions.md#d79) records. - **A breaking change says how to migrate.** Since the beta, a version's entry in the [version history](../VERSION-HISTORY.md) says how to migrate beside each thing it breaks. @@ -60,13 +60,14 @@ Each feature, the contract that states it, its state in the implementation, and | Extension modules: their types, extensions read with `:`, observations, event sources and executions | [Extension modules](../spec/vocabulary.md#extension-modules) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | The DOM declared as DOMQL's own reference types, and the cast from `Aria` to `Element` | [Nodes](../spec/nodes-and-shadow-trees.md#nodes), [types](../spec/vocabulary.md#vocabulary-types) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | Diagnostic codes of DOMQL's own | [Errors](../spec/errors.md) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | +| The size layout gives a box, `layoutSize`, along its writing mode's axes, and `size`, the box as it is drawn, partly observable | [`layoutSize`](../spec/vocabulary.md#property-element-layoutsize), [`size`](../spec/vocabulary.md#property-element-size) | Implemented, as [D111](decisions.md#d111) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | Scrolling: `scroll` of an element and of the window, `scrollContainer`, and the padding box, `clientRect` | [Element `scroll`](../spec/vocabulary.md#property-element-scroll), [`scrollContainer`](../spec/vocabulary.md#function-element-scrollcontainer), [`clientRect`](../spec/vocabulary.md#property-element-clientrect) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | | Measurements of layout compared within a tolerance | [Tolerance](../spec/vocabulary.md#vocabulary-tolerance) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | | The observation target `children`, and a document's size | [Observation targets](../spec/vocabulary.md#observations-targets) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | | The focused element, `Domql.document.activeElement`, through open shadow roots | [`activeElement`](../spec/vocabulary.md#property-document-activeelement) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | | An element's `direction`, as `dir` decides it along its ancestry | [`direction`](../spec/vocabulary.md#property-element-direction) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | | States `displayed` and `focusable` | [`displayed`](../spec/vocabulary.md#state-element-displayed), [`focusable`](../spec/vocabulary.md#state-element-focusable) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | -| A control's `value`, and states `indeterminate` and `autofilled` | [`value`](../spec/vocabulary.md#property-element-value), [`indeterminate`](../spec/vocabulary.md#state-element-indeterminate), [`autofilled`](../spec/vocabulary.md#state-element-autofilled) | Implemented; no observation follows autofill itself, as [D17](decisions.md#d17) records | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | +| A control's `value`, and states `indeterminate` and `autofilled` | [`value`](../spec/vocabulary.md#property-element-value), [`indeterminate`](../spec/vocabulary.md#state-element-indeterminate), [`autofilled`](../spec/vocabulary.md#state-element-autofilled) | Implemented; no observation of DOMQL's own follows autofill itself, as [D17](decisions.md#d17) records, and an animation the page's style starts on a field as it is filled or emptied is observed, as [D112](decisions.md#d112) records | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282), [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | An element's `text`, `html`, `localName`, `classes` and `inlineStyle[property]` | [`text`](../spec/vocabulary.md#property-element-text), [`html`](../spec/vocabulary.md#property-element-html), [`inlineStyle`](../spec/vocabulary.md#function-element-inlinestyle) | Implemented | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | | A media element's `playback`, observed through its media events | [`playback`](../spec/vocabulary.md#property-element-playback) | Implemented | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | | The document selection, `Domql.document.selection`, its `Range`, and an editable element's `selection` | [Document `selection`](../spec/vocabulary.md#property-document-selection), [`Range`](../spec/vocabulary.md#property-range-rect), [Element `selection`](../spec/vocabulary.md#property-element-selection) | Implemented; an element's `selection` and `hasSelection` observable, as [D20](decisions.md#d20) records | [`alpha.283`](../VERSION-HISTORY.md#v1-0-0-alpha-283) | @@ -95,6 +96,7 @@ Each feature, the contract that states it, its state in the implementation, and | Queries from text or a definition, `with`, `select` and `resolve` | [Queries](../spec/queries.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | | Imports, `Domql` supplied to every query | [Its imports](../spec/queries.md#making-a-query-imports) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | A query run directly, in one call, `domql.executeAsync(text, bindings, options)` and each operation of a query object alike | [Two ways to run a query](../spec/api.md#api-two-ways-to-run-a-query) | Implemented, as [D89](decisions.md#d89) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | +| Modules and queries prepared ahead of time, `domql.prepare` and the `manifest` each operation takes | [Preparing ahead of time](../spec/vocabulary.md#extension-modules-manifests) | Implemented, as [D116](decisions.md#d116) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | Bindings of the types a query declares, `domql.query(text, bindings, { types })` | [Declared types](../spec/queries.md#making-a-query-declared-types) | Implemented, as [D82](decisions.md#d82) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | | Evaluating once, and waiting for maintained members | [Evaluation](../spec/evaluation.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | | Watches, their dependencies and partial observation | [Watches](../spec/watches.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | @@ -106,7 +108,7 @@ Each feature, the contract that states it, its state in the implementation, and | An operation's owner, which every implementation receives in one environment for the operation | [The owner](../spec/behaviors.md#behaviors-the-owner), [the environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D47](decisions.md#d47) records | [`alpha.302`](../VERSION-HISTORY.md#v1-0-0-alpha-302) | | Commands to a running behavior, reaching its instance for their owner on their receiver | [Commands](../spec/behaviors.md#behaviors-commands) | Implemented, as [D48](decisions.md#d48) records | [`alpha.302`](../VERSION-HISTORY.md#v1-0-0-alpha-302) | | Occurrences a behavior offers, through event sources of its module bound to its owner and receiver | [Occurrences](../spec/behaviors.md#behaviors-occurrences) | Implemented, as [D49](decisions.md#d49) records | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303) | -| A delivery acknowledged once each subscription applied it | [Acknowledgment](../spec/behaviors.md#behaviors-acknowledgment) | Implemented, as [D50](decisions.md#d50) records | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303) | +| A delivery acknowledged once each subscription applied it, and answered where its source declares `answers` | [Acknowledgment](../spec/behaviors.md#behaviors-acknowledgment), [answers](../spec/behaviors.md#behaviors-answers) | Implemented, as [D50](decisions.md#d50) and [D113](decisions.md#d113) record | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303), [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | State a behavior offers, read by its module's members and followed through the `behavior` observation | [State](../spec/behaviors.md#behaviors-state) | Implemented, as [D52](decisions.md#d52) records | [`alpha.304`](../VERSION-HISTORY.md#v1-0-0-alpha-304) | | DOMQL's observations and frames for module code, `env.observe` and `env.frame`, a frame's writes before its reads | [The environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D53](decisions.md#d53) records | [`alpha.305`](../VERSION-HISTORY.md#v1-0-0-alpha-305) | | Queries from module code, `env.domql`, and no execution while a query is evaluated | [The environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D54](decisions.md#d54) records | [`alpha.305`](../VERSION-HISTORY.md#v1-0-0-alpha-305) | @@ -125,13 +127,13 @@ Each feature, the contract that states it, its state in the implementation, and | Change sets that compose by concatenation, which a host coalesces, or replaces with the latest snapshot | [Composing](../spec/results.md#results-composing), [coalescing](../spec/results.md#results-coalescing) | Implemented, as [D65](decisions.md#d65) records | [`alpha.310`](../VERSION-HISTORY.md#v1-0-0-alpha-310) | | A refresh that takes new samples of the maintained members its watch reads, `refreshAsync({ resample: true })`, and a refresh's `signal` | [Resampling](../spec/watches.md#watching-resampling) | Implemented, as [D66](decisions.md#d66) records | [`alpha.311`](../VERSION-HISTORY.md#v1-0-0-alpha-311) | | Modules loaded on request: a loader by a module's name, `domql.registerModuleLoader`, and `domql.loadModulesAsync`, which loads what a query imports | [Loading a module on request](../spec/vocabulary.md#extension-modules-loading) | Implemented, as [D68](decisions.md#d68) records | [`alpha.313`](../VERSION-HISTORY.md#v1-0-0-alpha-313) | -| What DOMQL delivers reaches its handlers in the order it happens, across handles, subscriptions and owners, and calls to several handles take effect in the order they are made | [Order across handles](../spec/api.md#api-order-across-handles) | Implemented, as [D69](decisions.md#d69) records; the C# half's queue waits with it | [`alpha.314`](../VERSION-HISTORY.md#v1-0-0-alpha-314) | +| What DOMQL delivers reaches its handlers in the order it happens, across handles, subscriptions and owners, and calls to several handles take effect in the order they are made | [Order across handles](../spec/api.md#api-order-across-handles) | Implemented, as [D69](decisions.md#d69) records, and carried across a boundary by a connection, as [D118](decisions.md#d118) records | [`alpha.314`](../VERSION-HISTORY.md#v1-0-0-alpha-314) | | Reactions, once executions a subscription carries out inside each event's delivery, bound to the event's value, whose results reach the handler after it | [Reactions](../spec/events.md#events-reactions) | Implemented, as [D71](decisions.md#d71) records | [`alpha.316`](../VERSION-HISTORY.md#v1-0-0-alpha-316) | | The element a watch's list item came from, `watch.sourceOf(...path)`, for a handler in the browser | [`sourceOf`](../spec/watches.md#watching-source-elements) | Implemented, as [D72](decisions.md#d72) records | [`alpha.317`](../VERSION-HISTORY.md#v1-0-0-alpha-317) | | Delivery options: a delayed schedule a refresh flushes, reporting on parts, and a subscription's throttle | [The delayed schedule](../spec/watches.md#watching-delayed), [reporting on parts](../spec/results.md#results-reporting-on-parts), [throttling](../spec/events.md#events-throttling) | Implemented, as [D73](decisions.md#d73) records | [`alpha.318`](../VERSION-HISTORY.md#v1-0-0-alpha-318) | | The beta, its promise and the changelog | [Version history](../VERSION-HISTORY.md#v1-0-0-beta-1), [changelog](../CHANGELOG.md) | Implemented, as [D75](decisions.md#d75) records | [`beta.1`](../VERSION-HISTORY.md#v1-0-0-beta-1) | | The preview, the beta's promise under FormaUI Versioning's name for it | [Stages](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/versions.md#stages) | Implemented, as [D106](decisions.md#d106) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | -| The C# half | [Design](domql-design.md#the-c-half) | Waits for its design | — | +| A connection, carrying DOMQL's operations across a boundary as messages, which [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) hosts for .NET applications | [Connections](../spec/connections.md) | Implemented, as [D118](decisions.md#d118) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | @@ -143,9 +145,9 @@ DOMQL moved from Lexica at `0e98b3e`, language `1.0.0-alpha.33`, to Nexo's langu - **One pin.** The migration was planned in checkpoints, each on a Nexo commit pinned as Nexo's work landed. Nexo reached its beta first, and its checklists describe the beta, so DOMQL moved to the beta at one pin, its checkpoints the order of the work, and passed its gate once on the beta: pinning a commit for each checkpoint would have meant writing against interfaces Nexo had already changed again. - **Imports.** DOMQL supplies its own module, `Domql`, as every query's import, and a query writes its other imports. An application configures no imports of its own, so a query's text means the same whatever was configured, as [D4](decisions.md#d4) records. - **Errors.** DOMQL's own conditions take `DOMQL` codes, catalogued in [errors](../spec/errors.md), bounded to the conditions it reports today; an error of Nexo's passing through DOMQL keeps its own code. -- **Module errors.** A module error of DOMQL's own, as its dispatch table's refusals are, is built with `NexoError.module`, which Nexo declared for its hosts in language `1.0.0-beta.2` for DOMQL's migration, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d29) record. -- **Host calls on a receiver of unknown type.** What such a call requests is read from the candidates Nexo answers for it, every declaration that takes the call as it is written, which Nexo answers from language `1.0.0-beta.3` for DOMQL, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d30) record. DOMQL read them from an index of its own before, which counted host calls a query could not reach. -- **What the migration found in Nexo since,** fixed in Nexo's languages `1.0.0-beta.4` to `1.0.0-beta.8`, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d31) record: a host call on a value of `Any` is refused as Nexo resolves it, where DOMQL refused it as a value to evaluate; a module's own type named `Pair` is named by that name in its declarations; `@Domql` standing alone gives `~Domql`; a watch made stale by a module recognizing values compares within each value's tolerance, as Nexo keeps origins across resolutions of one definition; and a member read through a value of `Any` is compared within the tolerance it declares. +- **Module errors.** A module error of DOMQL's own, as its dispatch table's refusals are, is built with `NexoError.module`, which Nexo declared for its hosts in language `1.0.0-beta.2` for DOMQL's migration, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d29) record. +- **Host calls on a receiver of unknown type.** What such a call requests is read from the candidates Nexo answers for it, every declaration that takes the call as it is written, which Nexo answers from language `1.0.0-beta.3` for DOMQL, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d30) record. DOMQL read them from an index of its own before, which counted host calls a query could not reach. +- **What the migration found in Nexo since,** fixed in Nexo's languages `1.0.0-beta.4` to `1.0.0-beta.8`, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d31) record: a host call on a value of `Any` is refused as Nexo resolves it, where DOMQL refused it as a value to evaluate; a module's own type named `Pair` is named by that name in its declarations; `@Domql` standing alone gives `~Domql`; a watch made stale by a module recognizing values compares within each value's tolerance, as Nexo keeps origins across resolutions of one definition; and a member read through a value of `Any` is compared within the tolerance it declares. Contracts: [Queries](../spec/queries.md), [types](../spec/vocabulary.md#vocabulary-types), [extension modules](../spec/vocabulary.md#extension-modules), [results](../spec/results.md), [errors](../spec/errors.md). @@ -154,20 +156,13 @@ Contracts: [Queries](../spec/queries.md), [types](../spec/vocabulary.md#vocabula ## The C# half -**Waits for its design.** The C# half is out of the current work until it is designed, as [D46](decisions.md#d46) records; the outline below is where its design starts. +**Implemented.** [D118](decisions.md#d118) records the connection, in place of the outline [D46](decisions.md#d46) waited with, and [D120](decisions.md#d120) the .NET half's move to a project of its own. -The C# half follows the migration, so its API is built on the final query text, imports, definition version and result representations, never reworked after them. +- **A connection,** `domql.connect`, carries a host's requests in batches, answered as their task ends, and sends each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. +- **[DOMQL.NET](https://github.com/FormaUI/DOMQL.NET)** is DOMQL's host of one for .NET applications, with its own specification, status and records. +- **One way of applying:** the conformance corpus, `tests/_conformance/change-sets.json`, which DOMQL's JavaScript applier passes, and DOMQL.NET's tests read and pass. -- **Its API,** as [the design](domql-design.md#the-c-half) sets out: `Domql.Query` and `Domql.Query` from text or a definition, binding its parameters; `Domql.TryQuery`, answering false with a diagnostic for a syntax or structure failure; and `query.Definition`. A `DomqlQuery` maps a result onto `T` by its declared contract, and a `DomqlQuery` answers a `DomqlSnapshot`. -- **Results:** lists, dictionaries and pairs mapped onto `T` and read through a `DomqlSnapshot` by their exported forms. -- **Imports:** `Domql`, which DOMQL supplies to every query, applied as the JavaScript half applies it. -- **Its adapter's synchronization:** live state with its baseline from the first ready event, one update at a time, no partial state, obsolete watches rejected, recovery from uncertainty, and handler failures reported, not retried. -- **One way of applying:** its application of change sets passes the conformance corpus the JavaScript patcher passes too. -- **Diagnostics:** an error of the language it reports keeps its code. - -**Completion:** the C# half passes the gate, its conformance corpus included. - -Contracts: [The C# half](domql-design.md#the-c-half), [keeping a copy of a result](../spec/results.md#results-keeping-a-copy). +Contracts: [Connections](domql-design.md#connections), [keeping a copy of a result](../spec/results.md#results-keeping-a-copy). @@ -179,7 +174,7 @@ The language's part is Nexo's already, adopted with the [migration](#migration-t **The order of the work:** -1. **The C# half** (A1), with its queue of ordered delivery (A5), once it is designed, as [D46](decisions.md#d46) records. +1. **The C# half** (A1), with its queue of ordered delivery (A5), implemented: the connection in DOMQL, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) over it, as [D120](decisions.md#d120) records. @@ -243,7 +238,7 @@ None remains: C1 to C14 are implemented, as [the features](#the-host) show, each ### API and host -Only the C# half's remain, A1 and A5's queue, both waiting for its design ([D46](decisions.md#d46)). A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: +A1 and A5's queue are implemented, as [D118](decisions.md#d118) and [D120](decisions.md#d120) record. A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: - Change sets compose by concatenation, so a host coalesces them itself ([D65](decisions.md#d65)). - A refresh takes new samples where it is asked to, and delivering an equal result needs nothing new ([D66](decisions.md#d66)). @@ -257,8 +252,8 @@ Only the C# half's remain, A1 and A5's queue, both waiting for its design ([D46] | | Addition | | --- | --- | -| A1 | **The C# half,** waiting for its design, as [outlined](#the-c-half): typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | -| A5 | **The C# half's queue of ordered delivery:** bounded, never coalesced, failing explicitly on overflow, carrying across the boundary the order the JavaScript side already keeps. It waits with A1 | +| A1 | **The C# half,** implemented by [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own: typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | +| A5 | **The C# half's queue of ordered delivery:** bounded, never coalesced, failing explicitly on overflow, carrying across the boundary the order the JavaScript side already keeps. Implemented by the [connection](../spec/connections.md#connections-pacing) | @@ -273,14 +268,14 @@ None remains: T1 to T3 are implemented, as [the features](#the-host) show: an im DOMQL releases as [cutting a release](../CONTRIBUTING.md#cut-a-release) sets out, by FormaUI Versioning's path, as [D107](decisions.md#d107) records. Its first release, `1.0.0-preview.1`, is released, tagged `v1.0.0-preview.1`, and `release.yml` publishes its NuGet package, with Nexo inside its bundle, to nuget.org through trusted publishing. nuget.org's policy names `FormaUI/DOMQL`, `release.yml` and the `release` environment. -Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `release.yml` publishes its npm package beside the NuGet package, as [D110](decisions.md#d110) records. npm's trusted publisher names the same repository, workflow and environment, and allows `npm publish`. A deprecated placeholder, `@formaui-net/domql@0.0.0`, holds npm's `latest` dist-tag until 1.0, as Nexo's does, since npm takes a trusted publisher only for a package it holds. Its third, `1.0.0-preview.3`, whose npm package changes only the README it carries, is released, tagged `v1.0.0-preview.3`, and published the same way. +Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `release.yml` publishes its npm package beside the NuGet package, as [D110](decisions.md#d110) records. npm's trusted publisher names the same repository, workflow and environment, and allows `npm publish`. A deprecated placeholder, `@formaui-net/domql@0.0.0`, holds npm's `latest` dist-tag until 1.0, as Nexo's does, since npm takes a trusted publisher only for a package it holds. Its third, `1.0.0-preview.3`, whose npm package changes only the README it carries, is released, tagged `v1.0.0-preview.3`, and published the same way, and so is its fourth, `1.0.0-preview.4`, on the specification `1.0.0-preview.2` and Nexo's `1.0.0-preview.4`. ### Consuming the language -**Current:** DOMQL depends on Nexo's npm package, `@formaui-net/nexo`, from `1.0.0-preview.1`, the release its lock installs and its tests run against, as [D109](decisions.md#d109) records; with `NEXO_SOURCE` naming a Nexo checkout, the build links that checkout's working tree in the package's place. CI checks Nexo out at the release's tag, whose documents the link test reads. It imports the language's entry point alone, and bundles it into `domql.js`. The language's tests that run through DOMQL's entry point are DOMQL's integration tests. +**Current:** DOMQL depends on Nexo's npm package, `@formaui-net/nexo`, from `1.0.0-preview.4`, the release its lock installs and its tests run against, as [D109](decisions.md#d109) records; with `NEXO_SOURCE` naming a Nexo checkout, the build links that checkout's working tree in the package's place. CI checks Nexo out at the release's tag, whose documents the link test reads. It imports the language's entry point alone, and bundles it into `domql.js`. The language's tests that run through DOMQL's entry point are DOMQL's integration tests. **Remaining:** @@ -288,7 +283,7 @@ Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `rele 2. Write the NuGet bundle with `../nexo/nexo.js` as an import, rather than carrying the language inside, as the npm package's sources import `@formaui-net/nexo`. 3. Have the gate check that DOMQL's packages depend on Nexo's and Nexo's on nothing of DOMQL's. -Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#release) records. +Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#release) records. ### Packages @@ -306,7 +301,7 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https - The documents and the module API were audited, and the behavior of a cast inside an optional enclosed access was settled. - The specification and the runtime both took `1.0.0-beta.1`. The contract is that of `1.0.0-alpha.318`, unchanged. -- No breaking redesign is planned. The C# half (A1) and A5's queue wait for their design, as [D46](decisions.md#d46) records. The [deferred work](#deferred) and the design's [decisions not taken](domql-design.md#decisions-not-taken) document the other limitations. +- No breaking redesign is planned. The [deferred work](#deferred) and the design's [decisions not taken](domql-design.md#decisions-not-taken) document the other limitations. - A break from here on says how to migrate, beside it, in the [version history](../VERSION-HISTORY.md), and a change a caller can notice is listed in the [changelog](../CHANGELOG.md). @@ -317,9 +312,9 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https | Requirement | Why | State | | --- | --- | --- | -| **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.1`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#what-1-0-requires) sets out. | +| **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.4`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#what-1-0-requires) sets out. | | **Contracts settled.** No decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) is shown to land without a break. | What may still change after 1.0 must be able to change compatibly. | Holds: no decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) lands as an addition or within the implementation. A watch's promise to evaluate its whole query each time was the one that would have made evaluating less a break; [what an evaluation gives](../spec/watches.md#watching-what-an-evaluation-gives) now leaves it to DOMQL. | -| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | It waits for the owner's design, as [D46](decisions.md#d46) records, and a .NET application may need it to drive DOMQL. | Waits for its design. | +| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | A .NET application may need it to drive DOMQL. | Holds: the connection is implemented, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) hosts it for .NET applications, as [D120](decisions.md#d120) records. | | **Published.** DOMQL's packages are on npm and NuGet, tested as consumers install them. | A caller pins a release it can install. | Holds: the NuGet package is published from `1.0.0-preview.1` and the npm package from `1.0.0-preview.2`, each verified as consumers install it before its release. | | **Used for real.** Forma's own scripts run as DOMQL queries, watches, subscriptions and executions on a published release. | The [planned capabilities](#planned-capabilities) came from reading those scripts, and only running them settles the contract. | Planned. | | **A release candidate that breaks nothing.** `1.0.0-rc.1` is released once the rest hold, and Forma takes it with no change but its version. `1.0.0` is its contract, unchanged. | It is the last check that nothing still needs to break. | Waits for the rest. | @@ -342,7 +337,7 @@ This work is separate from the plan above. No order is assigned here. | Work | Status | Remaining | | --- | --- | --- | -| Editor tooling | Waits for Nexo's design | Nexo's, through its syntax tree, in its [tooling](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#tooling), which waits for its design | +| Editor tooling | Waits for Nexo's design | Nexo's, through its syntax tree, in its [tooling](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#tooling), which waits for its design | **Verification outside the gate.** Performance is measured outside the gate, by `npm run bench` and `npm run scale` from `tests/`. `Domql.window.size` following a scrollbar that appears or goes runs in the gate, as a browser test with a launch of its own. diff --git a/nuget/README.md b/nuget/README.md index 4315e78..eb91bc3 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -2,9 +2,9 @@ **A declarative approach to managing the DOM.** -DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. This guide takes you from your first query to watching results, handling events and extending the library. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). +DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. This guide takes you from your first query to watching results, handling events and extending the library. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md). -> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.3`, implements DOMQL's specification `1.0.0-preview.1` on Nexo's language `1.0.0-preview.1`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. +> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.3`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. ## In this guide @@ -19,6 +19,7 @@ DOMQL is a JavaScript library for querying the DOM, allowing you to read informa - [Environments](#environments) - [Extend the vocabulary](#extend-the-vocabulary) - [Execute once and run continuously](#execute-once-and-run-continuously) +- [Use DOMQL from .NET](#use-domql-from-net) ## Install and load @@ -205,7 +206,7 @@ Call `dispose()` when you no longer need updates. It stops the watch's listeners ### Observation limits -A watch can only respond to changes reported by its members' observations. Some members have gaps: `matches` misses pointer state such as `:hover`, and `rect` can miss position changes that none of its observations detect. +A watch can only respond to changes reported by its members' observations. Some members have gaps: `matches` misses pointer state such as `:hover`, `rect` can miss position changes that none of its observations detect, and `size` misses a transform, which changes the size a box is drawn at but not its layout. To watch a box's size, watch `layoutSize`, which every change of its layout reports. Watching a partly observable member requires an explicit option: @@ -798,6 +799,8 @@ panel.scroll { } ``` +`rect` and `size` measure the box as it is drawn, its transforms and its ancestors' applied. `layoutSize` is the size layout gives the box, along its writing mode's axes, `inline` and `block`, with any transform left aside, as the browser's resize observer measures it, and null for an element that isn't laid out as one box, or whose box has no size. It is pending until the browser first reports the box, as it lays the page out: `evaluate` fails on it, so read it with `evaluateAsync` or a watch, whose first snapshot waits for that report. + `scrollContainer()` finds the nearest ancestor the user can scroll, across shadow roots and slots, and is null where the window scrolls the element. `sizeLimits` reads the `min-width`, `max-width`, `min-height` and `max-height` a box is kept within, in pixels, each null where it is no length. A watch compares each measurement within a twentieth of a pixel, so a box settling by less reports no change. ### Read values and text @@ -1001,7 +1004,7 @@ Modules can also declare Boolean members, properties and functions whose result A member the host invokes, `invokedBy: 'host'`, is a host call that DOMQL carries out: an event source, `requestKind: 'subscription'`, or an execution, `requestKind: 'execution'`, which runs `once` or `continuous` as its `executionMode` says. An event source's implementation receives the receiver, arguments, environment and an event-delivery callback, as `{ receiver, args, env, deliver }`, and returns an object with a `stop` method to end listening. Each event is captured as the type its declaration's result names, and a module adds event types of its own as mappings of DOMQL's type selector `event`, `{ selector: 'event', key, type }`, each naming the type its events are captured as. -[Nexo's modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules) specify the full extension contracts. The next section shows execution modules. +[Nexo's modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules) specify the full extension contracts. The next section shows execution modules. ### Bind data as a module's type @@ -1075,6 +1078,41 @@ unread.evaluate(); `loadModulesAsync` takes a query, a definition, a text or a list of module names. It loads only the modules the instance doesn't hold yet, and shares a load that is already under way, so call it before every query that may need one. A query that imports a module whose loader hasn't run yet is refused with `DOMQL3007`. Load first even for `run`, which starts its execution before it returns. +### Prepare ahead of time + +Creating and registering a module checks its declarations, and a query's text is read and resolved, each time a page starts. Your build can make those checks once, with `domql.prepare`, and give the page what it recorded, a manifest, which spares it the checks: + +```js +const badges = { + types: [{ + name: 'BadgeElements', + kind: 'extension', + target: 'Domql.Element', + members: [{ + name: 'badge', + kind: 'property', + result: 'String?', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-badge'] }] }, + impl: ({ receiver: element }) => element.getAttribute('data-badge') + }] + }] +}; + +// At build time: the module and the query, checked once, as a manifest kept as JSON. +const manifest = domql.prepare([{ name: 'Badges', contents: badges }], { + scripts: [{ script: 'import Badges\npanel:badge ?? "none"', types: { panel: 'Domql.Element' } }] +}); + +// At the page's start: the same module and query, from the manifest. +domql.registerModule(domql.createModule('Badges', badges, { manifest }), { manifest }); +domql.query('import Badges\npanel:badge ?? "none"', { panel }, { manifest }).evaluate(); +// 'none' +``` + +- **A binding given a type and no value** stands for every value of that type, so `types: { panel: 'Domql.Element' }` prepares the query for any element. A `String` or a `Boolean` binding is given its value, since its value decides what a member reads. +- **Pass the manifest** to `createModule`, `registerModule`, `registerModuleLoader` and `query`, or beside `types` to an operation run directly. Anything the manifest doesn't hold is checked and resolved as usual. +- **Prepare again with each release.** A manifest another version of Nexo made holds nothing, so everything is checked again until your build makes it anew. + ## Execute once and run continuously ### Change the page with a built-in execution @@ -1280,6 +1318,8 @@ A behavior reports what happens, a drop, a move or a choice, as an occurrence: i `deliver` answers a promise that settles once each subscription has applied the occurrence, a handler's returned promise included, and rejects where none listens or one failed; a behavior that doesn't need to know may leave it. +A behavior that asks its caller what to do, as which address to go to, declares the answer's type on the source, `answers: 'String?'`. The first subscription's handler answers by returning the value, or a promise of it, and `deliver`'s promise fulfils with that answer, captured as the declared type, so the question and its answer are one delivery: `const destination = await deliver('destinations', request)` holds the subscription's answer. + ```js domql.registerModule(domql.createModule('Pickers', { types: [{ @@ -1540,12 +1580,16 @@ clickFilter.dispose(); filtered.dispose(); ``` +## Use DOMQL from .NET + +To run DOMQL from .NET code, with typed results and watches kept current in .NET, use [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), which runs over DOMQL's [connection](https://github.com/FormaUI/DOMQL/blob/main/spec/connections.md). + ## Learn more - [Repository README](https://github.com/FormaUI/DOMQL): what DOMQL is for, what is built, and how to build and test it. -- [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md): the language DOMQL is written in, its syntax, types, null semantics, imports and extensions, and the runtime contracts of its modules. +- [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md): the language DOMQL is written in, its syntax, types, null semantics, imports and extensions, and the runtime contracts of its modules. - [DOMQL specification](https://github.com/FormaUI/DOMQL/blob/main/spec/README.md): queries, the DOM's vocabulary, evaluating and watching a query, its results, events, executions, and the API. -- [DOMQL design](https://github.com/FormaUI/DOMQL/blob/main/docs/domql-design.md): how DOMQL is built, and the decisions it did not take, and the [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md): how the language and its runtime are built. +- [DOMQL design](https://github.com/FormaUI/DOMQL/blob/main/docs/domql-design.md): how DOMQL is built, and the decisions it did not take, and the [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md): how the language and its runtime are built. - [Changelog](https://github.com/FormaUI/DOMQL/blob/main/CHANGELOG.md): each release of the package and what it changed. - [Status](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md): what is implemented, what is being built, and what remains. diff --git a/package-lock.json b/package-lock.json index 141ee15..2712550 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "license": "Apache-2.0", "dependencies": { - "@formaui-net/nexo": "^1.0.0-preview.1" + "@formaui-net/nexo": "^1.0.0-preview.4" }, "devDependencies": { "esbuild": "^0.25.0" @@ -458,9 +458,9 @@ } }, "node_modules/@formaui-net/nexo": { - "version": "1.0.0-preview.1", - "resolved": "https://registry.npmjs.org/@formaui-net/nexo/-/nexo-1.0.0-preview.1.tgz", - "integrity": "sha512-713+idtSy2efEFqAguoJX6hE4G5OJ0vxSmETqngu9571ruQcuVGZTW6YXAsRkHT7homK1zqB2JPSBD1jth0PbQ==", + "version": "1.0.0-preview.4", + "resolved": "https://registry.npmjs.org/@formaui-net/nexo/-/nexo-1.0.0-preview.4.tgz", + "integrity": "sha512-FfXUg8plHMeGRUzld4C97Jg6G+b7diYLfrTLXn1uS3ACFLc04Hh6f8DnGyUlzwq3pa8ygLYkSobq/TGxF5rtEQ==", "license": "Apache-2.0" }, "node_modules/esbuild": { diff --git a/package.json b/package.json index badc078..c88d7a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "description": "DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes.", "license": "Apache-2.0", "author": "Eyal Alon", @@ -26,10 +26,11 @@ "access": "public" }, "scripts": { - "bundle": "node scripts/bundle.mjs" + "bundle": "node scripts/bundle.mjs", + "manifest": "node scripts/module-manifest.mjs" }, "dependencies": { - "@formaui-net/nexo": "^1.0.0-preview.1" + "@formaui-net/nexo": "^1.0.0-preview.4" }, "devDependencies": { "esbuild": "^0.25.0" diff --git a/scripts/Test-Packages.ps1 b/scripts/Test-Packages.ps1 index 0a8825a..5c4faf9 100644 --- a/scripts/Test-Packages.ps1 +++ b/scripts/Test-Packages.ps1 @@ -103,6 +103,7 @@ foreach ($name in $expected.Keys) { Write-Host " $name holds the $($listed.Count) files its list names" } +# The consumers' work folder, outside the repository and its .sandbox/, where Node and TypeScript find none of the repository's own node_modules, as no consumer does. $work = Join-Path ([System.IO.Path]::GetTempPath()) "domql-packages-$([guid]::NewGuid().ToString('N'))" $previousPackages = $env:NUGET_PACKAGES diff --git a/scripts/module-manifest.mjs b/scripts/module-manifest.mjs new file mode 100644 index 0000000..4abbe38 --- /dev/null +++ b/scripts/module-manifest.mjs @@ -0,0 +1,37 @@ +/** + * module-manifest — the manifest Nexo makes of DOMQL's own module, written into the module DOMQL creates its module and registry under + */ + +import { readFile, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { BrowserModule } from '../src/dom/BrowserModule.mjs'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +/** Where DOMQL's sources hold the manifest. */ +export const moduleManifestPath = resolve(root, 'src', 'dom', 'ModuleManifest.mjs'); + +/** The text of the module holding the manifest Nexo makes of DOMQL's own module, as the Nexo DOMQL builds against makes it. */ +export function moduleManifestText() { + return [ + '/**', + " * ModuleManifest — the manifest Nexo makes of DOMQL's own module, which DOMQL creates its module and registry under; written by scripts/module-manifest.mjs", + ' */', + '', + `export const ModuleManifest = Object.freeze(${JSON.stringify(BrowserModule.prepare())});`, + '', + ].join('\n'); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const text = moduleManifestText(); + const current = await readFile(moduleManifestPath, 'utf8').catch(() => null); + + if (current === text) { + console.log(`${moduleManifestPath} is current`); + } else { + await writeFile(moduleManifestPath, text); + console.log(`Wrote the manifest of DOMQL's own module to ${moduleManifestPath}`); + } +} diff --git a/scripts/packages/npm.files b/scripts/packages/npm.files index 2561e0f..fc8672c 100644 --- a/scripts/packages/npm.files +++ b/scripts/packages/npm.files @@ -5,6 +5,7 @@ README.md package.json src/Versions.mjs src/common/ObjectUtils.mjs +src/connections/Connection.mjs src/dom/Behaviors.mjs src/dom/BrowserExecutionImplementations.mjs src/dom/BrowserModule.mjs @@ -18,6 +19,7 @@ src/dom/EventListener.mjs src/dom/ExecutionHandle.mjs src/dom/FocusChain.mjs src/dom/FrameSchedule.mjs +src/dom/ModuleManifest.mjs src/dom/MutationObservers.mjs src/dom/ObservationSession.mjs src/dom/Observations.mjs diff --git a/spec/README.md b/spec/README.md index 976c363..8886ea4 100644 --- a/spec/README.md +++ b/spec/README.md @@ -1,12 +1,12 @@ -# DOMQL Specification v1.0.0-preview.1 +# DOMQL Specification v1.0.0-preview.2 -DOMQL reads the DOM and shapes what it reads as data, keeps that data current as the document changes, delivers the page's events as data, and carries out the executions its own module and its extensions declare. Its queries are scripts written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), whose specification holds two contracts: the language's, what a script means, and the runtime's, how a host binds, resolves and evaluates a script. DOMQL declares the DOM as Nexo's domain, in a module like any other, and is the host that carries each query out against a document. It adds no language rule: a rule of the language or of its runtime is Nexo's, and this specification links to it. +DOMQL reads the DOM and shapes what it reads as data, keeps that data current as the document changes, delivers the page's events as data, and carries out the executions its own module and its extensions declare. Its queries are scripts written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), whose specification holds two contracts: the language's, what a script means, and the runtime's, how a host binds, resolves and evaluates a script. DOMQL declares the DOM as Nexo's domain, in a module like any other, and is the host that carries each query out against a document. It adds no language rule: a rule of the language or of its runtime is Nexo's, and this specification links to it. This specification is the authoritative contract for DOMQL. It states what DOMQL is, not how far its implementation has come: [the status overview](../docs/features-status.md) says what this repository implements, and [the design](../docs/domql-design.md) how it is built. -**Version.** This specification describes DOMQL's version `1.0.0-preview.1`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.1`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. +**Version.** This specification describes DOMQL's version `1.0.0-preview.2`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.3`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. ## What it covers @@ -14,8 +14,8 @@ Five layers meet whenever a query runs. Nexo's specification covers the first tw | Layer | What it owns | Documents | | --- | --- | --- | -| The language | What a query means: its imports, syntax, names and scope, values and types, expressions and functions, members, extensions, and the contracts a vocabulary keeps | [Nexo's language](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | -| The runtime | Binding, resolving and evaluating a script for a host, the modules it registers, its definitions and its results | [Nexo's runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/hosting.md) | +| The language | What a query means: its imports, syntax, names and scope, values and types, expressions and functions, members, extensions, and the contracts a vocabulary keeps | [Nexo's language](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | +| The runtime | Binding, resolving and evaluating a script for a host, the modules it registers, its definitions and its results | [Nexo's runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/hosting.md) | | DOMQL's module | The DOM as Nexo's domain: its nodes and shadow trees, its members, its states among them, its event sources and event types, its executions, and the observations that follow its changes | [Nodes and shadow trees](nodes-and-shadow-trees.md), [vocabulary](vocabulary.md), [events](events.md) | | DOMQL, the host | Carrying a query out against a document: evaluating it, watching it, and invoking its host calls, delivering its events, carrying out its executions and keeping its behaviors where their module reaches them, through the API a caller uses | [Queries](queries.md), [evaluation](evaluation.md), [watches](watches.md), [results](results.md), [events](events.md), [executions](executions.md), [behaviors](behaviors.md), [the API](api.md), [errors](errors.md) | | The caller | The application around DOMQL: which queries it makes, when it carries each out, and what it does with each result | The caller's own | @@ -38,6 +38,7 @@ Start with [queries](queries.md), which shows a query with its parameters and it 8. [Executions](executions.md): executing once and running continuously. 9. [Behaviors](behaviors.md): an operation's owner, a behavior's running instance, the commands that reach it, its occurrences and their acknowledgment, handling inside the native dispatch, and the state it offers. 10. [The API](api.md): every entry point, operation and handle, the events a handle raises, their order across handles, lifetimes and errors. -11. [Errors](errors.md): the codes of DOMQL's own conditions. -12. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. -13. [Terms](terms.md): the glossary. +11. [Connections](connections.md): DOMQL's operations carried across a boundary as messages, the requests a host sends and the deliveries it receives, and how a watch's are paced. +12. [Errors](errors.md): the codes of DOMQL's own conditions. +13. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. +14. [Terms](terms.md): the glossary. diff --git a/spec/api.md b/spec/api.md index d756dc1..f340f41 100644 --- a/spec/api.md +++ b/spec/api.md @@ -40,7 +40,7 @@ const size = domql.evaluate('panel.size', { panel }); const panelQuery = domql.query('panel { size = it.size }', { panel }); const now = panelQuery.evaluate(); // Its result now. const width = panelQuery.select('size', 'width'); // Its width alone: width.evaluate() runs the query and answers it. -const watch = panelQuery.watch({ signal }); // Its result kept current until the signal aborts. +const watch = panelQuery.watch({ acceptPartialObservation: true, signal }); // Its result kept current until the signal aborts, but for a transform, which no observer reports. ``` Both ways offer the same six operations. Which one a query takes follows from what it does: a query that reads the page is evaluated or watched, one that listens to it is subscribed to, and one that changes it is executed or run. @@ -69,7 +69,7 @@ Each entry point and operation is listed here with what it takes, and the sectio | Entry point or operation | Meaning | | --- | --- | -| `domql.query(text, bindings?, options?)`, `domql.query(definition, bindings?, options?)` | Makes a query object, binding its parameters, each of the type `options.types` [declares](queries.md#making-a-query-declared-types) for it, as [making a query](queries.md#making-a-query) sets out | +| `domql.query(text, bindings?, options?)`, `domql.query(definition, bindings?, options?)` | Makes a query object, binding its parameters, each of the type `options.types` [declares](queries.md#making-a-query-declared-types) for it, read from the manifest `options.manifest` gives, as [making a query](queries.md#making-a-query) sets out | | `domql.evaluate(text, bindings?, options?)`, and `domql.evaluateAsync`, `domql.watch`, `domql.executeAsync` and `domql.run` alike; `domql.subscribe(text, bindings, handler, options?)` | Runs a query directly, in one call, as the query object `domql.query(text, bindings)` makes runs it, as [two ways to run a query](#api-two-ways-to-run-a-query) sets out; each takes a definition in place of the text too | | `query.definition` | The query's immutable definition, without its bindings | | `query.with(bindings)` | A new query with the same definition, bound to these bindings, of the types the query declares | @@ -81,10 +81,12 @@ Each entry point and operation is listed here with what it takes, and the sectio | `query.subscribe(handler, options?)` | Subscribes to a subscription, answering a `DomqlEventListener`, as [subscribing](events.md#subscribing) sets out | | `query.executeAsync(options?)` | Carries out a once execution, answering a promise of its result, as [executing once](executions.md#executions-executing-once) sets out | | `query.run(options?)` | Starts a continuous execution, answering a `DomqlExecutionHandle`, as [running continuously](executions.md#executions-running-continuously) sets out | -| `domql.format(source)` | The canonical text of a text, a definition or a query object, as [formatting](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/definition.md#definition-canonical-text) sets out | -| `domql.createModule(name, contents)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out | -| `domql.registerModule(module)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out | -| `domql.registerModuleLoader(name, load)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | +| `domql.format(source)` | The canonical text of a text, a definition or a query object, as [formatting](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/definition.md#definition-canonical-text) sets out | +| `domql.prepare(modules, options?)` | Checks modules and queries ahead of time, answering the manifest a host gives back as `manifest`, as [preparing ahead of time](vocabulary.md#extension-modules-manifests) sets out | +| `domql.createModule(name, contents, options?)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | +| `domql.registerModule(module, options?)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | +| `domql.registerModuleLoader(name, load, options?)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out, its module registered with the options given | +| `domql.connect(deliver, options?)` | Opens a connection that carries the instance's operations across a boundary as messages, as [connections](connections.md) set out, which [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) opens | | `domql.loadModulesAsync(modules)` | Loads and registers every module named that the instance doesn't hold yet, answering a promise, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | | `domql.info` | Which build this is and what it follows, in `versions`: `runtime`, the runtime release version, which the package and the bundle carry, its sources reporting the same; `specification`, the version of DOMQL's specification it follows; and `language`, the language specification version the Nexo runtime it runs on follows, its `nexo.info.versions.language` | @@ -177,6 +179,6 @@ An operation that answers a handle, given a signal already aborted, answers a di ## Errors -Every failure is a `NexoError` with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md) set out, and a caller reads the code, the kind and the location rather than the message. A condition of Nexo's keeps its `NEXO` code, and one of DOMQL's own takes a `DOMQL` code, as [errors](errors.md) catalog them. A failure is reported where it arises: a syntax or structure failure as the query is made; a module failure as a module is created or registered, or as a request that uses a declaration without an implementation is carried out; a validation failure as the request is resolved; and an evaluation failure as it is carried out, a missing window among them. +Every failure is a `NexoError` with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md) set out, and a caller reads the code, the kind and the location rather than the message. A condition of Nexo's keeps its `NEXO` code, and one of DOMQL's own takes a `DOMQL` code, as [errors](errors.md) catalog them. A failure is reported where it arises: a syntax or structure failure as the query is made; a module failure as a module is created or registered, or as a request that uses a declaration without an implementation is carried out; a validation failure as the request is resolved; and an evaluation failure as it is carried out, a missing window among them. A failure no handler or caller receives, as an `"error"` event no listener receives, a failure of an `"error"` handler or of a subscription's handler, or one a once execution reports after its caller stopped waiting, goes to the **window's error reporting**, its `reportError`, or the console where the window has none. A watch, an event listener and a waiting evaluation let go of every observation they hold even where letting go of one fails: each attempts every cleanup, reports a failure of one to the window's error reporting, and never lets it replace its result, its error or its cancellation. diff --git a/spec/behaviors.md b/spec/behaviors.md index d46d37a..bb495e4 100644 --- a/spec/behaviors.md +++ b/spec/behaviors.md @@ -66,6 +66,15 @@ What a behavior reports, a drop, a move, a placement or an editor's change, is a The `deliver` an event source of a module's own implementation receives answers the same acknowledgment, of its one subscription. + + +**Answers.** An event source that declares `answers`, the type of an answer in type notation, written as a [declared binding's](queries.md#making-a-query-declared-types) type is, is answered by its subscriptions, so a behavior that asks what to do learns it from the same delivery: + +- **What a subscription answers.** Its handler answers the occurrence with what it returns, or with what the promise it returns fulfils with. +- **What `deliver` answers.** Its promise fulfils, once every subscription has applied the occurrence, with the answer of the first to subscribe, captured as the declared type as a binding of that type is: its declared fields alone, null where the handler answers nothing and the type takes null. The answers of the subscriptions after it are not taken, so nothing checks them, as for a source that declares none. +- **An answer the type refuses** is the handler's failure: the promise rejects with `DOMQL5025`, located at the subscription, its `cause` the refusal, which goes to the window's error reporting as well. A notation that names no type is refused so too, as the first answer is captured, since a notation is read as a binding's type is, where a value is given. +- **A source that declares none** fulfils with undefined, whatever its handlers return. + ## Handling inside the native dispatch diff --git a/spec/connections.md b/spec/connections.md new file mode 100644 index 0000000..0fd996b --- /dev/null +++ b/spec/connections.md @@ -0,0 +1,110 @@ +# Connections + + + +A **connection** carries DOMQL's operations across a boundary as messages, for a host whose code runs somewhere else, as a .NET application's does. The host sends **requests** in batches, and DOMQL answers each batch. DOMQL sends back **deliveries**: a watch's changes, a subscription's events, a result that settled later, and failures. + +```js +const connection = domql.connect(deliveries => host.receiveAsync(deliveries)); + +const answers = await connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'panel-7', query: { key: 'width', text: '{ width = panel.layoutSize?.inline }' }, bindings: { panel } }, + { request: 'watch', handle: 2, owner: 'panel-8', query: 'width', bindings: { panel: other } }, +]); +// [{ snapshot: { width: 640 } }, { snapshot: { width: 320 } }] +``` + +[DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) is DOMQL's own host of a connection, for .NET applications. + +In this document: + +1. [Opening one](#connections-opening) +2. [Requests and their answers](#connections-requests) +3. [Deliveries](#connections-deliveries) +4. [Pacing](#connections-pacing) +5. [Owners, handles and generations](#connections-handles) +6. [Failures and closing](#connections-failures) + + + +## Opening one + +`domql.connect(deliver, options?)` opens a connection on this instance of DOMQL, its registry and its modules among it. + +- **`deliver(deliveries)`** is the host's receiver. DOMQL calls it with every delivery of one task, in the order they happened. It answers a promise of one answer for each delivery, which settles once the host has applied them all. A `deliver` that is no function is refused with `DOMQL2022`. +- **`options.window`** is the window the connection's operations run in, the global one by default. +- **`connection.close()`** ends every handle the connection started. Each request after it answers `DOMQL5027`. `connection.isClosed` says whether it has closed. + + + +## Requests and their answers + +`connection.requestAsync(requests)` carries out a list of requests in order. It answers a promise of their answers, one for each, in order. The promise settles once the task that carried them out has ended, so whatever that task settled is final: + +- A watch whose first evaluation ran in the task answers with its snapshot. +- An execution or an evaluation that settled in the task answers with its value. +- What still waits answers `{ pending: true }`. Its result arrives as a delivery of its handle. + +| Request | Fields | Answer | +| --- | --- | --- | +| `watch` | `handle`, `owner`, `query`, `bindings`, `options`: `schedule`, `delay`, `reportOn`, `acceptPartialObservation` | `{ snapshot }`; or `{ pending: true }`, the snapshot delivered whole, with `error` where the first evaluation failed | +| `subscribe` | `handle`, `owner`, `query`, `bindings`, `options`: `throttle`, `reactions` | `{}` | +| `run` | `handle`, `owner`, `query`, `bindings` | `{}` | +| `execute` | `handle`, `owner`, `query`, `bindings` | `{ value }` or `{ pending: true }` | +| `evaluate` | `handle`, `owner`, `query`, `bindings` | `{ value }` or `{ pending: true }`, waiting for maintained members as `evaluateAsync` does | +| `load` | `handle`, `modules` | `{ value: null }` or `{ pending: true }`, as `loadModulesAsync` loads them | +| `update` | `handle`, `generation`, `bindings`, `options` | A watch watches anew with the new bindings and answers as a `watch` request does. A subscription subscribes anew, and an execution is updated in place, each answering `{}` | +| `refresh` | `handle`, or none for every watch; `generation`; `resample` | `{}`; each watch's snapshot is delivered whole, changed or not | +| `dispose` | `handle` | `{}` | +| `release` | `owner` | `{}`; every handle of the owner ends | + +- **Each request fails alone.** A request that fails answers `{ error }`, and starts no handle. The others of its batch are carried out. +- **Malformed requests.** One that names no request of the table is refused with `DOMQL2023`. A list of requests that is no list rejects the whole call with `DOMQL2023`. +- **Queries cross once.** A request names its query as `{ key, text }`, or `{ key, definition }`, the first time. It may give `types` and `manifest` beside it, as [`domql.query`](queries.md#making-a-query-declared-types) takes them. Every later request names the query by its key alone. A key no earlier request made is refused with `DOMQL2024`. A query whose making was refused is made by no key, so the host sends its text again. +- **Bindings** are the values the transport carried. An element the transport revives, as a .NET element reference becomes the element it names, binds as an element. +- **Reactions** are given in the connection's own form, each `{ query, bindings }`. + + + +## Deliveries + +Each delivery names the handle it belongs to: + +| Delivery | What it holds | +| --- | --- | +| `{ handle, generation, snapshot }` | A watch's snapshot whole: its first, where its request answered pending; after a refresh; or where it is shorter than the change set | +| `{ handle, generation, changes }` | A watch's [change set](results.md#results-change-sets) from the snapshot delivered before it, change sets concatenated where several arose while one was waiting, as [D65](../docs/decisions.md#d65) records | +| `{ handle, generation, event }` | A subscription's event, its projected value | +| `{ handle, value }` | The result of an execution, an evaluation or a load that answered pending | +| `{ handle, generation, error }` | A failure: a watch's evaluation, a subscription's event, or what a continuous execution reports | + +- **One task, one batch.** The deliveries of one task cross in one call to `deliver`, in the order they happened, across handles. +- **The answers.** `deliver`'s promise answers one answer for each delivery. An event's answer is the host's answer to it. Where the event source declares [`answers`](behaviors.md#behaviors-answers), that answer answers the source. Every other answer is ignored. +- **A host keeps its copy** of a watch's result by applying each delivery in order, as [keeping a copy of a result](results.md#results-keeping-a-copy) sets out. + + + +## Pacing + +- **A watch waits for its acknowledgment.** A watch's next delivery waits until `deliver` has settled the batch holding its last one. Whatever arises meanwhile waits, joined: + - Two change sets join into one, concatenated, unless the snapshot whole is shorter. + - A snapshot whole replaces everything waiting before it. + - A failure keeps its place after what came before it. +- **An event never waits.** It crosses with the task it happened in, behind nothing, and is never joined or dropped, so a host hears events in the order the page did, as [D69](../docs/decisions.md#d69) requires. Its acknowledgment settles once the host has applied it: `deliver`'s promise settles the event's acknowledgment in the browser, so an event source that waits for it waits for the host. +- **A rejected batch.** Where `deliver`'s promise rejects, each event of the batch is rejected in the browser. Each watch of the batch waits until it is refreshed, which delivers its snapshot whole. +- **A limit.** Where earlier batches have left 4,096 deliveries the host has not acknowledged, the next batch closes the connection, reporting `DOMQL5026` to the window, rather than hold every occurrence for a host that answers none. One task of many deliveries crosses whole. + + + +## Owners, handles and generations + +- **Handles.** A request that starts an operation names its handle: a string or a number. A handle that is not a string or a number, or one that still runs, is refused with `DOMQL2025`. +- **Owners.** A request names its owner, which every implementation the operation reaches receives as `env.owner`, as [the owner](api.md#api-the-owner) sets out. It is a string, a number or null, since a host's message holds no object twice. Any other owner is refused with `DOMQL2025`. +- **Generations.** A request may give its handle's generation, a whole number, 0 where none was given. Each delivery of the handle carries the generation it was made at. A host that updated a handle drops a delivery of an earlier generation. +- **Overtaking an answer.** A delivery may reach the host before its request's answer does. A host holds a watch's deliveries until its request is answered, and applies them in order after the snapshot the answer holds. + + + +## Failures and closing + +A failure crosses as `{ code, kind, message, location }`, as the [`NexoError`](api.md#api-errors) DOMQL or Nexo made gives it. A failure of a module's own code crosses as its message alone. The codes this document names are catalogued with DOMQL's others, in [errors](errors.md). diff --git a/spec/errors.md b/spec/errors.md index fc596b5..3a7d510 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -2,9 +2,9 @@ -Every failure DOMQL reports is a `NexoError`, with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md#diagnostics-codes) set out. A caller reads the code, the kind and the location, never the message. +Every failure DOMQL reports is a `NexoError`, with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md#diagnostics-codes) set out. A caller reads the code, the kind and the location, never the message. -- **Nexo's conditions** keep their codes, `NEXO` and four digits, as Nexo's catalogs give them: [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/errors.md) for what a query may express, and [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md) for definitions, bindings, declarations and the API. A Nexo error passing through DOMQL keeps its code and takes no second one. +- **Nexo's conditions** keep their codes, `NEXO` and four digits, as Nexo's catalogs give them: [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/errors.md) for what a query may express, and [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md) for definitions, bindings, declarations and the API. A Nexo error passing through DOMQL keeps its code and takes no second one. - **DOMQL's own conditions** take codes of DOMQL's prefix, `DOMQL` and four digits, in the ranges Nexo's kinds use, as the tables below give them. - **A code is stable.** It names its condition, never its wording. A new condition takes a new code, and a retired code is never reused. @@ -37,7 +37,7 @@ A caller's use of the API, refused where it is made. | `DOMQL2010` | `env.observe` given a request without a type or a target, or a `notify` that is no function | | `DOMQL2011` | `env.frame` given a callback that is no function or a phase neither `write` nor `read`, or in a window without animation frames | | `DOMQL2012` | `env.measureUnder` given an element that is none, a class that is no one token, or a `read` that is no function | -| `DOMQL2013` | `domql.registerModuleLoader` given a name that is no module's, a `load` that is no function, or a name a loader is registered for already | +| `DOMQL2013` | `domql.registerModuleLoader` given a name that is no module's, a `load` that is no function, options that are no object, or a name a loader is registered for already | | `DOMQL2014` | `domql.loadModulesAsync` given neither a query object, a definition, a text nor a list of module names | | `DOMQL2015` | A subscription's `reactions` given anything but a list of query objects of the instance | | `DOMQL2016` | A watch's `sourceOf` given a path that ends at no list's item | @@ -45,6 +45,11 @@ A caller's use of the API, refused where it is made. | `DOMQL2018` | A subscription given both `throttle` and `reactions` | | `DOMQL2019` | A watch's `delay` that is no number above 0, given to a schedule other than `delayed`, or missing from one that is | | `DOMQL2020` | A watch's `reportOn` that is no list of paths | +| `DOMQL2021` | A query `domql.prepare` is given that gives `imports` of its own, since DOMQL reads its text with `Domql` supplied | +| `DOMQL2022` | `domql.connect` given a deliver that is no function | +| `DOMQL2023` | A [connection's](connections.md#connections-requests) request that names no request it carries out, or a list of requests that is no list | +| `DOMQL2024` | A connection's request naming a query by a key no earlier request made | +| `DOMQL2025` | A connection's request whose handle is no string or number, runs already, or runs no operation of the kind it asks for; or whose owner is no string, number or null | @@ -85,6 +90,7 @@ A module refused as it is created or registered, a module loaded on request that | `DOMQL4013` | An event source of a behavior declaring an `impl` or parameters, which DOMQL carries out | | `DOMQL4014` | A module's loader answering no module of its name | | `DOMQL4015` | A module loaded that is neither registered nor given a loader | +| `DOMQL4016` | An `answers` declared by anything but an event source, or that is no string, or an empty one | @@ -118,3 +124,9 @@ A failure while a request is carried out, located in the query where it concerns | `DOMQL5022` | A maintained observation failing to take the new sample a refresh asked for, its failure the error's `cause` | | `DOMQL5023` | A module's loader failing, its failure the error's `cause` | | `DOMQL5024` | An occurrence a throttled subscription dropped for a later one | +| `DOMQL5025` | An answer a subscription gave an occurrence that the type its event source declares it answers refuses, or whose notation names no type, the refusal the error's `cause` | +| `DOMQL5026` | A connection whose host left as many deliveries unacknowledged as its [limit](connections.md#connections-pacing) holds, which the next batch closes | +| `DOMQL5027` | A request or a delivery of a connection that has closed | +| `DOMQL5028` | Reserved for [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET): a result the type a query maps it onto can't hold | +| `DOMQL5029` | Reserved for DOMQL.NET: a change set that doesn't apply to a watch's copy, which then asks for its snapshot whole | +| `DOMQL5030` | Reserved for DOMQL.NET: a batch of requests that could not cross, or a delivery that could not be read | diff --git a/spec/evaluation.md b/spec/evaluation.md index de8f39a..4892d69 100644 --- a/spec/evaluation.md +++ b/spec/evaluation.md @@ -3,7 +3,7 @@ -**Evaluating** a query reads the document once and answers its result. DOMQL evaluates a query as Nexo's [runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-evaluation) evaluates a script, synchronously, against the document it runs against, and each member declares how it reads. A caller evaluates with `evaluate`, which answers at once, or with `evaluateAsync`, which also waits for the browser's first report of what a maintained member reads. +**Evaluating** a query reads the document once and answers its result. DOMQL evaluates a query as Nexo's [runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-evaluation) evaluates a script, synchronously, against the document it runs against, and each member declares how it reads. A caller evaluates with `evaluate`, which answers at once, or with `evaluateAsync`, which also waits for the browser's first report of what a maintained member reads. ```js const query = domql.query('{ size = panel.size, nearEnd = sentinel.intersects({ root = panel }) }', { panel, sentinel }); @@ -12,7 +12,7 @@ query.evaluate(); // Throws an evaluation error: intersects is mainta await query.evaluateAsync(); // { size: { width: 640, height: 480 }, nearEnd: false } ``` -Evaluating a query is read-only, as [Nexo requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads) of every vocabulary. A measurement that needs the document changed first, such as measuring columns at their intrinsic widths under a temporary class, is an [execution](executions.md) of its own. +Evaluating a query is read-only, as [Nexo requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads) of every vocabulary. A measurement that needs the document changed first, such as measuring columns at their intrinsic widths under a temporary class, is an [execution](executions.md) of its own. In this document: @@ -28,7 +28,7 @@ In this document: `query.evaluate(options?)` resolves the query, then evaluates it once against the document in a single synchronous pass, following the resolution rather than looking names up again. What an evaluation reads is always the document as it is. Its options are `window` and [`owner`](api.md#api-the-owner). - **The result** is a detached copy, frozen, that holds nothing of the document. A structure a member answers is taken by its data shape alone, the properties its type declares, each read as the value offers it, a getter's included, so a property beside them never reaches a result and an instance of a class answers as the properties its type declares. -- **A member that breaks its contract.** A member whose function answers a type other than the one it declares has broken its contract, and the evaluation fails with an evaluation error naming the member and where it stands in the query; so does a member whose function throws, with the thrown error as its cause. A request that uses a member a module declares and does not implement is refused before anything is evaluated, with a module error naming the declaration, as Nexo's [declarations without an implementation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules-declarations-without-an-implementation) set out. +- **A member that breaks its contract.** A member whose function answers a type other than the one it declares has broken its contract, and the evaluation fails with an evaluation error naming the member and where it stands in the query; so does a member whose function throws, with the thrown error as its cause. A request that uses a member a module declares and does not implement is refused before anything is evaluated, with a module error naming the declaration, as Nexo's [declarations without an implementation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-declarations-without-an-implementation) set out. - **A maintained member** cannot be read in a single synchronous pass and fails `evaluate`, with an evaluation error naming the member; `evaluateAsync` waits for it. - **A request of another kind** is refused, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. @@ -36,7 +36,7 @@ In this document: ## How DOMQL's members read -Each member declares how it reads by [Nexo's contract](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads): DOMQL's members read fresh from the document, as an attribute or a box is, maintained by a browser observation, as `intersects` is, captured, as an event's data is, or derived, as a list's `count` is. +Each member declares how it reads by [Nexo's contract](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads): DOMQL's members read fresh from the document, as an attribute or a box is, maintained by a browser observation, as `intersects` is, captured, as an event's data is, or derived, as a list's `count` is. A member whose result depends on what happened before, as well as on the document as it is, is captured: it keeps that history while a watch or an event listener holds it, and documents what an evaluation once reports without it. diff --git a/spec/events.md b/spec/events.md index c2aff96..13c7ec9 100644 --- a/spec/events.md +++ b/spec/events.md @@ -3,7 +3,7 @@ -An **event source** delivers things that happened, as a click or a key pressed, and a **subscription** shapes each event it delivers into data, read as the event is dispatched. An event source is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) DOMQL carries out by subscribing to it, and a subscription is a query whose chain ends in one: a caller subscribes to it, and the caller's handler receives one result for each event, immutable data that holds no event object and no element. +An **event source** delivers things that happened, as a click or a key pressed, and a **subscription** shapes each event it delivers into data, read as the event is dispatched. An event source is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) DOMQL carries out by subscribing to it, and a subscription is a query whose chain ends in one: a caller subscribes to it, and the caller's handler receives one result for each event, immutable data that holds no event object and no element. ```js const clicks = domql.query(` @@ -30,7 +30,7 @@ In this document: ## Event sources -An event source is subscribed to, and never read or watched: DOMQL starts it as its caller subscribes, and has each event it delivers projected through the object expression that follows it, as Nexo [projects a value its host supplies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls), each event captured as the members of the type its event type maps to. +An event source is subscribed to, and never read or watched: DOMQL starts it as its caller subscribes, and has each event it delivers projected through the object expression that follows it, as Nexo [projects a value its host supplies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls), each event captured as the members of the type its event type maps to. | Available on | Source | Delivers | Fixed | | --- | --- | --- | --- | @@ -50,7 +50,7 @@ A subscription listening in the capture phase observes alone, as every subscript ## Event types -DOMQL's module declares the [type selector](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-type-selectors) `event`, whose keys are the event types, and a module extends it with event types of its own as it extends DOMQL's types. The built-in event types, the type each maps to, and the members each event offers: +DOMQL's module declares the [type selector](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-type-selectors) `event`, whose keys are the event types, and a module extends it with event types of its own as it extends DOMQL's types. The built-in event types, the type each maps to, and the members each event offers: | Event types | Type | Members | | --- | --- | --- | diff --git a/spec/examples.md b/spec/examples.md index eccc860..cd602d1 100644 --- a/spec/examples.md +++ b/spec/examples.md @@ -85,7 +85,7 @@ With no item selected, `current` is null. With an empty panel, `items` is an emp `intersects` reads maintained values, so the result comes from an asynchronous evaluation or a watch, which wait for its first samples; a synchronous evaluation of the query fails, since it cannot wait. -Watching the query requires accepting partial observation, since `all`, `style`, `grid`, `rect` and `first` are partly observable, which the refusal names as `node.all`, `element.style`, `element.grid`, `element.rect` and `node.first`, each with the changes it misses; the watch then follows the items the panel holds, each item's height, attributes and intersection, the panel's size and focus, the sentinel's intersection, the media query and the document's visibility. +Watching the query requires accepting partial observation, since `all`, `size`, `style`, `grid`, `rect` and `first` are partly observable, which the refusal names as `Node.all`, `Element.size`, `Element.style`, `Element.grid`, `Element.rect` and `Node.first`, each with the changes it misses; the watch then follows the items the panel holds, each item's height, attributes and intersection, the panel's size and focus, the sentinel's intersection, the media query and the document's visibility. diff --git a/spec/executions.md b/spec/executions.md index 69b86c3..eb5d2f7 100644 --- a/spec/executions.md +++ b/spec/executions.md @@ -3,7 +3,7 @@ -An **execution** is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) DOMQL carries out to change the page. A **once execution** changes it once and answers its result; a **continuous execution** starts something that runs on the page until it is updated or disposed, and has no result, a [behavior](behaviors.md) whose running instance the commands of its module reach. DOMQL's module declares its [built-in executions](vocabulary.md#built-in-executions), each one platform call named by the verb it carries out, as [properties and functions](vocabulary.md#vocabulary-properties-and-functions) set out, and an [extension module](vocabulary.md#extension-modules) declares its own, each with its execution mode and the implementation that carries it out. `executeAsync` carries out a once execution and `run` a continuous one, and no other operation carries out either, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. +An **execution** is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) DOMQL carries out to change the page. A **once execution** changes it once and answers its result; a **continuous execution** starts something that runs on the page until it is updated or disposed, and has no result, a [behavior](behaviors.md) whose running instance the commands of its module reach. DOMQL's module declares its [built-in executions](vocabulary.md#built-in-executions), each one platform call named by the verb it carries out, as [properties and functions](vocabulary.md#vocabulary-properties-and-functions) set out, and an [extension module](vocabulary.md#extension-modules) declares its own, each with its execution mode and the implementation that carries it out. `executeAsync` carries out a once execution and `run` a continuous one, and no other operation carries out either, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. ```js // A built-in once execution, answering whether focus landed on the field. @@ -33,8 +33,8 @@ In this document: `query.executeAsync(options?)` carries out a once execution and answers a promise of its result; its options are `window`, [`owner`](api.md#api-the-owner) and `signal`. Each call executes it again. One carried out while a query is evaluated, by a member's implementation, rejects with `DOMQL5021`, executing nothing, since a member reads alone; `run` throws it alike. - **Order.** An execution's implementation is invoked within the call that carries it out, once its preparation has run, so executions carried out in one task, once or continuous, are invoked in the order they are carried out, each seeing what the ones before it changed, as opening a dialog and then focusing a field within it. -- **Preparation first.** Its receiver and its arguments are prepared first, synchronously, as [Nexo's preparation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls) evaluates them; a failure there rejects the promise and executes nothing. A skipped preparation, where the receiver is null, or an argument whose parameter propagates null is null, executes nothing, and the promise resolves to null, as a member's null is; a null argument whose parameter accepts null is passed as it stands, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. -- **The result.** The execution's implementation receives the receiver, the arguments, the environment and the signal, and may answer its result or a promise of it. The result must be of the type the execution declares, as Nexo [captures a supplied value](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls-capturing), and data alone; a result of another type rejects the promise with an evaluation error naming the execution, and an execution that declares no result resolves to null. An object expression that follows the execution is evaluated against the result once it arrives, as `evaluate` evaluates a query, so a member maintained by an observation fails it, and the promise answers detached, immutable data. +- **Preparation first.** Its receiver and its arguments are prepared first, synchronously, as [Nexo's preparation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls) evaluates them; a failure there rejects the promise and executes nothing. A skipped preparation, where the receiver is null, or an argument whose parameter propagates null is null, executes nothing, and the promise resolves to null, as a member's null is; a null argument whose parameter accepts null is passed as it stands, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. +- **The result.** The execution's implementation receives the receiver, the arguments, the environment and the signal, and may answer its result or a promise of it. The result must be of the type the execution declares, as Nexo [captures a supplied value](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls-capturing), and data alone; a result of another type rejects the promise with an evaluation error naming the execution, and an execution that declares no result resolves to null. An object expression that follows the execution is evaluated against the result once it arrives, as `evaluate` evaluates a query, so a member maintained by an observation fails it, and the promise answers detached, immutable data. - **Failure.** A failure of the execution, whatever it throws, rejects the promise with an evaluation error naming the execution, whose cause is what was thrown; nothing goes to the error reporting while the caller holds the promise. - **Cancellation.** A signal already aborted rejects with its reason and executes nothing. A signal that aborts while the execution runs rejects the promise with its reason at once, and the execution learns of it through the signal it was given; what it does after that is its own, its result is discarded, and a failure it reports afterwards goes to the window's error reporting, since no caller waits for it. - **No rollback.** An execution can change the document before it fails or is canceled, and DOMQL never undoes what it did; an execution that can be undone offers that as an execution of its own. diff --git a/spec/nodes-and-shadow-trees.md b/spec/nodes-and-shadow-trees.md index a7320a5..ff26c64 100644 --- a/spec/nodes-and-shadow-trees.md +++ b/spec/nodes-and-shadow-trees.md @@ -14,7 +14,7 @@ In this document: ## Nodes -A node is a value of the DOM tree. DOMQL's module declares the nodes as [reference types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#reference-types): `Node`, abstract, and beneath it its kinds, `Element`, `Document`, `DocumentFragment`, a document fragment that is no shadow root, and `ShadowRoot`. DOMQL's `typeOf` recognizes a bound node as the kind it is, never as `Node` itself, and each type's `isInstance` checks membership, so a host may still bind a node declared as a `Node`. `Window` is a reference type of a hierarchy of its own, no node, and so is `Range`, a range of a document a selection holds. Text and comment nodes are none of these kinds, and are refused as bindings. +A node is a value of the DOM tree. DOMQL's module declares the nodes as [reference types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#reference-types): `Node`, abstract, and beneath it its kinds, `Element`, `Document`, `DocumentFragment`, a document fragment that is no shadow root, and `ShadowRoot`. DOMQL's `typeOf` recognizes a bound node as the kind it is, never as `Node` itself, and each type's `isInstance` checks membership, so a host may still bind a node declared as a `Node`. `Window` is a reference type of a hierarchy of its own, no node, and so is `Range`, a range of a document a selection holds. Text and comment nodes are none of these kinds, and are refused as bindings. diff --git a/spec/queries.md b/spec/queries.md index a1b9a1a..49eceb7 100644 --- a/spec/queries.md +++ b/spec/queries.md @@ -66,7 +66,7 @@ A caller can take that result once, keep it current as the document changes, or // From text, binding its parameters by name. const panelQuery = domql.query(` panel { - size = it.size, + size = it.layoutSize, hasFocus = it.focusWithin } `, { panel }); @@ -82,7 +82,7 @@ const fromDefinition = domql.query(panelQuery.definition, { panel }); ### Its imports -A query uses the vocabulary of the modules it imports, as Nexo's [imports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/modules.md#scripts-imports) set out, and DOMQL's own module, `Domql`, is imported by every query. +A query uses the vocabulary of the modules it imports, as Nexo's [imports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/modules.md#scripts-imports) set out, and DOMQL's own module, `Domql`, is imported by every query. - **DOMQL supplies `Domql`.** DOMQL reads every query's text with the import `Domql` supplied, so a query reads the DOM's members, `Domql.document` and `Domql.window`, and names DOMQL's types, as `Element`, without writing `import Domql`. Writing it as well is harmless. - **Another module is imported by the query.** A query that uses a module its caller registered begins with that module's import, `import Charts`, and reads the members its extensions add to DOMQL's types with `:`, as `panel:palette`, as [extension modules](vocabulary.md#extension-modules) set out. Registering a module adds nothing to a query's imports, so a query that does not import a module reads the same before the module is registered and after. A module [loaded on request](vocabulary.md#extension-modules-loading) is loaded before a query importing it is carried out, which its imports name. @@ -93,7 +93,7 @@ A query uses the vocabulary of the modules it imports, as Nexo's [imports](https ### Binding its parameters -Each parameter is bound under the name the query uses, with a value Nexo's [script parameters and bindings](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/scripts.md#scripts-script-parameters) allow, and a result is data, which a caller receives in its own language's form. `with` answers a new query whose bindings replace the old ones whole, of the types the query declares; the query it was called on, and every operation running from it, are unaffected. A query can be made without its bindings and bound afterwards, and a required binding that is missing fails before anything is carried out. +Each parameter is bound under the name the query uses, with a value Nexo's [script parameters and bindings](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/scripts.md#scripts-script-parameters) allow, and a result is data, which a caller receives in its own language's form. `with` answers a new query whose bindings replace the old ones whole, of the types the query declares; the query it was called on, and every operation running from it, are unaffected. A query can be made without its bindings and bound afterwards, and a required binding that is missing fails before anything is carried out. A binding is typed from its value, unless the query [declares its type](#making-a-query-declared-types): every value is typed from itself, a null, an empty list and a list holding nulls among them, so a query is made for an element that is not there yet as it is for one that is. @@ -105,7 +105,7 @@ const another = query.with({ panel: otherPanel, ids: [1, 2] }); -**Declared types.** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, as Nexo's [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/bindings.md#runtime-bindings) bind it, where data typed from itself would be of no module's type: +**Declared types.** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, as Nexo's [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/bindings.md#runtime-bindings) bind it, where data typed from itself would be of no module's type: ```js const routed = domql.query("import Forma\nForma.firstKey(routes)", { routes: [{ key: "Enter" }] }, { types: { routes: "List" } }); @@ -115,7 +115,8 @@ const routed = domql.query("import Forma\nForma.firstKey(routes)", { routes: [{ - **Data is captured as the type:** a structure keeps its data shape, a property the data leaves out is null where its type is nullable, a map binds as a dictionary and a set as a list. Data the type doesn't admit refuses the binding (NEXO2045). - **A reference type holds to its contract:** the value belongs to the type, or is null where it is nullable. - **Every binding made from the query keeps the types:** `with`'s, an execution's update and a reaction's. The query keeps a copy of them, so a change its caller makes afterwards reaches none. -- **The options are the bindings':** a declared type that is no string is refused (NEXO2044), and so is an option the bindings take none of (NEXO2048). +- **A manifest.** `options.manifest` gives a manifest [prepared ahead of time](vocabulary.md#extension-modules-manifests): the text is read from the definition it holds, and the query's resolutions from it, where it holds them. Every query made from the query keeps it, as it keeps the types. A manifest of another shape is refused with Nexo's `NEXO4566`. +- **The options are the bindings', and the manifest:** a declared type that is no string is refused (NEXO2044), and so is an option neither takes (NEXO2048). With the first bindings, the result is the following: an object expression following the null `panel` is null, and `ids` is the empty list. @@ -134,7 +135,7 @@ A query belongs to the instance of the library that made it, and an instance ref ## Resolution -A request is resolved before it is first carried out, and resolution validates it against the vocabulary its imports make available, as Nexo's [resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-bindings-and-resolution) sets out; a module a request imports is registered by its caller beforehand. A resolution is kept while Nexo says it is current, so a module registered later leaves a running watch, subscription or execution as it was, unless the module recognizes values its resolution may meet, as [registering a module while requests run](vocabulary.md#extension-modules-registering) sets out. A misspelling or a wrong argument is an error before anything is evaluated; a member's fit to its receiver is checked once the receiver's type is specific enough, which a null receiver's is not; null is always a result. +A request is resolved before it is first carried out, and resolution validates it against the vocabulary its imports make available, as Nexo's [resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-bindings-and-resolution) sets out; a module a request imports is registered by its caller beforehand. A resolution is kept while Nexo says it is current, so a module registered later leaves a running watch, subscription or execution as it was, unless the module recognizes values its resolution may meet, as [registering a module while requests run](vocabulary.md#extension-modules-registering) sets out. A misspelling or a wrong argument is an error before anything is evaluated; a member's fit to its receiver is checked once the receiver's type is specific enough, which a null receiver's is not; null is always a result. `query.resolve(options?)` resolves a request without evaluating anything, and answers its kind, `value`, `subscription` or `execution`, an execution's `executionMode`, null for a request of another kind, and its type, null for an execution that answers no result; it needs no browser. It answers its definition and the declarations it uses as well, each with its `qualifiedName`, `typeAt(path)`, the type a path reaches, and `getLocation(pointer)`, where a pointer into its definition stands in its text. Its options `watch` and `acceptPartialObservation` resolve it as a watch would, so a watch's refusal of a partly observable member, as [accepting partial observation](watches.md#accepting-partial-observation) sets out, is found before a watch starts. @@ -142,7 +143,7 @@ A request is resolved before it is first carried out, and resolution validates i ## Request kinds and their operations -Evaluating, watching or subscribing to a request reads the document and changes nothing, whatever vocabulary it uses; an [execution](executions.md) explicitly requests effects, carried out only when its caller executes or runs it. The request's source decides its kind: a query gives a value, or ends in a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls), which DOMQL carries out as its declaration says, by subscribing to an event source, or by executing once or running continuously an execution of that mode. The one entry point serves every request kind, and resolution refuses an operation the kind does not take before anything is evaluated or started, with a validation error that says what the request does and names the operation it takes: +Evaluating, watching or subscribing to a request reads the document and changes nothing, whatever vocabulary it uses; an [execution](executions.md) explicitly requests effects, carried out only when its caller executes or runs it. The request's source decides its kind: a query gives a value, or ends in a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls), which DOMQL carries out as its declaration says, by subscribing to an event source, or by executing once or running continuously an execution of that mode. The one entry point serves every request kind, and resolution refuses an operation the kind does not take before anything is evaluated or started, with a validation error that says what the request does and names the operation it takes: ```text Cannot execute 'panel.size': it produces a value. @@ -165,7 +166,7 @@ The object `domql.query` answers is a query object, whatever it holds, and what `query.select(...path)` answers a selection, a part of the query's result. A selection belongs to the query, as its definition and bindings do, and every operation on it starts work of its own, where a selected view belongs to a running watch, as [sharing a watch](watches.md#sharing-a-watch) sets out. It offers `select(...path)`, `evaluate(options?)`, `evaluateAsync(options?)` and `watch(options?)`. A path holds the names of written fields, of a dictionary's `entries` and a pair's `key` and `value`, and list indices that are not negative; a local is no field, so it is never part of a path. ```js -const width = panelQuery.select("size", "width"); // As panelQuery.select("size").select("width"). +const width = panelQuery.select("size", "inline"); // As panelQuery.select("size").select("inline"). const currentWidth = await width.evaluateAsync(); @@ -175,6 +176,6 @@ rowsQuery.select(0, "height"); - **A path's shape is checked at once.** `select` refuses, without resolving anything, a path item that is neither a written field's name nor an index that is a whole number and not negative, as `-1` and `1.5` are not. - **A path's fit is checked at resolution.** Whether a field exists, and whether an index applies to a list, is checked when an operation resolves the query, before anything is evaluated or observed; a selection of a query whose vocabulary is not yet registered is therefore made without failing. - **What it gives.** A nullable ancestor and a list index out of range give null, and a list index follows a position, never a particular element. -- **Dictionaries and pairs** are selected in the form a [result holds them](results.md#results-collections), as Nexo's [result paths](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-result-paths) step into them: `select("counts", "entries")` gives a dictionary's entries, `select("counts", "entries", 0, "value")` the value of its first, and `select("range", "key")` a pair's key. Any other name after a dictionary or a pair is refused at resolution. +- **Dictionaries and pairs** are selected in the form a [result holds them](results.md#results-collections), as Nexo's [result paths](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-result-paths) step into them: `select("counts", "entries")` gives a dictionary's entries, `select("counts", "entries", 0, "value")` the value of its first, and `select("range", "key")` a pair's key. Any other name after a dictionary or a pair is refused at resolution. - **The whole query.** A selection reads the whole query's result, so the whole query decides its dependencies, its failures and its readiness. - **Its watch** delivers its first value, each change to that value, and its value again after a failed evaluation. It watches snapshots alone; a caller that wants live state of a smaller result writes that result in DOMQL. diff --git a/spec/results.md b/spec/results.md index c8a0c62..fb5a960 100644 --- a/spec/results.md +++ b/spec/results.md @@ -48,7 +48,7 @@ A snapshot never changes once delivered. A new snapshot reuses every immutable b - **What a change set is.** A change set is a [JSON Patch](https://www.rfc-editor.org/rfc/rfc6902) document limited to `replace`, `add`, `remove` and `move`, whose paths are JSON Pointers into the result; applying it to the result it was computed against gives the new result. A field the change set leaves out is unchanged, and a field that became null is replaced with null. An object expression's fields are fixed, so `add` and `remove` apply to list items alone. - **Lists.** A list whose items descend from elements changes by element: an element entering is added, one leaving is removed, one changing position is moved, and one whose result changed is changed inside its item. Any other list changes by position. -- **Identity.** Two elements can project to the same data, so the identity of each item cannot be read back from a snapshot. Each item is matched by the reference it descends from, its provenance, which Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results-provenance) records beside the result and which neither a result nor a change set ever holds: the source the earliest projection the item descends from read, which Nexo classifies as a reference or as data. A list projected from elements is matched by element, and so are a projection of its items and a list filtered, sliced or ordered from it, each by the element its item first came from. +- **Identity.** Two elements can project to the same data, so the identity of each item cannot be read back from a snapshot. Each item is matched by the reference it descends from, its provenance, which Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results-provenance) records beside the result and which neither a result nor a change set ever holds: the source the earliest projection the item descends from read, which Nexo classifies as a reference or as data. A list projected from elements is matched by element, and so are a projection of its items and a list filtered, sliced or ordered from it, each by the element its item first came from. - **Its source in the browser.** A watch answers the reference an item descends from to a caller in the browser, through [`sourceOf`](watches.md#watching-source-elements), and never in the result. - **Matched by position.** A list no projection built, one an item of which descends from data or from null, and one in which an element stands twice, are matched by position. DOMQL reads the classification Nexo reports, never inferring a reference from the value. - **What a change set reproduces.** A change set takes the result it was computed against to the reconciled snapshot, the one the watch reports, with every comparison and tolerance applied; it never describes a different, raw evaluation. @@ -89,7 +89,7 @@ A number a conditional gave compares within the tolerance of the member its bran ## Dictionaries and pairs -A result holds a dictionary or a pair as data, in the form Nexo [exports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-host-forms) them: a dictionary as `{ entries: [{ key, value }, …] }`, its entries in their order, and a pair as `{ key, value }`. +A result holds a dictionary or a pair as data, in the form Nexo [exports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-host-forms) them: a dictionary as `{ entries: [{ key, value }, …] }`, its entries in their order, and a pair as `{ key, value }`. - **Compared and changed as data.** A watch compares them as it compares any object and list, and a change set addresses them in that form: an entry's value is changed at `/counts/entries/0/value`, and an entry entering or leaving is added or removed at its position in `entries`. - **A key is data.** A numeric key is an entry's `key`, never a list index, and a change set reaches an entry by its position in `entries`, never by its key. A [selection](queries.md#selecting-a-result) steps into them in that form, as `select("counts", "entries", 0, "value")`. diff --git a/spec/terms.md b/spec/terms.md index 6a97702..71f2f74 100644 --- a/spec/terms.md +++ b/spec/terms.md @@ -2,7 +2,7 @@ -Each term this specification uses, what it means, and where its authoritative explanation is. A term here defines nothing its linked document does not, and a term of the language, as a script, a binding, a member, an import, a module or a host call, is [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/terms.md), and one of the runtime, as a registry, a resolution or a module key, is [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/terms.md), each Nexo's. +Each term this specification uses, what it means, and where its authoritative explanation is. A term here defines nothing its linked document does not, and a term of the language, as a script, a binding, a member, an import, a module or a host call, is [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/terms.md), and one of the runtime, as a registry, a resolution or a module key, is [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/terms.md), each Nexo's. In this document: @@ -72,7 +72,7 @@ In this document: | Term | Meaning | Reference | | --- | --- | --- | -| Host call | Nexo's call of a function the host invokes, which ends a query; DOMQL carries each out as an event source or an execution | [Host calls](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) | +| Host call | Nexo's call of a function the host invokes, which ends a query; DOMQL carries each out as an event source or an execution | [Host calls](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) | | Event source | A host call that delivers things that happened, as `on(type)` does | [Event sources](events.md#event-sources) | | Event type | A key of DOMQL's type selector `event`, which names the type its events are captured as | [Event types](events.md#event-types) | | Subscription | A query whose chain ends in an event source, which shapes each event into data | [Events](events.md#events) | diff --git a/spec/vocabulary.md b/spec/vocabulary.md index e87f7ed..82956c6 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -17,7 +17,7 @@ Properties and functions are named in camelCase, and names are case-sensitive. B -**Properties and functions.** The vocabulary follows Nexo's rule for [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions): a property names what its receiver is, has or is in, and a function does work or takes what it needs. +**Properties and functions.** The vocabulary follows Nexo's rule for [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions): a property names what its receiver is, has or is in, and a function does work or takes what it needs. - **A state is a property.** What the user, the browser or the page sets and clears, as whether an element is checked, focused or hovered, is a Boolean property read without a call, `panel.checked`, as [states](#states) set out. - **An execution is a function.** A change DOMQL makes is named by the verb it carries out and called with its parentheses, whether or not it takes an argument, `panel.focus()`, as [executions](#built-in-executions) set out. @@ -42,7 +42,7 @@ In this document: ## Module members -DOMQL's module, `Domql`, declares two [module members](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/modules.md#namespaces-module-members), read through its namespace, each with no receiver: +DOMQL's module, `Domql`, declares two [module members](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/modules.md#namespaces-module-members), read through its namespace, each with no receiver: | Member | Type | Reads | Changes | | --- | --- | --- | --- | @@ -55,7 +55,7 @@ Neither needs a binding, and a caller's binding named `Domql` is read as `~Domql ## Types -DOMQL's module declares each of its types with its members, as Nexo's [declaring a type](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules-declaring-a-type) sets out: its reference types, which a query reads through and a result never holds, and its structured types, which hold data. Its `typeOf` recognizes the values a host binds, and each reference type's `isInstance` checks membership: +DOMQL's module declares each of its types with its members, as Nexo's [declaring a type](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-declaring-a-type) sets out: its reference types, which a query reads through and a result never holds, and its structured types, which hold data. Its `typeOf` recognizes the values a host binds, and each reference type's `isInstance` checks membership: | Reference type | Supertype | What it is | Where a value has the type | | --- | --- | --- | --- | @@ -71,6 +71,7 @@ DOMQL's module declares each of its types with its members, as Nexo's [declaring | Structured type | What it is | Properties | | --- | --- | --- | | `Size` | A width and a height | `width`, `height`: `Number` | +| `LogicalSize` | A box's size along the axes of its writing mode | `inline`, `block`: `Number` | | `Rectangle` | A box's edges and size | `left`, `top`, `right`, `bottom`, `width`, `height`: `Number` | | `Selection` | A text selection's range | `start`, `end`: `Number` | | `DocumentSelection` | The document's selection as it stands | `type`: `String`; `collapsed`: `Boolean`; `rangeCount`: `Number`; `anchorElement`, `focusElement`: `Element?`; `range`: `Range?` | @@ -98,11 +99,11 @@ An element with a layout box whose dimensions are zero has actual measurements o -**Tolerance.** A member that measures layout in CSS pixels declares a [tolerance](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#what-a-member-declares-numeric-tolerance) of 0.05, a twentieth of a pixel, for every number it answers, so a watch reports a measurement only once it moves by more than that from the one it last reported, as [comparing snapshots](results.md#comparing-snapshots) sets out: +**Tolerance.** A member that measures layout in CSS pixels declares a [tolerance](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#what-a-member-declares-numeric-tolerance) of 0.05, a twentieth of a pixel, for every number it answers, so a watch reports a measurement only once it moves by more than that from the one it last reported, as [comparing snapshots](results.md#comparing-snapshots) sets out: - **What it absorbs.** A box settling by a unit of the browser's layout, 1/64 of a pixel in Chromium and WebKit and 1/60 in Firefox, and the rounding of the arithmetic that answers a measurement, as `right` is `left` and `width` added. - **What it reports.** Any move a device pixel shows, which is a quarter of a pixel at a device pixel ratio of 4. A move made in steps smaller than the tolerance is reported once the steps add up to more, since each is compared with the measurement last reported. -- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. +- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `layoutSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. Scrolling reads the same way, along the axes of a box's writing mode: @@ -128,6 +129,7 @@ A property exposes a value, read by property access, and takes no argument. Each | Element | [`clientRect`](#property-element-clientrect) | `Rectangle?` | | Element | [`size`](#property-element-size) | `Size?` | | Element | [`clientSize`](#property-element-clientsize) | `Size?` | +| Element | [`layoutSize`](#property-element-layoutsize) | `LogicalSize?` | | Element | [`scroll`](#property-element-scroll) | `Scroll?` | | Element | [`grid`](#property-element-grid) | `Grid?` | | Element | [`selection`](#property-element-selection) | `Selection?` | @@ -244,9 +246,9 @@ A property exposes a value, read by property access, and takes no argument. Each **Type:** `Size?` **Reads:** Fresh **Tolerance:** [0.05](#vocabulary-tolerance) -**Result.** Its border box's `width` and `height` +**Result.** Its border box's `width` and `height`, as the box is drawn, its own transforms and its ancestors' applied, as `rect` measures it -**Changes.** Observable +**Changes.** Partly observable: its box's size as layout gives it is observed; a transform or an animation, its own or an ancestor's, which changes the box as it is drawn without resizing it, is not, nor the size of an inline box, which flows as fragments no resize observer measures. [`layoutSize`](#property-element-layoutsize) is the size layout gives the box, which every change of it reports @@ -260,6 +262,23 @@ A property exposes a value, read by property access, and takes no argument. Each **Changes.** Partly observable: its border box and its content box are observed, so a scrollbar appearing or going and a border changing are; a border and padding changing so that one grows by as much as the other shrinks, which leaves both boxes as they were, is not + + +### Element: layoutSize + +**Type:** `LogicalSize?` **Reads:** Maintained **Tolerance:** [0.05](#vocabulary-tolerance) + +**Result.** The size layout gives its border box, along the axes of its writing mode, `inline` and `block`, as the browser's resize observation measures it: a transform, its own or an ancestor's, changes how the box is drawn, which [`size`](#property-element-size) answers, and not its layout, which this answers. A box in a vertical writing mode, 40 pixels wide and 300 high, is 300 along its inline axis and 40 along its block axis. + +It is null where the element is laid out as no one box: while it has no layout box, as [measurements and layout](#vocabulary-measurements-and-layout) set out, and while it is an inline box of text and elements, `display: inline` on an element its own content doesn't replace, which flows as fragments no resize observer measures. It is null for a box of no size too, 0 by 0, which a resize observer measures as it measures no box: a box of no size that stops or starts being laid out resizes nothing it reports, so reading both alike keeps every change observed. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an SVG element, which the resize observation measures by its bounding box. It is pending until the browser first reports the element, which it does as it lays the page out, so not while the document is hidden: `evaluate` fails on it, as on any [maintained member](evaluation.md#waiting-for-maintained-members), and `evaluateAsync` and a watch's first snapshot wait for that report. So the first snapshot holds the size as laid out, never a size the box was drawn at before it. + +**Changes.** Observable + +```domql +list.layoutSize?.inline // The space its items have along a line. +(item.layoutSize?.inline ?? 0) > (list.layoutSize?.inline ?? 0) // Whether an item is longer than the line. +``` + ### Element: scroll @@ -608,7 +627,7 @@ An element that is no scroll container is scrolled by 0. Null while it has no la ### List: count, first, last -`count`, `first` and `last` are properties [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`count`, `first` and `last` are properties [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -850,7 +869,7 @@ A box whose overflow is not `visible` along one axis computes `visible` as `auto ### List: item -The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -858,7 +877,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ### List: max, min, sum -`max`, `min` and `sum` are functions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`max`, `min` and `sum` are functions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -866,7 +885,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ### List: where -`where` is a function [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`where` is a function [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -878,7 +897,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ## States -A **state** is what the user, the browser or the page sets and clears over time, as whether an element is checked; a presence, as whether it is focused; or a capability the browser offers, as whether it can share. Each is a Boolean property, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: +A **state** is what the user, the browser or the page sets and clears over time, as whether an element is checked; a presence, as whether it is focused; or a capability the browser offers, as whether it can share. Each is a Boolean property, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: - **Reading one.** A query reads a state where it stands, `it.checked`, or through its module, its receiver first, `Domql.checked(it)`, and each way reaches the one declaration, whose observations follow it. - **Filtering by one.** A query filters by a state with a body, `rows.where(it.checked)`. Only a function has a reference, so `rows.where(Domql.checked)` is refused (NEXO3076). @@ -1101,7 +1120,7 @@ Whether the Tab key reaches it, and in what order, is sequential focus navigatio **True when.** It matches `:autofill`, or `:-webkit-autofill` in a browser that knows no other: the browser filled its value, from a saved address or password, and the user has not edited it since -**Changes.** Partly observable: the user's input and changes in its tree are observed, which the browser fires as it fills a field the user chose a suggestion for; the browser filling a field on its own, as a password manager does as the page loads, fires no event and is not. No observation follows the filling itself, since one would write a stylesheet into the page, which watching never does +**Changes.** Partly observable: the user's input and changes in its tree are observed, which the browser fires as it fills a field the user chose a suggestion for; and so is an animation the page's style starts on it as it is filled or emptied, as a rule for `:autofill` naming one does, `animationstart` and `animationcancel`; the browser filling a field on its own, as a password manager does as the page loads, fires no event and is not, unless the page's style starts such an animation. No observation of DOMQL's own follows the filling itself, since one would write a stylesheet into the page, which watching never does @@ -1210,7 +1229,7 @@ Each reads the element's own attribute under a contract of its own, falling back So `it.checked or it.aria.checked` is whether either says checked, and `it.aria["checked"] == "mixed"` tells a mixed state, which the ARIA view's `checked` answers false for, from the others. The ARIA view's unnamed indexer reads the attribute written on the element, as `it["aria-checked"]` does, and never the element's effective accessibility state. -No other ARIA attribute has a state until one is declared, each with a contract of its own, since not every ARIA attribute is a Boolean; an extension declares one on the ARIA view, a type it does not own, as the [rules for extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions) let any module do. +No other ARIA attribute has a state until one is declared, each with a contract of its own, since not every ARIA attribute is a Boolean; an extension declares one on the ARIA view, a type it does not own, as the [rules for extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions) let any module do. @@ -1495,7 +1514,7 @@ Module code holds a target the same way, through an owned write it runs with [`e ## Built-in conversions -A query converts with the four conversions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#vocabulary-conversions) declares between the language's types of data, which DOMQL's module, owning none of those types, declares none of; each rejects a value it cannot convert: +A query converts with the four conversions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#vocabulary-conversions) declares between the language's types of data, which DOMQL's module, owning none of those types, declares none of; each rejects a value it cannot convert: | From | To | Converts | | --- | --- | --- | @@ -1508,7 +1527,7 @@ A query converts with the four conversions [Nexo's own module](https://github.co ## Observations -A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as eleven observation types, each animation frame as a twelfth, and the state a behavior offers as a thirteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. +A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as twelve observation types, each animation frame as a thirteenth, and the state a behavior offers as a fourteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. @@ -1522,6 +1541,7 @@ Each type is shared by equivalent requests, those of the same target and the sam | `mutation` | Invalidation | A node's attributes, its children or its text, and its descendants' where `subtree` says so | `attributes`: `true`, or a list of attribute names; `childList`, `subtree` and `characterData`, Booleans, false when omitted; at least one of attributes, children and text is observed | All four | | `attachment` | Invalidation | Whether a node is attached to its document, through every shadow root between them, a node another document owns inserted into the window's document included | None | None | | `intersection` | Maintained | Whether the browser reports an element intersecting a root, or the window where the root is null, grown by a margin in CSS pixels; pending until its first report. It takes a new sample by observing the element again, which the browser reports after it lays out its next frame | `root`, an element or null, null when omitted; `margin`, a number, 0 when omitted | `root`, `margin` | +| `layoutSize` | Maintained | The size layout gives an element's border box along the axes of its writing mode, a transform aside, as the browser's resize observation reports it; pending until its first report, which the browser makes once it has laid the element out. It takes a new sample by observing the element again | None | None | | `media` | Invalidation | Whether a media query matches | `query`, the media query | `query` | | `pixelRatio` | Invalidation | The device pixel ratio | None | None | | `event` | Invalidation | Events of the given types reaching the target, or reaching it in the capture phase | `types`, a list of event types; `capture`, a Boolean, false when omitted | `types`, `capture` | @@ -1536,7 +1556,7 @@ Each type is shared by equivalent requests, those of the same target and the sam ### Observation targets -An observation observes its member's receiver, an argument, `{ argument }`, or a target DOMQL's module declares, as Nexo's [observation targets](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations-targets) set out: +An observation observes its member's receiver, an argument, `{ argument }`, or a target DOMQL's module declares, as Nexo's [observation targets](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/observations.md#observations-targets) set out: | Target | Found from the receiver | Observes | | --- | --- | --- | @@ -1552,7 +1572,7 @@ DOMQL resolves each target as it starts an observation, and each evaluation that ## Extension modules -A module extends the built-in vocabulary as Nexo's [modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules) set out: it declares types of its own, each with its members and operators, states among them, and event types, executions and observation types, and adds members to DOMQL's types in its [extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions), each naming the one type it extends qualified, as `{ name: 'ChartElements', kind: 'extension', target: 'Domql.Element', members: [/* … */] }` adds members to elements. `domql.createModule(name, contents)` creates one from its declarations, each that runs code carrying its implementation as its `impl`, and `domql.registerModule(module)` registers it in the instance's registry, which holds DOMQL's module and every module registered with it. A request is resolved against the modules it imports, registered by then, so a module a query imports is registered beforehand, once, rather than for every evaluation. +A module extends the built-in vocabulary as Nexo's [modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules) set out: it declares types of its own, each with its members and operators, states among them, and event types, executions and observation types, and adds members to DOMQL's types in its [extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions), each naming the one type it extends qualified, as `{ name: 'ChartElements', kind: 'extension', target: 'Domql.Element', members: [/* … */] }` adds members to elements. `domql.createModule(name, contents)` creates one from its declarations, each that runs code carrying its implementation as its `impl`, and `domql.registerModule(module)` registers it in the instance's registry, which holds DOMQL's module and every module registered with it. A request is resolved against the modules it imports, registered by then, so a module a query imports is registered beforehand, once, rather than for every evaluation. ```js domql.registerModule(domql.createModule("Charts", { @@ -1573,15 +1593,15 @@ domql.registerModule(domql.createModule("Charts", { domql.query("import Charts\npanel:palette", { panel }).evaluate(); ``` -- **A query imports it, and reads its extensions with `:`.** A query that uses a module's vocabulary imports the module, `import Charts`, as [its imports](queries.md#making-a-query-imports) set out, and reads a member an extension adds with `:`, never `.`: `panel:palette`, or `panel:ChartElements.palette` where two of its extensions declare one name, as Nexo's [extension access](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions-access) sets out. DOMQL's own members stand within its types, so a query reads them with `.`. +- **A query imports it, and reads its extensions with `:`.** A query that uses a module's vocabulary imports the module, `import Charts`, as [its imports](queries.md#making-a-query-imports) set out, and reads a member an extension adds with `:`, never `.`: `panel:palette`, or `panel:ChartElements.palette` where two of its extensions declare one name, as Nexo's [extension access](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions-access) sets out. DOMQL's own members stand within its types, so a query reads them with `.`. - **DOMQL's members win on its types.** A name DOMQL's type declares is read with `.` as DOMQL's, and an extension's member of that name is read with `:` alone. Two modules' extensions declaring one name both register, and a query that reads the name where neither is more specific is refused where it does so (NEXO3024), naming the extensions to write. - **States and work.** A module declares a state as a Boolean property, and a member that does work or takes an argument as a function, as [properties and functions](#vocabulary-properties-and-functions) set out; Nexo refuses neither form, so a module follows the rule itself. -- **What an implementation receives.** Every implementation receives the one object Nexo's [implementations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#members-what-an-implementation-receives) receive, whose `env` is the [environment](#extension-modules-environment) of the operation that reaches it. -- **Arguments.** A host call's implementation receives its arguments as Nexo prepares them, by parameter name. A null argument whose parameter accepts null is passed as it stands, as a bound of null meaning the viewport, and one whose parameter propagates null skips the call, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. An option of a structured type, written in place as an object expression, as `buttons = { container = viewport, step = 3 }`, is [constructed](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#types-constructing-a-structure) as that type's data, a field of a reference type holding the element it names, and reaches the implementation as a frozen structure. +- **What an implementation receives.** Every implementation receives the one object Nexo's [implementations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#members-what-an-implementation-receives) receive, whose `env` is the [environment](#extension-modules-environment) of the operation that reaches it. +- **Arguments.** A host call's implementation receives its arguments as Nexo prepares them, by parameter name. A null argument whose parameter accepts null is passed as it stands, as a bound of null meaning the viewport, and one whose parameter propagates null skips the call, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. An option of a structured type, written in place as an object expression, as `buttons = { container = viewport, step = 3 }`, is [constructed](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#types-constructing-a-structure) as that type's data, a field of a reference type holding the element it names, and reaches the implementation as a frozen structure. -- **Kept functions.** A host call's function argument, as a test of what a behavior hears, `when = it.matches(".pick")`, reaches its implementation as a function it keeps and calls later, a [kept function](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls-kept-functions): each call reads the page as it is then, through the locals and the bindings the call was prepared with, as a query evaluated once reads, so a member it reads reads alone, and is checked against the parameter's contract. DOMQL ends the functions an execution keeps as the execution ends: a continuous execution's as its instance ends, and as an update gives its instance others, once the instance accepted them; a once execution's as its implementation's answer settles, a canceled one's among them; and an event source's as its subscription ends. A call of one afterwards fails with Nexo's NEXO5051, which the implementation receives as it does any failure of the call. +- **Kept functions.** A host call's function argument, as a test of what a behavior hears, `when = it.matches(".pick")`, reaches its implementation as a function it keeps and calls later, a [kept function](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls-kept-functions): each call reads the page as it is then, through the locals and the bindings the call was prepared with, as a query evaluated once reads, so a member it reads reads alone, and is checked against the parameter's contract. DOMQL ends the functions an execution keeps as the execution ends: a continuous execution's as its instance ends, and as an update gives its instance others, once the instance accepted them; a once execution's as its implementation's answer settles, a canceled one's among them; and an event source's as its subscription ends. A call of one afterwards fails with Nexo's NEXO5051, which the implementation receives as it does any failure of the call. - **Reading.** A member's implementation is synchronous and reads alone, as Nexo requires of every vocabulary, so evaluating, watching and subscribing change nothing; a change to the page is an [execution](executions.md). - **Event types.** A module adds event types of its own as keys of DOMQL's type selector `event`, each a mapping, `{ selector: 'event', key, type }`, naming the type its events are captured as, so `on` listens to them as it listens to the built-in ones. - **Observations.** A member of any module names DOMQL's observation types and targets as DOMQL's own members do. DOMQL resolves the targets its own module declares alone, so a module declaring observation targets of its own is refused when it is registered, and an observation type a module declares, which owns no target, observes the receiver or an argument. An observation type a module declares is started by its implementation, which receives `request`, the observation's `type`, its `target` and its `arguments`, each argument the member names resolved to its value; `notify`, which it calls when what it observes may have changed; and `env`, [an observation's environment](#extension-modules-observation-environment). It answers an object whose `stop()` ends the observation and, for a maintained observation, whose `sample()` answers its latest sample, `{ pending, value }`. A maintained observation whose sample can lag behind the page, as one the browser reports after it lays a frame out, offers `resampleAsync()` too: it takes a new sample and answers a promise that settles once that sample has arrived, which a [refresh that resamples](watches.md#watching-resampling) waits for. One that offers none is read as it stands, its sample taken to be current whenever `sample()` answers it. @@ -1606,7 +1626,7 @@ An operation gives every implementation it reaches one environment, its `env`, m -**History per holder.** The environment is one per operation, so a member that reads captured values, keeping what it measured before as Nexo's [captured reading](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads) has its holder keep it, keys that history by its environment and its receiver, in a `WeakMap` of its own: each watch, wait and subscription keeps its own, from its start to its end, and lets it go with the operation, and an evaluation once, whose environment is its own, reports what it sees with none. +**History per holder.** The environment is one per operation, so a member that reads captured values, keeping what it measured before as Nexo's [captured reading](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads) has its holder keep it, keys that history by its environment and its receiver, in a `WeakMap` of its own: each watch, wait and subscription keeps its own, from its start to its end, and lets it go with the operation, and an evaluation once, whose environment is its own, reports what it sees with none. @@ -1620,10 +1640,10 @@ An operation gives every implementation it reaches one environment, its `env`, m ### Registering a module while requests run -A query's imports decide what it resolves against, so a module registered later changes no resolution's meaning: a running watch, subscription or continuous execution keeps the resolution it has, and goes on evaluating and delivering, as Nexo keeps a resolution [current](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-reuse). +A query's imports decide what it resolves against, so a module registered later changes no resolution's meaning: a running watch, subscription or continuous execution keeps the resolution it has, and goes on evaluating and delivering, as Nexo keeps a resolution [current](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-reuse). -- **A module that recognizes values.** A module declaring a `typeOf` may recognize values a resolution captures, so it makes stale the resolutions that may meet such a value, as Nexo's [reusing a resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-reuse) sets out: one whose host call supplies `DomEvent`, whose `target` is a nullable reference, among them. An operation started after it resolves its request again. -- **A running watch or a waiting evaluation made stale** resolves its request again at its next evaluation, which evaluates the whole query anew, as each of its evaluations does, so it goes on as before. A watch compares that evaluation's result as it compares any, within each value's tolerance: Nexo gives every resolution of one definition the same [origins](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results) where it selects the same declarations. Resolving again checks what starting the watch checked, and its refusal is that evaluation's failure. +- **A module that recognizes values.** A module declaring a `typeOf` may recognize values a resolution captures, so it makes stale the resolutions that may meet such a value, as Nexo's [reusing a resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-reuse) sets out: one whose host call supplies `DomEvent`, whose `target` is a nullable reference, among them. An operation started after it resolves its request again. +- **A running watch or a waiting evaluation made stale** resolves its request again at its next evaluation, which evaluates the whole query anew, as each of its evaluations does, so it goes on as before. A watch compares that evaluation's result as it compares any, within each value's tolerance: Nexo gives every resolution of one definition the same [origins](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results) where it selects the same declarations. Resolving again checks what starting the watch checked, and its refusal is that evaluation's failure. - **A subscription or a once execution made stale** prepares its request again where a value its host call supplies is next projected: at the next event, or as the execution's result arrives. Where that preparation reaches the declaration it was carried out through, the value is projected through it, its locals and the object expression evaluated as that preparation finds them, and a subscription goes on listening with the receiver and the arguments its event source started with. Where it reaches none, or another, the subscription hands its handler the failure `DOMQL5015` and ends, and the once execution rejects with it, its effect standing. Where preparing it again fails, the subscription hands its handler that failure and ends, and the once execution rejects with it. @@ -1648,22 +1668,50 @@ chart.evaluate(); - **A module that names another's types** is registered after it, so its loader loads that one first, `await domql.loadModulesAsync(["Gestures"])`, before answering its own. - **Not loaded yet.** A request importing a module that has a loader, and is not registered yet, is refused as it is resolved with `DOMQL3007`, located at the import, rather than Nexo's refusal of a module it doesn't know. No operation loads a module itself: an execution would lose the order and the activation of the call that carries it out. + + +### Preparing modules and queries ahead of time + +Each time a page starts, creating and registering a module checks its declarations, and making and resolving a query reads its text and resolves it. A host's build can make those checks once, ahead of time, and give the page what they recorded, a **manifest**, as Nexo's [preparing modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-preparing) and [preparing scripts](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-preparing-scripts) set out. + +```js +// At build time: the modules a page registers and the queries it makes, checked once. +const manifest = domql.prepare([{ name: "Charts", contents: charts }], { + scripts: [{ script: "import Charts\npanel:palette", types: { panel: "Domql.Element" } }] +}); + +// At the page's start, from the manifest the build kept as JSON. +domql.registerModule(domql.createModule("Charts", charts, { manifest }), { manifest }); +domql.query("import Charts\npanel:palette", { panel }, { manifest }).evaluate(); +``` + +- **`domql.prepare(modules, options?)`** creates each module given, `{ name, contents }` as `domql.createModule` takes it, and registers it with every check, in the order given, after DOMQL's own. It refuses what `domql.createModule` and `domql.registerModule` refuse, and what is no list of modules with Nexo's `NEXO4565`. +- **Its queries.** It resolves each query `options.scripts` gives, `{ script, bindings, types }`, against those modules, as `domql.query(script, bindings, { types })` resolves it, its text read with `Domql` supplied. It refuses what that refuses, and a query that gives `imports` of its own with `DOMQL2021`, since `domql.query` reads none. It answers the manifest, plain data the host keeps as JSON. +- **A binding given a type and no value** stands for any value of its type that decides nothing, as an element does, so `types: { panel: "Domql.Element" }` prepares the query for every element. A `String` or a `Boolean` decides what a member reads by its value, so one is given its value, and a query bound to another value is resolved as it is carried out. +- **`manifest` gives it back** to these operations: + - `domql.createModule(name, contents, { manifest })` creates a module of the same contents without the checks the manifest records. + - `domql.registerModule(module, { manifest })` registers such a module without them, beside the modules registered before it in the manifest. + - `domql.registerModuleLoader(name, load, { manifest })` registers the module its loader answers so. Options that are no object are refused with `DOMQL2013`. + - `domql.query(text, bindings, { types, manifest })` reads the text from the definition the manifest holds, and each resolution it holds for the bindings, as [making a query](queries.md#making-a-query-declared-types) sets out. An operation run directly takes it beside `types`. +- **What it holds none of** is checked and resolved as it is without one. DOMQL's own checks of a module's host calls are made either way. +- **A manifest belongs to its implementation.** One another version of Nexo made holds no module and no query, so everything given it is checked and resolved. A host prepares again at each release of DOMQL, or of Nexo beside it, that it takes. + ### Host calls DOMQL carries out -A module declares an event source or an execution as a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls), a function with `invokedBy: 'host'`, within a type, within an extension, or among its module members, and gives DOMQL what Nexo leaves to its host: the `requestKind` the call makes, `subscription` for an event source or `execution`; an execution's `executionMode`, `once` or `continuous`; and the `impl` that carries it out. `domql.createModule` keeps these in DOMQL's own catalog, and gives Nexo the declaration without them, so Nexo resolves and prepares the call and DOMQL alone invokes it. One declaration standing within several types, as DOMQL's `on` does within `Element`, `Document` and `Window`, is kept for each. +A module declares an event source or an execution as a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls), a function with `invokedBy: 'host'`, within a type, within an extension, or among its module members, and gives DOMQL what Nexo leaves to its host: the `requestKind` the call makes, `subscription` for an event source or `execution`; an execution's `executionMode`, `once` or `continuous`; and the `impl` that carries it out. `domql.createModule` keeps these in DOMQL's own catalog, and gives Nexo the declaration without them, so Nexo resolves and prepares the call and DOMQL alone invokes it. One declaration standing within several types, as DOMQL's `on` does within `Element`, `Document` and `Window`, is kept for each. | Host call | `requestKind` | `executionMode` | Its `result` | Its implementation receives | It answers | | --- | --- | --- | --- | --- | --- | -| Event source | `subscription` | Refused | The type of each event it delivers, `@selected` where an event type selects it | `receiver`, `args`, `env` and `deliver`, which each event is handed to and which answers its [acknowledgment](behaviors.md#behaviors-acknowledgment) | An object whose `stop()` ends the listening | +| Event source | `subscription` | Refused | The type of each event it delivers, `@selected` where an event type selects it | `receiver`, `args`, `env` and `deliver`, which each event is handed to and which answers its [acknowledgment](behaviors.md#behaviors-acknowledgment), with the subscription's [answer](behaviors.md#behaviors-answers) where it declares `answers` | An object whose `stop()` ends the listening | | Event source of a behavior, declaring `behavior` | `subscription` | Refused | The type of each occurrence it delivers | Nothing: DOMQL carries it out, so it declares no `impl` and no parameters | — | | Once execution | `execution` | `once` | The type of its result | `receiver`, `args`, `env` and `signal`, which aborts it | Its result, or a promise of it | | Command, a once execution declaring `behavior` | `execution` | `once` | The type of its result | What a once execution receives, and `instance`, the running instance of its behavior | Its result, or a promise of it | | Continuous execution | `execution` | `continuous` | None; one declared is refused | `receiver`, `args`, `env`, `reportError`, which a failure while it runs is reported through, `deliver(source, value)`, which hands an [occurrence](behaviors.md#behaviors-occurrences) to its module's event source of that name, and `notify()`, which says the [state it offers](behaviors.md#behaviors-state) may have changed | An object whose `update(receiver, args)` applies new arguments and whose `dispose()` ends it, started before it returns | -A [command](behaviors.md#behaviors-commands) and an [event source of occurrences](behaviors.md#behaviors-occurrences) declare the behavior they reach as their `behavior`, the name of a continuous execution their module declares, which DOMQL keeps beside their request kind and gives Nexo the declaration without; so does a member the evaluator invokes reading the [state a behavior offers](behaviors.md#behaviors-state), whose implementation receives the behavior's `instance`. A behavior itself names none. +An event source, a behavior's or one its module implements, may declare `answers`, the type of what its subscription answers each event with, as [answers](behaviors.md#behaviors-answers) set out, which DOMQL keeps beside its request kind and gives Nexo the declaration without. A [command](behaviors.md#behaviors-commands) and an [event source of occurrences](behaviors.md#behaviors-occurrences) declare the behavior they reach as their `behavior`, the name of a continuous execution their module declares, which DOMQL keeps beside their request kind and gives Nexo the declaration without; so does a member the evaluator invokes reading the [state a behavior offers](behaviors.md#behaviors-state), whose implementation receives the behavior's `instance`. A behavior itself names none. -`domql.createModule` refuses, with a module error naming the declaration, the type it stands within and the key, of the code [errors](errors.md#errors-module) give, a host call whose `requestKind` is missing or neither `subscription` nor `execution`; an execution whose `executionMode` is missing or neither `once` nor `continuous`; an event source given an `executionMode`, or declaring no result, since each event it delivers is the value its subscription projects; a member the evaluator invokes given either key, an unnamed indexer named `[]`, as Nexo names it; a continuous execution that declares a result; a `behavior` on a continuous execution, or naming no behavior by a name; one naming no continuous execution of its module; and an event source of a behavior declaring an `impl` or parameters. `domql.registerModule` refuses a module declaring a host call its catalog holds nothing of, as a module `domql.createModule` did not make. So an execution whose mode was left out is refused as an execution missing its mode. +`domql.createModule` refuses, with a module error naming the declaration, the type it stands within and the key, of the code [errors](errors.md#errors-module) give, a host call whose `requestKind` is missing or neither `subscription` nor `execution`; an execution whose `executionMode` is missing or neither `once` nor `continuous`; an event source given an `executionMode`, or declaring no result, since each event it delivers is the value its subscription projects; a member the evaluator invokes given either key, an unnamed indexer named `[]`, as Nexo names it; a continuous execution that declares a result; a `behavior` on a continuous execution, or naming no behavior by a name; one naming no continuous execution of its module; an event source of a behavior declaring an `impl` or parameters; and an `answers` declared by anything but an event source, or other than a string of a type's notation. `domql.registerModule` refuses a module declaring a host call its catalog holds nothing of, as a module `domql.createModule` did not make. So an execution whose mode was left out is refused as an execution missing its mode. -On a receiver of unknown type, a host call has no declaration yet, so its [candidates](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls), every declaration that takes the call as it is written, say what it does, as they say who invokes it. Where they disagree on what they request, the request is refused as ambiguous with a validation error, located at the call. +On a receiver of unknown type, a host call has no declaration yet, so its [candidates](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls), every declaration that takes the call as it is written, say what it does, as they say who invokes it. Where they disagree on what they request, the request is refused as ambiguous with a validation error, located at the call. diff --git a/spec/watches.md b/spec/watches.md index 367dbee..077f7df 100644 --- a/spec/watches.md +++ b/spec/watches.md @@ -69,19 +69,19 @@ In this document: ## How a member changes -Every member declares how its result changes, by the categories [Nexo defines](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-changes), and a watch decides by each what it may follow: +Every member declares how its result changes, by the categories [Nexo defines](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-changes), and a watch decides by each what it may follow: | Category | As in DOMQL | In a watch | | --- | --- | --- | | Constant | Whether the browser offers a capability, as `Domql.window.canShare` reads | Allowed; it never invalidates. | -| Observable | A size, which a resize observation covers | Allowed. | +| Observable | The size layout gives a box, `layoutSize`, which a resize observation covers | Allowed. | | Partly observable | A computed style, which a rule outside the element can change unobserved | Allowed when the caller accepts partial observation for that watch; a change the observations miss reaches the watch at its next evaluation, which `refreshAsync` or another observed change causes. | | Unobserved | A member that names no observations | A validation error. | -A watch is checked against every member its query may read. A member of a value of `Any` is selected as the query is evaluated, so the watch is checked against every declaration of its name Nexo could select, as Nexo's [candidate declarations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md) overestimate them: a watch over `panel:bag.rect`, where a module's extension member `bag` answers `Any`, takes `acceptPartialObservation`, as one over `panel.rect` does. +A watch is checked against every member its query may read. A member of a value of `Any` is selected as the query is evaluated, so the watch is checked against every declaration of its name Nexo could select, as Nexo's [candidate declarations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md) overestimate them: a watch over `panel:bag.rect`, where a module's extension member `bag` answers `Any`, takes `acceptPartialObservation`, as one over `panel.rect` does. | Derived | A list's `first` or `where` | Allowed wherever what it derives from is. | -A literal is constant, so a watched object expression can carry one: `viewport { kind = "viewport", width = it.size?.width }`. +A literal is constant, so a watched object expression can carry one: `viewport { kind = "viewport", width = it.layoutSize?.inline }`. @@ -105,7 +105,7 @@ A watch's dependencies are what its last evaluation actually read: each member a ### Following a change a member misses -A query follows a change its members miss by reading a member that observes it. A body's local runs whether or not anything uses it, as Nexo's [ordered evaluation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/scripts.md#bodies-ordered-evaluation) sets out, so it adds the dependency without adding to the result. A row a sibling's edit moves, which `rectRelativeTo` misses, is followed by reading the text around it: +A query follows a change its members miss by reading a member that observes it. A body's local runs whether or not anything uses it, as Nexo's [ordered evaluation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/scripts.md#bodies-ordered-evaluation) sets out, so it adds the dependency without adding to the result. A row a sibling's edit moves, which `rectRelativeTo` misses, is followed by reading the text around it: ```domql let edited = panel.text diff --git a/src/Versions.mjs b/src/Versions.mjs index f2dbdea..a55a55b 100644 --- a/src/Versions.mjs +++ b/src/Versions.mjs @@ -6,10 +6,10 @@ import { nexo } from '@formaui-net/nexo'; export class Versions { /** The runtime release version, which the package and the bundle carry. */ - static runtime = '1.0.0-preview.3'; + static runtime = '1.0.0-preview.4'; /** The DOMQL specification version the implementation follows. */ - static specification = '1.0.0-preview.1'; + static specification = '1.0.0-preview.2'; /** The language specification version the Nexo runtime DOMQL runs on follows, as that runtime reports it. */ static language = nexo.info.versions.language; diff --git a/src/connections/Connection.mjs b/src/connections/Connection.mjs new file mode 100644 index 0000000..8313922 --- /dev/null +++ b/src/connections/Connection.mjs @@ -0,0 +1,593 @@ +/** + * Connection — DOMQL's operations carried across a boundary as messages: the requests a host sends in batches, each answered as its batch's task ends, and the deliveries DOMQL sends back, those of one task together, + * each watch's paced by the acknowledgment of the one before it + */ + +import { NexoError } from '@formaui-net/nexo'; + +/** The requests a connection carries out, by the name each gives in `request`. */ +const REQUESTS = new Set(['evaluate', 'execute', 'watch', 'subscribe', 'run', 'update', 'refresh', 'dispose', 'release', 'load']); + +/** The requests that start a handle, which names it. */ +const STARTING = new Set(['evaluate', 'execute', 'watch', 'subscribe', 'run', 'load']); + +/** The options a watch request gives its watch; the strategy is the connection's, which keeps the host's copy by change sets. */ +const WATCH_OPTIONS = ['schedule', 'delay', 'reportOn', 'acceptPartialObservation']; + +/** The options a subscription request gives its subscription; its reactions are requests of the connection's own form. */ +const SUBSCRIBE_OPTIONS = ['throttle', 'reactions']; + +/** The deliveries earlier batches may leave unacknowledged; a batch sent while that many wait closes the connection, since a host that acknowledges none would otherwise hold every occurrence. */ +const OUTSTANDING_LIMIT = 4096; + +export class Connection { + /** The DOMQL instance whose operations the connection carries out. */ + #domql; + + /** The host's receiver of deliveries: `deliver(deliveries)` answers a promise of one answer for each delivery, which settles once the host has applied them. */ + #deliver; + + /** The window the connection's operations run in. */ + #window; + + /** Each query a request made, by the key the host gave it, which later requests name it by; kept until the connection closes. @type {Map} */ + #queries = new Map(); + + /** Each handle a request started that has not ended, by the id the host gave it. @type {Map} */ + #handles = new Map(); + + /** The deliveries of the current task, in the order they happened, sent together as it ends. @type {object[]} */ + #queue = []; + + #isFlushScheduled = false; + + /** The deliveries sent whose acknowledgment has not settled. */ + #outstanding = 0; + + #isClosed = false; + + /** + * @param {object} domql The DOMQL instance whose operations it carries out. + * @param {(deliveries: object[]) => Promise} deliver The host's receiver of deliveries. + * @param {{ window?: Window }} [options] + */ + constructor(domql, deliver, { window = globalThis.window } = {}) { + this.#domql = domql; + this.#deliver = deliver; + this.#window = window; + } + + /** Whether the connection has closed: by `close`, or as a host that acknowledged nothing let its deliveries pass their limit. */ + get isClosed() { + return this.#isClosed; + } + + /** + * Carries out the requests given, in order, and answers a promise of their answers, one for each, in order, which settles once the task that carried them out has ended: an answer the task settled is final, and + * one it left waiting answers `{ pending: true }`, its result reaching the host as a delivery of its handle. + * @param {object[]} requests + * @returns {Promise} + */ + requestAsync(requests) { + if (!Array.isArray(requests)) { + return Promise.reject(NexoError.structure('DOMQL2023', 'A connection is sent a list of requests', {})); + } + + const answers = requests.map(request => this.#carryOut(request)); + + // The task's microtasks settle what they settle, which a message posted to the window's own channel runs after; an answer still waiting then is delivered once it settles. + return this.#afterTask().then(() => answers.map(answer => (typeof answer === 'function' ? answer() : answer))); + } + + /** Ends every handle the connection started, and refuses every request after it. Closing again does nothing. */ + close() { + if (this.#isClosed) { + return; + } + + this.#isClosed = true; + + for (const handle of [...this.#handles.values()]) { + this.#end(handle); + } + + const closed = NexoError.evaluation('DOMQL5027', 'The connection is closed, and delivers nothing more', {}); + + this.#queue.splice(0).forEach(({ failed }) => failed(closed)); + } + + /** The answer to one request: final, or a function that answers once the task has ended. */ + #carryOut(request) { + try { + if (this.#isClosed) { + throw NexoError.evaluation('DOMQL5027', 'The connection is closed, and carries out no request', {}); + } + + if (request === null || typeof request !== 'object' || !REQUESTS.has(request.request)) { + throw NexoError.structure('DOMQL2023', `A request names what it asks for, as request: 'watch', and this one names ${JSON.stringify(request?.request ?? null)}`, {}); + } + + if (STARTING.has(request.request)) { + this.#refuseHandleId(request.handle); + } + + switch (request.request) { + case 'evaluate': { + const query = this.#queryOf(request); + const owner = this.#ownerOf(request); + + return this.#settleLater(request.handle, owner, () => query.evaluateAsync({ owner, window: this.#window })); + } + case 'execute': { + const query = this.#queryOf(request); + const owner = this.#ownerOf(request); + + return this.#settleLater(request.handle, owner, () => query.executeAsync({ owner, window: this.#window })); + } + case 'load': + return this.#settleLater(request.handle, this.#ownerOf(request), () => this.#domql.loadModulesAsync(request.modules)); + case 'watch': + return this.#watch(request); + case 'subscribe': + return this.#subscribe(request); + case 'run': + return this.#run(request); + case 'update': + return this.#update(request); + case 'refresh': + return this.#refresh(request); + case 'dispose': + return this.#dispose(request); + default: + return this.#release(request); + } + } catch (error) { + return { error: Connection.#errorOf(error) }; + } + } + + /** Starts a handle of the owner whose operation answers a promise, answered by its value where the task settles it, and otherwise pending, its result delivered once it settles. */ + #settleLater(id, owner, operate) { + const handle = { id, kind: 'settling', owner, generation: 0 }; + let outcome = null; + + this.#handles.set(id, handle); + + Promise.resolve().then(operate).then(value => { outcome = { value: value ?? null }; }, error => { outcome = { error: Connection.#errorOf(error) }; }).then(() => { + if (this.#handles.get(id) !== handle) { + return; + } + + if (handle.isAnswered) { + this.#enqueue({ handle: id, ...outcome }); + } + + this.#handles.delete(id); + }); + + return () => { + handle.isAnswered = true; + + return outcome ?? { pending: true }; + }; + } + + /** Starts a watch of live state, whose first snapshot answers the request where the task gave it one, and whose every later change is delivered, paced by the acknowledgment of the one before it. */ + #watch(request) { + const handle = { id: request.handle, kind: 'watch', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), request, watch: null, isAnswered: false, isWholeNext: false, isSuspended: false, unacknowledged: 0, waiting: [] }; + + this.#startWatch(handle, request); + this.#handles.set(handle.id, handle); + + return () => this.#baselineOf(handle); + } + + /** Starts the handle's watch with the request's query, bindings and options, listening to its changes. */ + #startWatch(handle, request) { + const options = Connection.#pick(request.options, WATCH_OPTIONS); + const watch = this.#queryOf(request).watch({ ...options, updateStrategy: 'liveState', owner: handle.owner, window: this.#window }); + + handle.watch = watch; + handle.isAnswered = false; + watch.subscribe('change', (sender, args) => this.#changed(handle, watch, args)); + } + + /** + * The answer a watch request or update is given as its task ends: the snapshot it has; or pending, its first snapshot delivered whole, with the failure of its first evaluation where that failed, since the watch + * runs on and a later evaluation may succeed. A request refused answers `{ error }` alone, and starts no handle. + */ + #baselineOf(handle) { + handle.isAnswered = true; + handle.waiting = []; + + if (handle.watch.status === 'ready') { + return { snapshot: handle.watch.snapshot }; + } + + handle.isWholeNext = true; + + return handle.watch.status === 'failed' ? { pending: true, error: Connection.#errorOf(handle.watch.error) } : { pending: true }; + } + + /** A watch's change or failure: nothing before its request is answered, whose answer holds the snapshot then current, and afterwards a delivery, joined to the one waiting where one waits. */ + #changed(handle, watch, args) { + if (handle.watch !== watch || !handle.isAnswered) { + return; + } + + if (args.status === 'failed') { + this.#paced(handle, { error: Connection.#errorOf(args.error) }); + + return; + } + + if (handle.isWholeNext) { + handle.isWholeNext = false; + this.#paced(handle, { snapshot: args.snapshot }); + + return; + } + + if (args.changes.length > 0) { + this.#paced(handle, { changes: args.changes, snapshot: args.snapshot }); + } + } + + /** + * Sends a watch's delivery where none of its own is unacknowledged, and otherwise keeps it waiting, joined to those waiting already: a change set to the one before it, concatenated, as change sets compose, unless + * the snapshot whole is shorter; a snapshot whole in place of all that waits, which it brings the host's copy past; and a failure after what came before it, in place of a failure waiting last. So the host hears a + * watch's deliveries in the order they happened, every one it waits for joined in one batch. A watch whose delivery the host rejected waits until it is refreshed. + */ + #paced(handle, delivery) { + const { waiting } = handle; + const last = waiting.at(-1); + + if (delivery.snapshot !== undefined && delivery.changes === undefined) { + waiting.splice(0, waiting.length, delivery); + } else if (delivery.error !== undefined && last?.error !== undefined) { + waiting[waiting.length - 1] = delivery; + } else if (delivery.changes !== undefined && last?.changes !== undefined) { + const changes = [...last.changes, ...delivery.changes]; + + waiting[waiting.length - 1] = JSON.stringify(changes).length > JSON.stringify(delivery.snapshot).length ? { snapshot: delivery.snapshot } : { changes, snapshot: delivery.snapshot }; + } else { + waiting.push(delivery); + } + + if (handle.unacknowledged === 0 && !handle.isSuspended) { + this.#sendWaiting(handle); + } + } + + /** Queues every delivery waiting of a watch, in order, each holding its change set, its snapshot or its failure, and the watch's own unacknowledged until the host settles them. */ + #sendWaiting(handle) { + const deliveries = handle.waiting.splice(0); + + handle.unacknowledged += deliveries.length; + + for (const { changes, snapshot, error } of deliveries) { + const sent = { handle: handle.id, generation: handle.generation, ...(changes !== undefined ? { changes } : error !== undefined ? { error } : { snapshot }) }; + + this.#enqueue(sent, () => this.#acknowledged(handle), () => { + handle.isSuspended = true; + this.#acknowledged(handle); + }); + } + } + + /** One of a watch's deliveries settled; once the last has, what waited since is sent, unless the host rejected one, or the watch has ended. */ + #acknowledged(handle) { + handle.unacknowledged -= 1; + + if (handle.unacknowledged === 0 && !handle.isSuspended && handle.waiting.length > 0 && this.#handles.get(handle.id) === handle) { + this.#sendWaiting(handle); + } + } + + /** Subscribes to an event source, each event delivered as it happens, never waiting for another, and answered with what the host answers it. */ + #subscribe(request) { + const handle = { id: request.handle, kind: 'subscription', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), request, listener: null }; + + this.#startSubscription(handle, request); + this.#handles.set(handle.id, handle); + + return {}; + } + + /** Starts the handle's subscription with the request's query, bindings and options, its reactions made as the connection makes a query. */ + #startSubscription(handle, request) { + const { reactions, ...options } = Connection.#pick(request.options, SUBSCRIBE_OPTIONS); + const made = reactions === undefined ? {} : { reactions: Array.isArray(reactions) ? reactions.map(reaction => this.#queryOf(reaction)) : reactions }; + + handle.listener = this.#queryOf(request).subscribe((sender, args) => this.#occurred(handle, args), { ...options, ...made, owner: handle.owner, window: this.#window }); + } + + /** An event of a subscription, or its failure: delivered at once, and answered with the host's answer, which settles the event's acknowledgment. */ + #occurred(handle, args) { + const delivery = args.status === 'ready' ? { handle: handle.id, generation: handle.generation, event: args.value } : { handle: handle.id, generation: handle.generation, error: Connection.#errorOf(args.error) }; + + return new Promise((resolve, reject) => this.#enqueue(delivery, answer => resolve(answer ?? undefined), reject)); + } + + /** Runs a continuous execution, each failure it reports delivered as it happens. */ + #run(request) { + const handle = { id: request.handle, kind: 'execution', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), execution: null }; + + handle.execution = this.#queryOf(request).run({ owner: handle.owner, window: this.#window }); + handle.execution.subscribe('error', (sender, { error }) => this.#enqueue({ handle: handle.id, generation: handle.generation, error: Connection.#errorOf(error) })); + this.#handles.set(handle.id, handle); + + return {}; + } + + /** + * Binds a handle anew, at the generation the request gives: an execution updated in place; a watch started again with the new bindings, its answer as a watch request's; and a subscription started again. Deliveries + * the handle made before carry the generation before it. + */ + #update(request) { + const handle = this.#getHandle(request.handle, ['watch', 'subscription', 'execution']); + + if (handle.kind === 'execution') { + handle.execution.update(this.#bindingsOf(request)); + handle.generation = Connection.#generationOf(request, handle.generation); + + return {}; + } + + const next = { ...handle.request, query: handle.request.query, bindings: request.bindings ?? {}, ...(request.options === undefined ? {} : { options: request.options }) }; + + if (handle.kind === 'subscription') { + const listener = handle.listener; + + this.#startSubscription(handle, next); + listener.dispose(); + handle.request = next; + handle.generation = Connection.#generationOf(request, handle.generation); + + return {}; + } + + const watch = handle.watch; + + this.#startWatch(handle, next); + watch.dispose(); + handle.isSuspended = false; + handle.request = next; + handle.generation = Connection.#generationOf(request, handle.generation); + handle.waiting = []; + + return () => this.#baselineOf(handle); + } + + /** + * Evaluates a watch now, or every watch the connection runs where the request names none, and delivers its snapshot whole once it has, changed or not, so a host that lost track of its copy has it again. A watch whose + * delivery the host rejected delivers again from it. + */ + #refresh(request) { + const watches = request.handle === undefined ? [...this.#handles.values()].filter(handle => handle.kind === 'watch') : [this.#getHandle(request.handle, ['watch'])]; + + for (const handle of watches) { + const { watch } = handle; + + if (request.handle !== undefined) { + handle.generation = Connection.#generationOf(request, handle.generation); + } + + handle.isWholeNext = true; + handle.isSuspended = false; + handle.waiting = []; + watch.refreshAsync({ resample: request.resample === true }).then(() => { + // A refresh whose result is unchanged raises no change, so the snapshot it settled on is delivered whole. + if (handle.watch === watch && handle.isWholeNext && watch.status === 'ready') { + handle.isWholeNext = false; + this.#paced(handle, { snapshot: watch.snapshot }); + } + }, error => { + // A failed evaluation raises its change, which delivered the failure already; a refresh that failed otherwise delivers its own. + if (handle.watch === watch && !(watch.status === 'failed' && watch.error === error)) { + this.#paced(handle, { error: Connection.#errorOf(error) }); + } + }); + } + + return {}; + } + + /** Ends a handle; one already ended, or never started, is ended already. */ + #dispose(request) { + const handle = this.#handles.get(request.handle); + + if (handle !== undefined) { + this.#end(handle); + } + + return {}; + } + + /** Ends every handle of the owner the request names. */ + #release(request) { + const owner = this.#ownerOf(request); + + for (const handle of [...this.#handles.values()].filter(candidate => candidate.owner === owner)) { + this.#end(handle); + } + + return {}; + } + + /** Ends a handle: its watch, subscription or execution disposed, and nothing more delivered of it. */ + #end(handle) { + this.#handles.delete(handle.id); + handle.waiting = []; + handle.watch?.dispose(); + handle.listener?.dispose(); + handle.execution?.dispose(); + } + + /** Queues a delivery of the current task, sent with the others of the task as it ends; `settled` hears the host's answer to it, and `failed` its rejection. */ + #enqueue(delivery, settled = () => {}, failed = () => {}) { + if (this.#isClosed) { + failed(NexoError.evaluation('DOMQL5027', 'The connection is closed, and delivers nothing more', {})); + + return; + } + + this.#queue.push({ delivery, settled, failed }); + + if (!this.#isFlushScheduled) { + this.#isFlushScheduled = true; + queueMicrotask(() => this.#flush()); + } + } + + /** Sends the task's deliveries to the host, together, in the order they happened. */ + #flush() { + this.#isFlushScheduled = false; + + const entries = this.#queue.splice(0); + + if (entries.length === 0 || this.#isClosed) { + return; + } + + if (this.#outstanding >= OUTSTANDING_LIMIT) { + const error = NexoError.evaluation('DOMQL5026', `The host has acknowledged none of the last ${OUTSTANDING_LIMIT} deliveries, so the connection closes rather than hold more`, {}); + + entries.forEach(({ failed }) => failed(error)); + this.close(); + this.#reportError(error); + + return; + } + + this.#outstanding += entries.length; + + let answered; + + try { + answered = Promise.resolve(this.#deliver(entries.map(({ delivery }) => delivery))); + } catch (error) { + answered = Promise.reject(error); + } + + answered.then(answers => { + this.#outstanding -= entries.length; + entries.forEach(({ settled }, index) => settled(Array.isArray(answers) ? answers[index] : undefined)); + }, error => { + this.#outstanding -= entries.length; + entries.forEach(({ failed }) => failed(error)); + }); + } + + /** Reports a failure that belongs to no handle to the window. */ + #reportError(error) { + try { + (this.#window?.reportError ?? (failure => console.error(failure)))(error); + } catch { + // A reporter failure ends nowhere else. + } + } + + /** Settles once the current task has ended, a message posted to a channel running after its microtasks; without a channel, a timer does. */ + #afterTask() { + const Channel = this.#window?.MessageChannel ?? globalThis.MessageChannel; + + if (Channel === undefined) { + return new Promise(resolve => setTimeout(resolve, 0)); + } + + return new Promise(resolve => { + const channel = new Channel(); + + channel.port1.onmessage = () => { + channel.port1.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); + } + + /** The query a request names, bound to its bindings: one its key names, made by an earlier request, or one it makes from its text or its definition and keeps by its key. */ + #queryOf(request) { + const { query } = request; + let made; + + if (typeof query === 'string' || typeof query === 'number') { + made = this.#queries.get(query); + + if (made === undefined) { + throw NexoError.structure('DOMQL2024', `No request of this connection made the query ${JSON.stringify(query)}; the first request of a query gives its text or its definition beside its key`, {}); + } + } else if (query !== null && typeof query === 'object' && (typeof query.key === 'string' || typeof query.key === 'number')) { + made = this.#queries.get(query.key); + + if (made === undefined) { + const options = Connection.#pick(query, ['types', 'manifest']); + + made = this.#domql.query(query.text ?? query.definition, {}, options); + this.#queries.set(query.key, made); + } + } else { + throw NexoError.structure('DOMQL2024', 'A request names its query by the key an earlier request gave it, or gives it as { key, text } or { key, definition }', {}); + } + + return made.with(this.#bindingsOf(request)); + } + + /** The bindings a request gives, none where it gives none. */ + #bindingsOf(request) { + return request.bindings ?? {}; + } + + /** The owner a request names: a string, a number or null, which a release names again; any other is refused, since a host's message holds no object twice. */ + #ownerOf(request) { + const owner = request.owner ?? null; + + if (owner !== null && typeof owner !== 'string' && typeof owner !== 'number') { + throw NexoError.structure('DOMQL2025', 'A request names its owner as a string, a number or null, which a release names again', {}); + } + + return owner; + } + + /** Refuses a handle id that is no string or number, or that names a handle still running. */ + #refuseHandleId(id) { + if (typeof id !== 'string' && typeof id !== 'number') { + throw NexoError.structure('DOMQL2025', 'A request that starts a handle names it, as handle: 1, by a string or a number', {}); + } + + if (this.#handles.has(id)) { + throw NexoError.structure('DOMQL2025', `The handle ${JSON.stringify(id)} runs already; a request names a new handle by an id of its own`, {}); + } + } + + /** The handle a request names, of one of the kinds given; one that isn't running is refused. */ + #getHandle(id, kinds) { + const handle = this.#handles.get(id); + + if (handle === undefined || !kinds.includes(handle.kind)) { + throw NexoError.structure('DOMQL2025', `No ${kinds.join(' or ')} of this connection runs as the handle ${JSON.stringify(id ?? null)}`, {}); + } + + return handle; + } + + /** The generation a request gives, a whole number; the one the handle had where it gives none. */ + static #generationOf(request, current = 0) { + return Number.isInteger(request.generation) ? request.generation : current; + } + + /** The keys given of an object, those it holds alone. */ + static #pick(source, keys) { + return source === null || typeof source !== 'object' ? {} : Object.fromEntries(keys.filter(key => Object.hasOwn(source, key)).map(key => [key, source[key]])); + } + + /** A failure as a host reads it: its code, kind, message and location where DOMQL or Nexo made it, its message alone otherwise. */ + static #errorOf(error) { + if (error instanceof NexoError) { + return { code: error.code, kind: error.kind, message: error.message, location: error.location ?? {} }; + } + + return { message: error?.message ?? String(error) }; + } +} diff --git a/src/dom/Behaviors.mjs b/src/dom/Behaviors.mjs index dfc07dd..d5f37f4 100644 --- a/src/dom/Behaviors.mjs +++ b/src/dom/Behaviors.mjs @@ -186,31 +186,32 @@ export class Behaviors { /** * Hands an occurrence of the running instance to every subscription of its source listening for its owner on its receiver, in the order they subscribed, each projecting it and calling its handler before this returns, - * and answers a promise that settles once each has applied it, or rejects with the first failure, and with `DOMQL5017` where none listens. + * and answers a promise that settles once each has applied it, fulfilled with the answer of the first to subscribe, whose answer alone is taken, which a source that answers nothing gives as undefined, or rejects + * with the first failure, and with `DOMQL5017` where none listens. * @param {RunningBehavior} running The instance delivering it. * @param {string} source The event source it is an occurrence of. * @param {unknown} value The occurrence. - * @param {object} location Where the behavior stands, which a delivery no subscription hears is located at. - * @returns {Promise} + * @param {() => object} locate Answers where the behavior stands, which a delivery no subscription hears is located at; called only then. + * @returns {Promise} */ - deliver(running, source, value, location) { + deliver(running, source, value, locate) { const receivers = this.#listening.get(Behaviors.#keyOf(running.module, running.name, source))?.get(running.owner)?.get(running.receiver); if (receivers === undefined) { - return this.#unheardBy(running, source, location); + return this.#unheardBy(running, source, locate); } - // One subscription's acknowledgment is the delivery's, fulfilled with nothing as it applies the occurrence, or rejected with its failure, as joining it alone would be. + // One subscription's acknowledgment is the delivery's, fulfilled with its answer as it applies the occurrence, or rejected with its failure, as joining it alone would be. if (receivers.length === 1) { return receivers[0](value); } - // A handler that subscribes or stops another as it receives the occurrence changes who hears the next, never this one. - return Promise.all([...receivers].map(receive => receive(value))).then(() => undefined); + // A handler that subscribes or stops another as it receives the occurrence changes who hears the next, never this one. The first to subscribe answers, and the others' answers are not taken. + return Promise.all([...receivers].map((receive, index) => receive(value, index === 0))).then(([answer]) => answer); } /** The rejection of an occurrence of the running instance's source that no subscription hears, made at the first and answered until a subscription to the source listens for it. */ - #unheardBy(running, source, location) { + #unheardBy(running, source, locate) { let rejections = this.#unheard.get(running); if (rejections === undefined) { @@ -221,7 +222,7 @@ export class Behaviors { let rejected = rejections.get(source); if (rejected === undefined) { - rejected = Promise.reject(NexoError.evaluation('DOMQL5017', `No subscription of '${source}' listens for this owner on this receiver, so no subscriber applied the occurrence '${running.name}' delivered`, location)); + rejected = Promise.reject(NexoError.evaluation('DOMQL5017', `No subscription of '${source}' listens for this owner on this receiver, so no subscriber applied the occurrence '${running.name}' delivered`, locate())); // Handled as it is made, so a behavior that leaves it is never reported for it. rejected.catch(() => {}); diff --git a/src/dom/BrowserModule.mjs b/src/dom/BrowserModule.mjs index 01b32c5..6587ce2 100644 --- a/src/dom/BrowserModule.mjs +++ b/src/dom/BrowserModule.mjs @@ -7,21 +7,40 @@ import { BrowserExecutionImplementations } from './BrowserExecutionImplementatio import { BrowserObservationImplementations } from './BrowserObservationImplementations.mjs'; import { BrowserVocabularyDeclarations } from './BrowserVocabularyDeclarations.mjs'; import { BrowserVocabularyImplementations } from './BrowserVocabularyImplementations.mjs'; +import { DispatchTable } from './DispatchTable.mjs'; import { MutationObservers } from './MutationObservers.mjs'; export class BrowserModule { /** * The DOM module, whose members read the window and the document they are given, whose executions change them, and whose observation types start observations of them, the state of the behaviors running among them. - * @param {{ behaviors?: Behaviors, mutationObservers?: MutationObservers }} [dependencies] The behaviors running in this instance of DOMQL, whose state the `behavior` observation follows, and its mutation observers, - * which its observations and its owned writes run and a transient measurement drains; a module of its own has those of its own. + * @param {{ behaviors?: Behaviors, mutationObservers?: MutationObservers, moduleManifest?: object | null }} [dependencies] The behaviors running in this instance of DOMQL, whose state the `behavior` observation + * follows, and its mutation observers, which its observations and its owned writes run and a transient measurement drains, a module of its own having those of its own; and the manifest `prepare` made of it, which + * the module is created under without the checks it records. */ - static create({ behaviors = new Behaviors(), mutationObservers = new MutationObservers() } = {}) { - return BrowserVocabularyDeclarations.createModule({ + static create({ behaviors = new Behaviors(), mutationObservers = new MutationObservers(), moduleManifest = null } = {}) { + return BrowserVocabularyDeclarations.createModule(BrowserModule.#implementationsOf(behaviors, mutationObservers), { moduleManifest }); + } + + /** + * The manifest Nexo makes of the DOM module, every check of its declarations and of their registration made, which `create` creates it under without those checks; and of the modules given after it, each + * `{ name, contents }` as the dispatch table's `createModule` takes them, and the scripts the options give, as the dispatch table's `prepare` makes it of them. What is no list of modules is left to Nexo. + * @param {{ name: string, contents?: object }[]} [modules] The modules registered after it, in order. + * @param {{ scripts?: object[] }} [options] The options Nexo's `prepare` takes. + */ + static prepare(modules = [], options = undefined) { + const contents = BrowserVocabularyDeclarations.contentsOf(BrowserModule.#implementationsOf(new Behaviors(), new MutationObservers())); + + return DispatchTable.prepare(Array.isArray(modules) ? [{ name: BrowserVocabularyDeclarations.moduleName, contents }, ...modules] : modules, options); + } + + /** The module's implementations, by the key each declaration is carried out under. */ + static #implementationsOf(behaviors, mutationObservers) { + return { ...BrowserVocabularyImplementations.implementations, ...BrowserExecutionImplementations.implementationsWith({ mutationObservers }), ...BrowserObservationImplementations.implementationsWith({ mutationObservers }), // The state the behaviors of a name offer on the target, which each instance's start, update, move and end tells, and its own notify. observeBehavior: ({ request: { target, arguments: { behavior } }, notify }) => behaviors.observe(behavior, target, notify), - }); + }; } } diff --git a/src/dom/BrowserObservationImplementations.mjs b/src/dom/BrowserObservationImplementations.mjs index 97a3cb2..e97d5cc 100644 --- a/src/dom/BrowserObservationImplementations.mjs +++ b/src/dom/BrowserObservationImplementations.mjs @@ -36,6 +36,7 @@ export class BrowserObservationImplementations { observeMutation: input => BrowserObservationImplementations.#observeMutation(input, mutationObservers), observeAttachment: input => BrowserObservationImplementations.#observeAttachment(input, mutationObservers), observeIntersection: BrowserObservationImplementations.#observeIntersection, + observeLayoutSize: BrowserObservationImplementations.#observeLayoutSize, observeMedia: BrowserObservationImplementations.#observeMedia, observePixelRatio: BrowserObservationImplementations.#observePixelRatio, observeEvents: BrowserObservationImplementations.#observeEvents, @@ -221,6 +222,62 @@ export class BrowserObservationImplementations { }; } + /** + * The size layout gives an element's border box, along the axes of its writing mode, a transform aside, as the browser's resize observation measures it; pending until its first report, which the browser makes + * once it has laid the element out. It takes a new sample by observing the element again, which the browser reports with its next layout, whatever it reported before. + */ + static #observeLayoutSize({ request: { target }, notify, env: { window } }) { + let latest = { pending: true, value: null }; + // The border box a report gives, one for the element's box, in a list as engines give it now, or alone, as some gave it before. + const sampleOf = ({ borderBoxSize: sizes }) => { + const box = sizes[0] ?? sizes; + + return { pending: false, value: { inline: box.inlineSize, block: box.blockSize } }; + }; + + // The new sample asked for, which the next report answers, or null while none is. + let resampling = null; + const resampled = () => { + resampling?.resolve(); + resampling = null; + }; + const observer = new window.ResizeObserver(entries => { + latest = sampleOf(entries.at(-1)); + resampled(); + notify(); + }); + + try { + observer.observe(target, { box: 'border-box' }); + } catch (error) { + observer.disconnect(); + + throw error; + } + + return { + stop: () => { + observer.disconnect(); + resampled(); + }, + sample: () => latest, + resampleAsync: () => { + if (resampling === null) { + const asked = {}; + + asked.promise = new Promise(resolve => { + asked.resolve = resolve; + }); + resampling = asked; + observer.unobserve(target); + observer.observe(target, { box: 'border-box' }); + } + + return resampling.promise; + }, + }; + } + /** Whether a media query matches. */ static #observeMedia({ request: { arguments: { query } }, notify, env: { window } }) { const list = window.matchMedia(query); diff --git a/src/dom/BrowserVocabularyDeclarations.mjs b/src/dom/BrowserVocabularyDeclarations.mjs index 25636f2..a533e3e 100644 --- a/src/dom/BrowserVocabularyDeclarations.mjs +++ b/src/dom/BrowserVocabularyDeclarations.mjs @@ -74,6 +74,10 @@ const STYLE = { changes: 'partly-observable', misses: 'rules matching from elsew const RENDERING = [ANCESTRY_STYLE, RESIZE]; const RENDERING_MISSES = 'a stylesheet\'s rules hiding or showing it where its box keeps its size, as a box of no size, and content-visibility skipping it'; const MEASURED = { tolerance: LAYOUT_TOLERANCE }; +// What changes the size of a box as it is drawn without resizing its layout, which no resize observer reports. +const DRAWN_SIZE_MISSES = 'a transform or an animation, its own or an ancestor\'s, which changes the box as it is drawn without resizing it, and the size of an inline box, which flows as fragments no resize observer measures'; +// An animation the page's style starts on a field as the browser fills it or empties it, as a rule for `:autofill` naming one does. +const AUTOFILL_ANIMATION = { type: 'event', of: 'receiver', types: ['animationstart', 'animationcancel'] }; // An element's place among its siblings, which the structure of its tree decides, as its parent does. const SIBLINGS = { changes: 'partly-observable', misses: 'a detached tree inserted into another detached tree or into a shadow root', observations: [{ type: 'mutation', of: 'root', childList: true, subtree: true }] }; @@ -118,10 +122,10 @@ export class BrowserVocabularyDeclarations { static moduleName = 'Domql'; /** - * DOMQL's module, made as every module DOMQL carries out is, through its dispatch table: its declarations, each carrying the implementation given for it where one is. + * The contents of DOMQL's module, as its dispatch table takes them: its declarations, each carrying the implementation given for it where one is. * @param {Record} [implementations] The implementations, by the key each declaration is carried out under. */ - static createModule(implementations = {}) { + static contentsOf(implementations = {}) { // A declaration takes the implementation given under its key, and none where none is given, which leaves it resolved against and never invoked. const implementing = (key, declaration) => (implementations[key] === undefined ? declaration : { ...declaration, impl: implementations[key] }); const observationType = (name, contract, key, rest = {}) => implementing(key, { name, contract, ...rest }); @@ -149,7 +153,7 @@ export class BrowserVocabularyDeclarations { requestKind: 'subscription', }); - return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, { + return { // A bound value's type: the kind of node it is, or the window. A text or a comment node is none, and is refused as a binding. typeOf: value => nodeKindOf(value) ?? (isWindow(value) ? 'Window' : isRange(value) ? 'Range' : null), @@ -189,11 +193,12 @@ export class BrowserVocabularyDeclarations { observations: [USER_INPUT, { type: 'mutation', of: 'root', attributes: ['checked', 'name', 'type', 'value'], childList: true, subtree: true }], }), }), - state('autofilled', 'autofilled', { updates: updatesOf({ changes: 'partly-observable', misses: 'the browser filling a field on its own, as a password manager does as the page loads, which fires no event', observations: [USER_INPUT] }) }), + state('autofilled', 'autofilled', { updates: updatesOf({ changes: 'partly-observable', misses: 'the browser filling a field on its own, as a password manager does as the page loads, which fires no event, where the page\'s style starts no animation on the field as it is filled or emptied', observations: [USER_INPUT, AUTOFILL_ANIMATION] }) }), implementing('rect', property('rect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [RESIZE, SCROLLING, WINDOW_RESIZE] }) })), implementing('clientRect', property('clientRect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [CLIENT_RESIZE, SCROLLING, WINDOW_RESIZE] }) })), - implementing('size', property('size', 'Size?', { updates: updatesOf({ ...MEASURED, observations: [RESIZE] }) })), + implementing('size', property('size', 'Size?', { updates: updatesOf({ changes: 'partly-observable', misses: DRAWN_SIZE_MISSES, ...MEASURED, observations: [RESIZE] }) })), + implementing('layoutSize', property('layoutSize', 'LogicalSize?', { updates: updatesOf({ reads: 'maintained', ...MEASURED, observations: [{ type: 'layoutSize', of: 'receiver' }] }) })), implementing('clientSize', property('clientSize', 'Size?', { updates: updatesOf({ changes: 'partly-observable', misses: 'a change that leaves its border box and its content box as they were, as its border and padding changing by the same amount', ...MEASURED, observations: [CLIENT_RESIZE] }) })), implementing('scroll', property('scroll', 'Scroll?', { updates: updatesOf({ @@ -374,6 +379,7 @@ export class BrowserVocabularyDeclarations { ]), structuredType('Size', { width: 'Number', height: 'Number' }), + structuredType('LogicalSize', { inline: 'Number', block: 'Number' }), structuredType('Rectangle', { left: 'Number', top: 'Number', right: 'Number', bottom: 'Number', width: 'Number', height: 'Number' }), structuredType('Selection', { start: 'Number', end: 'Number' }), // The document's selection as it stands: its type, whether it is collapsed, its ranges, the elements its anchor and its focus are in, and its first range. @@ -449,6 +455,7 @@ export class BrowserVocabularyDeclarations { observationType('mutation', 'invalidation', 'observeMutation', { identity: ['attributes', 'childList', 'subtree', 'characterData'] }), observationType('attachment', 'invalidation', 'observeAttachment'), observationType('intersection', 'maintained', 'observeIntersection', { identity: ['root', 'margin'] }), + observationType('layoutSize', 'maintained', 'observeLayoutSize'), observationType('media', 'invalidation', 'observeMedia', { identity: ['query'] }), observationType('pixelRatio', 'invalidation', 'observePixelRatio'), observationType('event', 'invalidation', 'observeEvents', { identity: ['types', 'capture'] }), @@ -469,7 +476,17 @@ export class BrowserVocabularyDeclarations { implementing('document', property('document', 'Document', { updates: updatesOf({ changes: 'constant' }) })), implementing('window', property('window', 'Window', { updates: updatesOf({ changes: 'constant' }) })), ], - }); + }; + } + + /** + * DOMQL's module, made as every module DOMQL carries out is, through its dispatch table: its declarations, each carrying the implementation given for it where one is, created under the module manifest given + * without the checks it records of the same contents. + * @param {Record} [implementations] The implementations, by the key each declaration is carried out under. + * @param {{ moduleManifest?: object | null }} [options] The manifest the dispatch table's `prepare` made of the module, or null. + */ + static createModule(implementations = {}, { moduleManifest = null } = {}) { + return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, BrowserVocabularyDeclarations.contentsOf(implementations), undefined, moduleManifest === null ? undefined : { manifest: moduleManifest }); } /** DOMQL's module as its declarations alone, which is enough to resolve a query and carries nothing out. */ diff --git a/src/dom/BrowserVocabularyImplementations.mjs b/src/dom/BrowserVocabularyImplementations.mjs index b41c7cb..672de01 100644 --- a/src/dom/BrowserVocabularyImplementations.mjs +++ b/src/dom/BrowserVocabularyImplementations.mjs @@ -29,6 +29,12 @@ const PIXELS = /^-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?px$/i; /** The media elements. */ const MEDIA_ELEMENTS = new Set(['audio', 'video']); +/** The elements whose box shows content of their own in place of their children's, laid out as one box whatever their display: replaced elements and form controls, as HTML renders them. */ +const REPLACED_ELEMENTS = new Set(['img', 'video', 'audio', 'canvas', 'iframe', 'embed', 'object', 'input', 'textarea', 'select', 'button', 'progress', 'meter', 'math']); + +/** The namespace of SVG's elements. */ +const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; + /** The platforms whose primary shortcut modifier is Meta, Command on their keyboards, by the name `navigator.userAgentData` gives them. */ const APPLE_PLATFORMS = new Set(['macOS', 'iOS']); @@ -73,6 +79,8 @@ export class BrowserVocabularyImplementations { devicePixelRatio: ({ receiver: window }) => window.devicePixelRatio, // The property reads the rectangle against the layout viewport, and rectRelativeTo against the element it is given. rect: ({ receiver: element, args: { relativeTo = null } }) => BrowserVocabularyImplementations.#rect(element, relativeTo), + // The size layout gives its border box, as the browser's resize observation last measured it, where it is laid out as one box of some size; a box of no size, 0 by 0, is read as none. + layoutSize: ({ receiver: element, env: { window }, samples: [size] }) => (size === null || (size.inline === 0 && size.block === 0) || !BrowserVocabularyImplementations.#isLaidOutAsOneBox(element, window) ? null : size), size: ({ receiver: element }) => { const rect = BrowserVocabularyImplementations.boxOf(element); @@ -203,6 +211,16 @@ export class BrowserVocabularyImplementations { return element.isConnected && element.getClientRects().length > 0; } + /** + * Whether the element is laid out as one box, which a resize observer measures: it has a layout box, and isn't an inline box of text and elements, `display: inline` on an element that replaces its content with + * none of its own, which flows as fragments a resize observer reports as of no size. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an + * SVG element, whose box a resize observer measures as its bounding box. + */ + static #isLaidOutAsOneBox(element, window) { + return BrowserVocabularyImplementations.#hasBox(element) + && (REPLACED_ELEMENTS.has(element.localName) || element.namespaceURI === SVG_NAMESPACE || window.getComputedStyle(element).display !== 'inline'); + } + /** * The element's border box, or null where it has no layout box. Its client rects answer both for nearly every element: none where it has no box, and one that is its bounding box * where it is laid out whole; an element split into several, as an inline one across lines, asks the browser for the box that bounds them. diff --git a/src/dom/DispatchTable.mjs b/src/dom/DispatchTable.mjs index 542ca3c..ff04381 100644 --- a/src/dom/DispatchTable.mjs +++ b/src/dom/DispatchTable.mjs @@ -30,16 +30,62 @@ export class DispatchTable { * that is no function are refused with a module error naming the declaration, an unnamed indexer as `[]`, as Nexo names it, the type it stands in where it stands in one, and the key; so is a `behavior` on a * declaration that reaches none, one naming no continuous execution of the module, and an event source of a behavior given an implementation or parameters, which DOMQL carries out. * A member the evaluator invokes declaring a `behavior` reads the state that behavior offers: its implementation receives the instance running for the environment's owner on its receiver, null where none runs. + * Under a manifest `prepare` made of the same contents, which the options give as Nexo's `createModule` takes them, Nexo makes none of the checks it records; DOMQL's own checks, those above, are made either way. * @param {string} name The module's name. * @param {object} contents What the module declares. * @param {import('./Behaviors.mjs').Behaviors} [behaviors] The behaviors running, which a member reading a behavior's state finds its instance among. + * @param {{ manifest?: object | null }} [options] The options Nexo's `createModule` takes, its manifest among them. */ - static createModule(name, contents, behaviors) { + static createModule(name, contents, behaviors, options = undefined) { // Contents Nexo refuses are left to it, which names what is wrong with them. if (contents === null || typeof contents !== 'object' || Array.isArray(contents)) { - return nexo.createModule(name, contents); + return nexo.createModule(name, contents, options); } + const { declared, memberDescriptors, typeDescriptors, sourcesOf } = DispatchTable.#describe(name, contents, behaviors); + const module = nexo.createModule(name, declared, options); + + // A module keeps its types, and the members of each, in the order they were declared. + const keep = (declarations, descriptors) => declarations?.forEach((declaration, index) => { + const descriptor = descriptors?.[index]; + + if (descriptor != null) { + DispatchTable.#dispatchDescriptors.set(declaration, descriptor); + + if (descriptor.executionMode === 'continuous') { + DispatchTable.#sources.set(declaration, sourcesOf(declaration.name)); + } + } + }); + + keep(module.members, memberDescriptors); + module.types.forEach((type, index) => keep(type.members, typeDescriptors?.[index])); + + return module; + } + + /** + * The manifest Nexo makes of the modules given, each `{ name, contents }` as `createModule` takes them, in the order they are registered: of the contents Nexo is given for each, every check of each module and its + * registration made, refusing what `createModule` refuses, so a module `createModule` creates from it makes none of the checks it records; and of the scripts the options give, as Nexo's `prepare` takes them. + * @param {{ name: string, contents?: object }[]} modules The modules, in the order they are registered. + * @param {{ scripts?: object[] }} [options] The options Nexo's `prepare` takes. + */ + static prepare(modules, options = undefined) { + // What Nexo refuses is left to it, which names what is wrong with it. + const declaredOf = entry => { + const contents = entry?.contents; + + return contents === null || typeof contents !== 'object' || Array.isArray(contents) ? entry : { ...entry, contents: DispatchTable.#describe(entry.name, contents).declared }; + }; + + return nexo.prepare(Array.isArray(modules) ? modules.map(declaredOf) : modules, options); + } + + /** + * What the dispatch table keeps of a module's host calls, and the contents Nexo is given without them: each host call's descriptor, by its place among its type's members or the module's, and the event sources + * reaching each behavior, refusing what `createModule` refuses. + */ + static #describe(name, contents, behaviors) { const location = (type, declaration, declarationKey) => ({ module: String(name), ...(type === null ? {} : { type }), declaration: String(declaration), declarationKey }); const fail = (code, message, type, declaration, key) => { throw NexoError.module(code, message, location(type, declaration, key)); @@ -71,32 +117,16 @@ export class DispatchTable { fail('DOMQL4012', `'${unknown.descriptor.behavior}' is no continuous execution the module '${name}' declares, whose running instance a declaration naming it reaches`, unknown.type, unknown.name, 'behavior'); } - const module = nexo.createModule(name, { + const declared = { ...contents, ...(memberDescriptors === null ? {} : { members: declarationsOf(contents.members, memberDescriptors) }), ...(typeDescriptors === null ? {} : { types: contents.types.map((type, index) => (typeDescriptors[index] === null ? type : { ...type, members: declarationsOf(type.members, typeDescriptors[index]) })) }), - }); + }; // The event sources reaching each behavior, which its occurrences are delivered to by name. const sourcesOf = behavior => Object.freeze(new Set(described.filter(({ descriptor }) => descriptor.requestKind === 'subscription' && descriptor.behavior === behavior).map(entry => entry.name))); - // A module keeps its types, and the members of each, in the order they were declared. - const keep = (declarations, descriptors) => declarations?.forEach((declaration, index) => { - const descriptor = descriptors?.[index]; - - if (descriptor != null) { - DispatchTable.#dispatchDescriptors.set(declaration, descriptor); - - if (descriptor.executionMode === 'continuous') { - DispatchTable.#sources.set(declaration, sourcesOf(declaration.name)); - } - } - }); - - keep(module.members, memberDescriptors); - module.types.forEach((type, index) => keep(type.members, typeDescriptors?.[index])); - - return module; + return { declared, memberDescriptors, typeDescriptors, sourcesOf }; } /** A type's local name, as Nexo names it in a location, without the type parameters a declared name writes after it, as `ListExtensions` writes `T`; null for a name that is no string. */ @@ -123,9 +153,14 @@ export class DispatchTable { return null; } - const { invokedBy, requestKind, executionMode, impl, result, behavior } = member; + const { invokedBy, requestKind, executionMode, impl, result, behavior, answers } = member; const name = member.kind === 'indexer' && member.name == null ? '[]' : member.name; + // What an event source's subscription answers each event with, which the acknowledgment its source receives fulfils with; any other declaration answers nothing. + if (answers !== undefined && (invokedBy !== 'host' || requestKind !== 'subscription' || typeof answers !== 'string' || answers === '')) { + fail('DOMQL4016', 'An event source declares what its subscription answers each event with as answers, the type of the answer, written as the type of a declared binding is; nothing else answers', name, 'answers'); + } + if (invokedBy !== 'host') { for (const [key, value] of [['requestKind', requestKind], ['executionMode', executionMode]]) { if (value !== undefined) { @@ -182,7 +217,7 @@ export class DispatchTable { } } - return { requestKind, executionMode: executionMode ?? null, implementation: impl, type, module, behavior: behavior ?? null }; + return { requestKind, executionMode: executionMode ?? null, implementation: impl, type, module, behavior: behavior ?? null, answers: answers ?? null }; } /** Why a declaration's `behavior` is refused. */ @@ -203,7 +238,7 @@ export class DispatchTable { return impl === undefined ? declaration : { ...declaration, impl: input => impl({ ...input, instance: behaviors?.find(module, behavior, input.env?.owner ?? null, input.receiver) ?? null }) }; } - const { requestKind, executionMode, impl, behavior, ...declaration } = member; + const { requestKind, executionMode, impl, behavior, answers, ...declaration } = member; return declaration; } diff --git a/src/dom/DomqlQuery.mjs b/src/dom/DomqlQuery.mjs index 78f2e89..e6b1c3f 100644 --- a/src/dom/DomqlQuery.mjs +++ b/src/dom/DomqlQuery.mjs @@ -29,7 +29,8 @@ export class DomqlQuery { * @param {object} bindings The values its parameters are bound to, as the registry it is resolved against binds them. * @param {QueryOperations} operations What carries its operations out. * @param {Record} values The values given by parameter name, which `bindings` binds. - * @param {{ types?: Record }} [options] The bindings' options, the types they declare among them, which every binding of this query and of the queries `with` makes from it keeps. + * @param {{ types?: Record, manifest?: object | null }} [options] The bindings' options, the types they declare among them, which every binding of this query and of the queries `with` makes from it + * keeps, and the manifest the query is resolved from where it holds its resolutions. */ constructor(definition, bindings, operations, values, options) { this.#definition = definition; @@ -49,6 +50,11 @@ export class DomqlQuery { return query.#bindings; } + /** The options the query was made with, its manifest among them, which DOMQL resolves it with; no part of a query object's API. */ + static optionsOf(query) { + return query.#options; + } + /** Whether the value is a query object itself, as this instance made it, rather than another instance's or anything standing in for one. */ static isQuery(value) { return value !== null && typeof value === 'object' && #values in value; diff --git a/src/dom/EventListener.mjs b/src/dom/EventListener.mjs index 09861d6..4d77f33 100644 --- a/src/dom/EventListener.mjs +++ b/src/dom/EventListener.mjs @@ -5,7 +5,7 @@ import { NexoError } from '@formaui-net/nexo'; -/** A promise of an event's acknowledgment, with what settles it. @typedef {{ promise: Promise, resolve: () => void, reject: (error: unknown) => void }} Acknowledgment */ +/** A promise of an event's acknowledgment, with what settles it, fulfilled with the subscription's answer where its source declares one. @typedef {{ promise: Promise, resolve: (answer?: unknown) => void, reject: (error: unknown) => void }} Acknowledgment */ export class EventListener { #evaluator; @@ -21,6 +21,10 @@ export class EventListener { #handler; #reportError; + /** What finds, for the prepared call, what captures the answer the handler gives each event; and what captures it for the source listened to, null where it answers nothing. */ + #answerOf; + #answer = null; + /** What carries out the subscription's reactions to an event's projected value, answering a promise of each one's result, or null for a subscription that has none. @type {((value: unknown) => readonly Promise[]) | null} */ #react; @@ -70,6 +74,8 @@ export class EventListener { * @param {(pointer: string) => object} dependencies.getLocation Where a pointer into the subscription's definition stands, which a failure to start is located at. * @param {import('./Observations.mjs').Observations} dependencies.observations The observations of the window, which the projections hold sessions on. * @param {(error: unknown) => void} dependencies.reportError The environment's error reporting, which a failure of the handler reaches. + * @param {(call: object) => ((answer: unknown) => unknown) | null} [dependencies.answerOf] What captures the answer the handler gives each event, as the type the prepared call's event source declares it answers with, or null + * where it declares none; an acknowledgment then fulfils with the answer captured, where it fulfils with nothing. * @param {(sender: EventListener, args: object) => unknown} dependencies.handler Receives the event listener and, for each event, `status: 'ready'` with its projected result as `value`, and the promises of its reactions' * results as `reactions` where it has reactions, or `status: 'failed'` with the `error` that capturing or projecting it raised. What it returns is not awaited. * @param {((value: unknown) => readonly Promise[]) | null} [dependencies.react] Carries out the subscription's reactions to an event's projected value, within its delivery; null where it has none. @@ -77,8 +83,9 @@ export class EventListener { * @param {{ set: (callback: () => void, delay: number) => unknown, clear: (timer: unknown) => void }} [dependencies.timers] The window's timers, which a throttle waits on. * @param {AbortSignal} [dependencies.signal] Disposes the event listener when it aborts. */ - constructor({ evaluator, sourceOf, getLocation, observations, reportError, handler, react = null, throttle = null, timers, signal }) { + constructor({ evaluator, sourceOf, getLocation, observations, reportError, handler, answerOf = () => null, react = null, throttle = null, timers, signal }) { this.#evaluator = evaluator; + this.#answerOf = answerOf; this.#react = react; this.#throttle = throttle; this.#timers = timers; @@ -169,26 +176,27 @@ export class EventListener { } const { declaration: { name }, pointer } = call; - const location = this.#getLocation(pointer); this.#sourceCall = call; this.#preparedCall = call; + this.#answer = this.#answerOf(call); const start = this.#sourceOf(call); - // Each event is projected during its delivery, captured as its type declares before anything else reads it, and answers its acknowledgment, which a source may leave. - const deliver = event => this.#receive(event); + // Each event is projected during its delivery, captured as its type declares before anything else reads it, and answers its acknowledgment, which a source may leave. A source whose subscriptions answer says + // whether this one's answer is taken, as it is the first to subscribe; one of a module's own has this subscription alone, whose answer is. + const deliver = (event, isAnswerTaken = true) => this.#receive(event, isAnswerTaken); let sourceHandle; try { sourceHandle = start(deliver); } catch (error) { - throw NexoError.evaluation('DOMQL5003', `The event source '${name}' failed to start listening`, location, { cause: error }); + throw NexoError.evaluation('DOMQL5003', `The event source '${name}' failed to start listening`, this.#getLocation(pointer), { cause: error }); } if (typeof sourceHandle?.stop !== 'function') { - throw NexoError.evaluation('DOMQL5004', `The event source '${name}' started listening and answered nothing that stops it`, location); + throw NexoError.evaluation('DOMQL5004', `The event source '${name}' started listening and answered nothing that stops it`, this.#getLocation(pointer)); } return sourceHandle; @@ -200,20 +208,22 @@ export class EventListener { * and keeps those retained before it, and the event listener goes on listening. A projection refused because a module registered since made the resolution stale is made again through the subscription prepared again. * Nothing it does throws into the source that delivers the event. */ - #receive(event) { + #receive(event, isAnswerTaken) { if (this.#status === 'disposed') { return EventListener.#rejected(this.#ended()); } try { - return this.#project(event); + return this.#project(event, isAnswerTaken ? this.#answer : null); } catch (error) { return EventListener.#rejected(error); } } - /** Projects the event and has its handler called, now or once the caller holds the event listener, answering the promise that settles once the handler has applied it. */ - #project(event) { + /** + * Projects the event and has its handler called, now or once the caller holds the event listener, answering the promise that settles once the handler has applied it, with its answer captured where it is taken. + */ + #project(event, answer) { let projection = this.#evaluator.project(this.#preparedCall, event, { observations: this.#observations, consumer: this }); if (projection.error?.code === 'NEXO2040') { @@ -251,10 +261,10 @@ export class EventListener { if (this.#react !== null) { const reactions = this.#react(projection.value); - return this.#runOrHold(() => this.#call({ status: 'ready', value: projection.value, reactions })); + return this.#runOrHold(() => this.#call({ status: 'ready', value: projection.value, reactions }, answer)); } - return this.#hand(true, () => this.#call({ status: 'ready', value: projection.value })); + return this.#hand(true, () => this.#call({ status: 'ready', value: projection.value }, answer)); } /** @@ -323,9 +333,9 @@ export class EventListener { const acknowledgment = {}; acknowledgment.promise = new Promise((resolve, reject) => { - acknowledgment.resolve = () => { + acknowledgment.resolve = answer => { this.#acknowledgments.delete(acknowledgment); - resolve(); + resolve(answer); }; acknowledgment.reject = error => { this.#acknowledgments.delete(acknowledgment); @@ -355,6 +365,22 @@ export class EventListener { return NexoError.evaluation('DOMQL5020', `The subscription failed to apply the occurrence: ${cause?.message ?? String(cause)}`, this.#getLocation(this.#preparedCall.pointer), { cause }); } + /** + * The answer the handler gave an event, captured by the capture given, as the type its source declares it answers with, as a binding of that type is captured. One that type refuses is the handler's failure, + * `DOMQL5025` located at the subscription, its cause the refusal, which goes to the environment's error reporting as a failure of the handler does. + */ + #captureAnswer(capture, answer) { + try { + return capture(answer); + } catch (cause) { + const error = NexoError.evaluation('DOMQL5025', `The subscription answered the occurrence with a value its event source's declared answer refuses: ${cause?.message ?? String(cause)}`, this.#getLocation(this.#preparedCall.pointer), { cause }); + + this.#reportError(error); + + throw error; + } + } + /** A promise rejected with the failure, handled, so a source that leaves it is never reported for it. */ static #rejected(error) { const promise = Promise.reject(error); @@ -395,9 +421,10 @@ export class EventListener { /** * Calls the handler with the event listener and the event's arguments, unless it is disposed, and answers the promise that settles once the handler has applied the event: as it returns, or as the promise it returns - * fulfils. A failure of the handler, thrown or rejected, goes to the environment's error reporting, and never back to the handler; it rejects the promise, as a failed event the handler received does. + * fulfils, with its answer captured where it is taken, the capture given. A failure of the handler, thrown or rejected, goes to the environment's error reporting, and never back to the handler; it rejects the + * promise, as a failed event the handler received does. */ - #call(args) { + #call(args, answer = null) { if (this.#status === 'disposed') { return EventListener.#rejected(this.#ended()); } @@ -413,14 +440,43 @@ export class EventListener { } if (typeof result?.then !== 'function') { - return args.status === 'ready' ? EventListener.#applied : EventListener.#rejected(this.#failed(args.error)); + if (args.status !== 'ready') { + return EventListener.#rejected(this.#failed(args.error)); + } + + if (answer === null) { + return EventListener.#applied; + } + + try { + return Promise.resolve(this.#captureAnswer(answer, result)); + } catch (error) { + return EventListener.#rejected(error); + } } - // A handler applies the event once the promise it returned fulfils, unless the event listener ends first. + // A handler applies the event once the promise it returned fulfils, unless the event listener ends first, which settled the acknowledgment already, and answers it with what the promise fulfils with. const acknowledgment = this.#acknowledge(); + const applied = value => { + if (this.#status === 'disposed') { + return; + } + + if (args.status !== 'ready') { + acknowledgment.reject(this.#failed(args.error)); + } else if (answer === null) { + acknowledgment.resolve(); + } else { + try { + acknowledgment.resolve(this.#captureAnswer(answer, value)); + } catch (error) { + acknowledgment.reject(error); + } + } + }; try { - result.then(() => (args.status === 'ready' ? acknowledgment.resolve() : acknowledgment.reject(this.#failed(args.error))), error => { + result.then(applied, error => { this.#reportError(error); acknowledgment.reject(this.#failed(error)); }); diff --git a/src/dom/ExecutionHandle.mjs b/src/dom/ExecutionHandle.mjs index 0a3c55a..7602bd6 100644 --- a/src/dom/ExecutionHandle.mjs +++ b/src/dom/ExecutionHandle.mjs @@ -163,7 +163,9 @@ export class ExecutionHandle { * an `error` event, and each occurrence it hands `deliver`, from its start on, is delivered to the subscriptions of its source listening for its owner on its receiver. */ #start({ name, module, sources, start, receiver, args, environment, resolution, pointer }) { - const location = resolution.getLocation(pointer); + // Where the execution stands, read once a failure is located there. + let location = null; + const locate = () => (location ??= resolution.getLocation(pointer)); const running = { module, name, owner: this.#owner, receiver, instance: null, hasEnded: false }; let instance; @@ -173,13 +175,13 @@ export class ExecutionHandle { args, env: environment, reportError: error => this.#eventDispatcher.raiseError(error), - deliver: (source, value) => this.#deliver(running, sources, location, source, value), + deliver: (source, value) => this.#deliver(running, sources, locate, source, value), notify: () => this.#behaviors.notify(running), }); } catch (error) { running.hasEnded = true; - throw NexoError.evaluation('DOMQL5007', `The execution '${name}' failed to start`, location, { cause: error }); + throw NexoError.evaluation('DOMQL5007', `The execution '${name}' failed to start`, locate(), { cause: error }); } if (typeof instance?.update !== 'function' || typeof instance?.dispose !== 'function') { @@ -192,7 +194,7 @@ export class ExecutionHandle { this.#eventDispatcher.reportError(error); } - throw NexoError.evaluation('DOMQL5008', `The execution '${name}' started and answered no update and dispose`, location); + throw NexoError.evaluation('DOMQL5008', `The execution '${name}' started and answered no update and dispose`, locate()); } running.instance = instance; @@ -207,19 +209,19 @@ export class ExecutionHandle { * instance that has ended delivers nothing and rejects, and a source its behavior has none of rejects and is raised as an `error` event, since it is the module's mistake. The promise is handled, so a behavior that * leaves it is never reported for it. */ - #deliver(running, sources, location, source, value) { + #deliver(running, sources, locate, source, value) { let delivered; try { if (running.hasEnded) { - delivered = Promise.reject(NexoError.evaluation('DOMQL5018', `The execution '${running.name}' has ended, and delivers nothing more`, location)); + delivered = Promise.reject(NexoError.evaluation('DOMQL5018', `The execution '${running.name}' has ended, and delivers nothing more`, locate())); } else if (!sources.has(source)) { - const error = NexoError.evaluation('DOMQL5019', `'${String(source)}' is no event source of '${running.name}', whose occurrences ${sources.size === 0 ? 'no source of its module delivers' : `are delivered to ${[...sources].map(name => `'${name}'`).join(', ')}`}`, location); + const error = NexoError.evaluation('DOMQL5019', `'${String(source)}' is no event source of '${running.name}', whose occurrences ${sources.size === 0 ? 'no source of its module delivers' : `are delivered to ${[...sources].map(name => `'${name}'`).join(', ')}`}`, locate()); this.#eventDispatcher.raiseError(error); delivered = Promise.reject(error); } else { - delivered = this.#behaviors.deliver(running, source, value, location); + delivered = this.#behaviors.deliver(running, source, value, locate); } } catch (error) { delivered = Promise.reject(error); diff --git a/src/dom/ModuleManifest.mjs b/src/dom/ModuleManifest.mjs new file mode 100644 index 0000000..c315a5f --- /dev/null +++ b/src/dom/ModuleManifest.mjs @@ -0,0 +1,5 @@ +/** + * ModuleManifest — the manifest Nexo makes of DOMQL's own module, which DOMQL creates its module and registry under; written by scripts/module-manifest.mjs + */ + +export const ModuleManifest = Object.freeze({"format":2,"implementation":"1.0.0-preview.4","modules":[{"name":"Domql","digest":"4b4aafe680c47b13d688","after":[]}],"scripts":[]}); diff --git a/src/domql.d.ts b/src/domql.d.ts index a6518fb..beb1aea 100644 --- a/src/domql.d.ts +++ b/src/domql.d.ts @@ -284,13 +284,15 @@ export interface DomqlBindings { [name: string]: unknown; } -/** The options a query's bindings take, as Nexo's `createBindings` takes them. */ +/** The options a query takes: those its bindings take, as Nexo's `createBindings` takes them, and the manifest it is read from. */ export interface DomqlQueryOptions { /** * The type of each top-level binding it names, by its notation, a module's type qualified where another of its name would hide it, as `{ routes: 'List' }`. Data is captured as that type, a map as a * dictionary and a set as a list, and a reference holds to the type's contract. Every binding of the query keeps the types, `with`'s, an update's and a reaction's among them. */ readonly types?: Readonly>; + /** A manifest `domql.prepare` made, which the query's text is read from and its resolutions read from where it holds them, or null; every query `with` makes keeps it. */ + readonly manifest?: NexoManifest | null; } /** @@ -571,11 +573,11 @@ export interface DomqlMemberImplementationInput { readonly samples?: readonly unknown[]; /** * An event source: the function each event is handed to, `deliver(event)`. A continuous execution: the function each occurrence is handed to, `deliver(source, value)`, by the name of its module's event source. Each - * answers a promise that settles once each subscription has applied what it delivered, and never throws. + * answers a promise that settles once each subscription has applied what it delivered, fulfilled with the first subscription's answer where the event source declares `answers`, and with undefined otherwise, and never throws. */ readonly deliver?: { - (event: unknown): Promise; - (source: string, value: unknown): Promise; + (event: unknown): Promise; + (source: string, value: unknown): Promise; }; /** A once execution: the signal that aborts it. */ readonly signal?: AbortSignal; @@ -612,6 +614,11 @@ export interface DomqlMemberDeclaration { * An event source of occurrences declares no `impl` and no parameters. */ behavior?: string; + /** + * An event source: the type its subscription answers each event with, in type notation, written as a declared binding's type is, as `String?` or `Culture.Destination?`. The acknowledgment its `deliver` answers fulfils + * with the first subscription's answer, its handler's return or what the promise it returns fulfils with, captured as that type. + */ + answers?: string; /** The form its arguments take where it has parameters, an optional one included: one for each parameter, in order, the required ones before the optional ones, or one options object whose fields supply them; a function alone takes it. */ arguments?: 'positional' | 'options'; /** Its parameters; a property takes none. */ @@ -712,6 +719,121 @@ export interface DomqlModule { readonly observationTargets: readonly DomqlObservationTargetDeclaration[]; } +/** + * What `domql.prepare` answers, Nexo's manifest: plain data a host keeps as JSON and gives back as `manifest`. One that another implementation of Nexo made holds no module and no script, so every module created and + * registered under it is checked, and every query resolved. + */ +export interface NexoManifest { + /** The form of the manifest. */ + readonly format: number; + /** The version of the Nexo implementation that made it. */ + readonly implementation: string; + /** Each module it checked, in the order it registered them: its name, the digest of its contents, and the modules registered before it, by name and digest. */ + readonly modules: readonly { readonly name: string; readonly digest: string; readonly after: readonly { readonly name: string; readonly digest: string }[] }[]; + /** Each query it resolved, with its definition and its resolutions, as data. */ + readonly scripts: readonly object[]; +} + +/** The options of an operation that takes a manifest, as Nexo's takes them. */ +export interface DomqlManifestOptions { + /** A manifest `domql.prepare` made, whose checks the operation makes no more where it holds what is given, or null. */ + readonly manifest?: NexoManifest | null; +} + +/** A module `domql.prepare` checks, as `createModule` takes it. */ +export interface DomqlModuleToPrepare { + readonly name: string; + readonly contents: DomqlModuleContents; +} + +/** A query `domql.prepare` resolves, as `domql.query` takes it, its text read with `Domql` supplied. */ +export interface DomqlQueryToPrepare { + /** Its text or its definition. */ + readonly script: string | DomqlDefinition; + /** The values it is bound to. */ + readonly bindings?: DomqlBindings; + /** + * The type declared for a binding, by its name, as a notation: one given a value types it, as `domql.query`'s `types` declares one, and one given none stands for any value of its type, as `Domql.Element` stands for every + * element; a `String` and a `Boolean` decide by their value, so a binding of either is given its value. + */ + readonly types?: Readonly>; +} + +/** The options of `domql.prepare`. */ +export interface DomqlPrepareOptions { + /** The queries it resolves against the modules. */ + readonly scripts?: readonly DomqlQueryToPrepare[]; +} + +/** A query a connection's request names: by the key an earlier request gave it, or as its text or its definition beside the key it goes by from then on. */ +export type DomqlConnectionQuery = + | string + | number + | { readonly key: string | number; readonly text: string; readonly types?: Readonly>; readonly manifest?: NexoManifest | null } + | { readonly key: string | number; readonly definition: DomqlDefinition; readonly types?: Readonly>; readonly manifest?: NexoManifest | null }; + +/** What every request that names a handle gives: the handle, its owner, and the generation it is at. */ +interface DomqlHandleRequest { + /** The handle's id, a string or a number unique among the connection's running handles. */ + readonly handle: string | number; + /** Who carries it out: a string, a number or null, which a release names again. */ + readonly owner?: string | number | null; + /** The generation its deliveries carry, which a host drops a delivery of an earlier one by. */ + readonly generation?: number; +} + +/** A request a host sends a connection, in a batch. */ +export type DomqlConnectionRequest = + | (DomqlHandleRequest & { readonly request: 'evaluate' | 'execute'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }) + | (DomqlHandleRequest & { readonly request: 'watch'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings; readonly options?: { readonly schedule?: 'frame' | 'immediate' | 'delayed'; readonly delay?: number; readonly reportOn?: readonly (readonly DomqlPathItem[])[]; readonly acceptPartialObservation?: boolean } }) + | (DomqlHandleRequest & { readonly request: 'subscribe'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings; readonly options?: { readonly throttle?: number; readonly reactions?: readonly { readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }[] } }) + | (DomqlHandleRequest & { readonly request: 'run'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }) + | (DomqlHandleRequest & { readonly request: 'load'; readonly modules: readonly string[] }) + | (DomqlHandleRequest & { readonly request: 'update'; readonly bindings?: DomqlBindings; readonly options?: object }) + | { readonly request: 'refresh'; readonly handle?: string | number; readonly generation?: number; readonly resample?: boolean } + | { readonly request: 'dispose'; readonly handle: string | number } + | { readonly request: 'release'; readonly owner: string | number | null }; + +/** A failure as a connection carries it: the code, kind, message and location of one DOMQL or Nexo made, the message alone of any other. */ +export interface DomqlConnectionError { + readonly code?: string; + readonly kind?: string; + readonly message: string; + readonly location?: NexoLocation; +} + +/** + * A request's answer, as its batch's task ends: a watch's snapshot; an evaluation's or an execution's value; pending, its result delivered once it settles, with the failure of a watch's first evaluation + * where that failed; a refusal, which starts no handle; or nothing more to say. + */ +export type DomqlConnectionAnswer = + | { readonly snapshot: unknown } + | { readonly value: unknown } + | { readonly pending: true; readonly error?: DomqlConnectionError } + | { readonly error: DomqlConnectionError } + | Record; + +/** + * A delivery a connection sends its host, of one handle: a watch's snapshot whole, or the change set from the one before it; a subscription's event; the value an answer left pending; or a failure. A watch's + * deliveries carry the generation they were made at. + */ +export type DomqlConnectionDelivery = + | { readonly handle: string | number; readonly generation: number; readonly snapshot: unknown } + | { readonly handle: string | number; readonly generation: number; readonly changes: readonly DomqlChangeOperation[] } + | { readonly handle: string | number; readonly generation: number; readonly event: unknown } + | { readonly handle: string | number; readonly value: unknown } + | { readonly handle: string | number; readonly generation?: number; readonly error: DomqlConnectionError }; + +/** A connection: this instance's operations carried across a boundary as messages, for a host whose code runs elsewhere. */ +export interface DomqlConnection { + /** Whether it has closed, by `close`, or as its host acknowledged none of the deliveries its limit holds. */ + readonly isClosed: boolean; + /** Carries out the requests in order, and answers a promise of their answers, in order, once the task that carried them out has ended. */ + requestAsync(requests: readonly DomqlConnectionRequest[]): Promise; + /** Ends every handle it started, and refuses every request after it. */ + close(): void; +} + /** The versions DOMQL reports, which change apart. */ export interface DomqlVersions { /** The DOMQL runtime release version, which the package and the bundle carry. */ @@ -751,17 +873,27 @@ export interface Domql { run(source: string | DomqlDefinition, bindings?: DomqlBindings, options?: DomqlQueryOptions & DomqlOperationOptions): DomqlExecutionHandle; /** The canonical text of a request, given as its text, its definition or a query object: it parses and checks the structure, writes every import the definition records but `Domql`, which DOMQL supplies, needs no bindings, and formatting what it gives gives that again. */ format(source: string | DomqlDefinition | DomqlQuery): string; - /** Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation. */ - createModule(name: string, contents: DomqlModuleContents): DomqlModule; - /** Registers a module's vocabulary, which every request resolved afterwards may use. */ - registerModule(module: DomqlModule): void; - /** Registers the loader of a module loaded on request, by the module's name: `load` answers the module, or a promise of it, and registers nothing itself. */ - registerModuleLoader(name: string, load: () => DomqlModule | Promise): void; + /** + * Checks modules and queries ahead of time, as a host's build does, answering the manifest it keeps as JSON: each module, as `createModule` takes it, created and registered after DOMQL's own with every check, and + * each query resolved against them as `domql.query` resolves it, refusing what those refuse. Given back as `manifest`, it spares each operation the checks it records. + */ + prepare(modules: readonly DomqlModuleToPrepare[], options?: DomqlPrepareOptions): NexoManifest; + /** Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation; under the manifest `domql.prepare` made of the same contents, without the checks it records. */ + createModule(name: string, contents: DomqlModuleContents, options?: DomqlManifestOptions): DomqlModule; + /** Registers a module's vocabulary, which every request resolved afterwards may use; one created under a manifest and registered under it, without the checks it records. */ + registerModule(module: DomqlModule, options?: DomqlManifestOptions): void; + /** Registers the loader of a module loaded on request, by the module's name: `load` answers the module, or a promise of it, and registers nothing itself; the module is registered with the options given. */ + registerModuleLoader(name: string, load: () => DomqlModule | Promise, options?: DomqlManifestOptions): void; /** * Loads every module named that the instance doesn't hold yet, each through its loader, and registers it, settling once each named is registered: those a query object, a definition or a text imports, or those a * list names. A load already under way is shared. */ loadModulesAsync(modules: DomqlQuery | DomqlDefinition | string | readonly string[]): Promise; + /** + * Opens a connection that carries this instance's operations across a boundary as messages: the requests a host sends, in batches, and the deliveries `deliver` receives, those of one task together, whose + * promise answers one answer for each, an event's the host's answer to it, and settles once the host has applied them. A watch's next delivery waits for that; an event never waits. + */ + connect(deliver: (deliveries: readonly DomqlConnectionDelivery[]) => Promise, options?: { readonly window?: Window }): DomqlConnection; } export declare const domql: Domql; diff --git a/src/domql.js b/src/domql.js index 6e19c25..ff00b54 100644 --- a/src/domql.js +++ b/src/domql.js @@ -5,12 +5,14 @@ import { SnapshotComparer } from './snapshots/SnapshotComparer.mjs'; import { Behaviors } from './dom/Behaviors.mjs'; +import { Connection } from './connections/Connection.mjs'; import { BrowserModule } from './dom/BrowserModule.mjs'; import { DomqlQuery } from './dom/DomqlQuery.mjs'; import { ExecutionHandle } from './dom/ExecutionHandle.mjs'; import { DispatchTable } from './dom/DispatchTable.mjs'; import { FrameSchedule } from './dom/FrameSchedule.mjs'; import { MutationObservers } from './dom/MutationObservers.mjs'; +import { ModuleManifest } from './dom/ModuleManifest.mjs'; import { Observations } from './dom/Observations.mjs'; import { QueryEvaluator } from './dom/QueryEvaluator.mjs'; import { EventListener } from './dom/EventListener.mjs'; @@ -101,10 +103,14 @@ class Domql { /** The mutation observers this instance runs, which a transient measurement drains of the records its own change caused. */ static #mutationObservers = new MutationObservers(); - static #browserModule = BrowserModule.create({ behaviors: Domql.#behaviors, mutationObservers: Domql.#mutationObservers }); - static #moduleRegistry = nexo.createRegistry([Domql.#browserModule]); + // DOMQL's module and its registry, created under the manifest its build made of the module. + static #browserModule = BrowserModule.create({ behaviors: Domql.#behaviors, mutationObservers: Domql.#mutationObservers, moduleManifest: ModuleManifest }); + static #moduleRegistry = nexo.createRegistry([Domql.#browserModule], { manifest: ModuleManifest }); - /** The loader of each module loaded on request, by its name, which a load asks where the registry holds no module of that name; kept for the instance's life. @type {Map unknown>} */ + /** + * The loader of each module loaded on request, by its name, with the options its module is registered with, which a load asks where the registry holds no module of that name; kept for the instance's life. + * @type {Map unknown, options: object | undefined }>} + */ static #moduleLoaders = new Map(); /** The load of each module under way, by its name, which every load asking for that module meanwhile shares; released as it settles, so a failed one is asked of its loader again. @type {Map>} */ @@ -146,12 +152,13 @@ class Domql { * A query object of another DOMQL instance is refused, with how to make it here from its definition. * @param {string | object} source The request's text, or its definition. * @param {Record} [bindings] The values supplied by parameter name. - * @param {{ types?: Record }} [options] The bindings' options, as Nexo's `createBindings` takes them: `types` declares a top-level binding's type by its notation, which every binding of the query keeps. + * @param {{ types?: Record, manifest?: object | null }} [options] The bindings' options, as Nexo's `createBindings` takes them: `types` declares a top-level binding's type by its notation, which every binding of the query keeps; + * and `manifest`, a manifest `prepare` made, which the text is read from and the query's resolutions read from where it holds them, every query `with` makes keeping it. * @returns {DomqlQuery} */ static query(source, bindings = {}, options = undefined) { if (typeof source === 'string') { - const definition = nexo.parse(source, { imports: Domql.#imports }); + const definition = nexo.parse(source, { imports: Domql.#imports, manifest: Domql.#manifestOf(options) }); return new DomqlQuery(definition, Domql.#bind(bindings, options), Domql.#operations, bindings, Domql.#keep(options)); } @@ -187,20 +194,65 @@ class Domql { return nexo.format(source, { imports: Domql.#imports }); } + /** + * The manifest Nexo makes, ahead of time, of the modules given, each `{ name, contents }` as `createModule` takes them, registered in order after DOMQL's own, every check of each and of its registration made, + * refusing what `createModule` and `registerModule` refuse; and of each query `options.scripts` gives, `{ script, bindings, types }`, resolved against them as `query(script, bindings, { types })` resolves it, its text + * read with DOMQL's own module supplied. A binding given a type and no value stands for any value of that type that decides nothing. A host keeps the manifest as JSON, and gives it back as `manifest`. + * @param {{ name: string, contents: object }[]} modules The modules, in the order they are registered. + * @param {{ scripts?: { script: string | object, bindings?: Record, types?: Record }[] }} [options] + */ + static prepare(modules, options = undefined) { + if (Array.isArray(modules)) { + modules.forEach(entry => Domql.#refuseObservationTargets(entry?.name, entry?.contents?.observationTargets)); + } + + // No list of modules is left to Nexo, which refuses it; BrowserModule's own prepare, given none, prepares DOMQL's module alone. + return BrowserModule.prepare(modules === undefined ? null : modules, Domql.#withImportsSupplied(options)); + } + + /** + * The options of `prepare`, each script given as text read with DOMQL's own module supplied, as `query` reads it; one that gives imports of its own is refused, since `query` reads none. Options of another shape + * are left to Nexo, which names what is wrong with them. + */ + static #withImportsSupplied(options) { + if (!Array.isArray(options?.scripts)) { + return options; + } + + const scripts = options.scripts.map((entry, index) => { + if (entry === null || typeof entry !== 'object' || typeof entry.script !== 'string') { + return entry; + } + + if (Object.hasOwn(entry, 'imports')) { + throw NexoError.structure('DOMQL2021', `DOMQL reads a query's text with its own module supplied, as domql.query reads it, so a script it prepares gives no imports, and script ${index} gives them`, {}); + } + + return { ...entry, imports: Domql.#imports }; + }); + + return { ...options, scripts }; + } + /** * Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation, keeping each host call's request kind, execution mode and implementation in DOMQL's dispatch table. + * Under the manifest `prepare` made of the same contents, Nexo makes none of the checks it records. * @param {string} name The module's name. * @param {object} contents What the module declares. + * @param {{ manifest?: object | null }} [options] The options Nexo's `createModule` takes, its manifest among them. */ - static createModule(name, contents) { - return DispatchTable.createModule(name, contents, Domql.#behaviors); + static createModule(name, contents, options = undefined) { + return DispatchTable.createModule(name, contents, Domql.#behaviors, options); } - /** Registers a module's vocabulary, which every request resolved afterwards may use; a module declaring observation targets is refused, since DOMQL resolves its own module's alone. */ - static registerModule(module) { - if (module?.observationTargets?.length > 0) { - throw NexoError.module('DOMQL4008', `DOMQL resolves the observation targets its own module declares alone, and the module '${module.name}' declares one of its own; its observations observe the receiver, an argument of the member, or window, document, root or roots through one of DOMQL's observation types`, { module: module.name, declarationKey: 'observationTargets' }); - } + /** + * Registers a module's vocabulary, which every request resolved afterwards may use; a module declaring observation targets is refused, since DOMQL resolves its own module's alone. A module created under a manifest + * `prepare` made, registered under it beside the modules registered before it there, is registered without the checks it records. + * @param {object} module A module `createModule` made. + * @param {{ manifest?: object | null }} [options] The options Nexo's `registerModule` takes, its manifest among them. + */ + static registerModule(module, options = undefined) { + Domql.#refuseObservationTargets(module?.name, module?.observationTargets); // DOMQL carries a host call out only as its dispatch table keeps it, which a module domql.createModule made holds. const unregistered = Domql.#membersOf(module).find(({ declaration }) => declaration?.invokedBy === 'host' && DispatchTable.get(declaration) === undefined); @@ -211,25 +263,38 @@ class Domql { throw NexoError.module('DOMQL4009', `The module '${module.name}' declares the host call '${declaration.name}' without the request it makes; create the module with domql.createModule, which keeps each host call's request kind, execution mode and implementation`, { module: module.name, ...(type === null ? {} : { type }), declaration: declaration.name, declarationKey: 'requestKind' }); } - Domql.#moduleRegistry.registerModule(module); + Domql.#moduleRegistry.registerModule(module, options); + } + + /** Refuses a module declaring observation targets, which DOMQL resolves for its own module alone. */ + static #refuseObservationTargets(name, targets) { + if (Array.isArray(targets) && targets.length > 0) { + throw NexoError.module('DOMQL4008', `DOMQL resolves the observation targets its own module declares alone, and the module '${name}' declares one of its own; its observations observe the receiver, an argument of the member, or window, document, root or roots through one of DOMQL's observation types`, { module: name, declarationKey: 'observationTargets' }); + } } /** * Registers the loader of the module of the name given, which `loadModulesAsync` asks for it where this instance holds no module of that name: `load()` answers the module, or a promise of it, and registers nothing - * itself. A name that is no module's, a `load` that is no function, and a second loader for one name are refused. + * itself, the module it answers registered with the options given, as `registerModule` takes them. A name that is no module's, a `load` that is no function, options that are no object, and a second loader for one + * name are refused. * @param {string} name The module's name. * @param {() => unknown} load Answers the module. + * @param {{ manifest?: object | null }} [options] The options its module is registered with. */ - static registerModuleLoader(name, load) { + static registerModuleLoader(name, load, options = undefined) { if (typeof name !== 'string' || name === '' || typeof load !== 'function') { throw NexoError.structure('DOMQL2013', 'A module loader is registered by the name of the module it loads, and is the function that answers that module', {}); } + if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) { + throw NexoError.structure('DOMQL2013', `The options the module '${name}' is registered with are an object, as domql.registerModule takes them`, {}); + } + if (Domql.#moduleLoaders.has(name)) { throw NexoError.structure('DOMQL2013', `A loader of the module '${name}' is registered already, and a module has one loader`, {}); } - Domql.#moduleLoaders.set(name, load); + Domql.#moduleLoaders.set(name, { load, options }); } /** @@ -286,21 +351,21 @@ class Domql { let loading = Domql.#loadingModules.get(name); if (loading === undefined) { - const load = Domql.#moduleLoaders.get(name); + const loader = Domql.#moduleLoaders.get(name); - if (load === undefined) { + if (loader === undefined) { return Promise.reject(NexoError.module('DOMQL4015', `The module '${name}' is neither registered nor loaded on request; register it, or a loader of it with domql.registerModuleLoader, before a query that imports it is carried out`, { module: name })); } - loading = Domql.#registerLoadedModuleAsync(name, load).finally(() => Domql.#loadingModules.delete(name)); + loading = Domql.#registerLoadedModuleAsync(name, loader).finally(() => Domql.#loadingModules.delete(name)); Domql.#loadingModules.set(name, loading); } return loading; } - /** Asks the loader for its module and registers it, unless this instance came to hold one of its name meanwhile. */ - static async #registerLoadedModuleAsync(name, load) { + /** Asks the loader for its module and registers it with the loader's options, unless this instance came to hold one of its name meanwhile. */ + static async #registerLoadedModuleAsync(name, { load, options }) { let module; try { @@ -314,7 +379,7 @@ class Domql { } if (!Domql.#moduleRegistry.moduleNames.includes(name)) { - Domql.registerModule(module); + Domql.registerModule(module, options); } } @@ -334,11 +399,22 @@ class Domql { return Object.freeze(options.types === undefined ? { ...options } : { ...options, types: Object.freeze({ ...options.types }) }); } - /** Binds the values given by parameter name through DOMQL's registry, which every query resolves against, each binding whose type the options declare captured as that type. */ + /** Binds the values given by parameter name through DOMQL's registry, which every query resolves against, each binding whose type the options declare captured as that type; their manifest is the query's, never the bindings'. */ static #bind(bindings, options) { + if (options !== null && typeof options === 'object' && Object.hasOwn(options, 'manifest')) { + const { manifest, ...bindingOptions } = options; + + return Domql.#moduleRegistry.createBindings(bindings, bindingOptions); + } + return Domql.#moduleRegistry.createBindings(bindings, options); } + /** The manifest a query's options give, undefined where they give none. */ + static #manifestOf(options) { + return options !== null && typeof options === 'object' ? options.manifest : undefined; + } + /** Evaluates the query once, synchronously, answering the part of its result the path reaches. */ static #evaluate(query, path, { window = globalThis.window, owner = null }) { const resolution = Domql.#resolveFor('evaluate', query); @@ -496,6 +572,11 @@ class Domql { return { set: (callback, delay) => window.setTimeout(callback, delay), clear: timer => window.clearTimeout(timer) }; } + /** What captures a subscription's answer as the type its event source declares it answers with, through DOMQL's registry, as a binding of that type is captured; null where the source answers nothing. */ + static #answerOf(notation) { + return notation === null ? null : answer => Domql.#moduleRegistry.createBindings({ answer }, { types: { answer: notation } }).readValue('answer'); + } + /** * Listens to the subscription's event source from the call on, so an event that follows the call is heard, and answers the event listener; a source that cannot start fails the call. * Each event is captured and projected through the object expression that follows the source, in the task the event is delivered in, and the handler receives the event listener and the result, or the failure. The source's receiver and arguments are evaluated once, as listening starts. @@ -530,12 +611,14 @@ class Domql { const start = Domql.#implementationOf(call); - return deliver => start({ receiver: call.receiver, args: call.args, env: environment, deliver }); + // A module's own event source hands each event to deliver alone, as deliver(event), so what else it passes, as forEach's index, reaches no subscription. + return deliver => start({ receiver: call.receiver, args: call.args, env: environment, deliver: event => deliver(event) }); }, getLocation: pointer => resolution.getLocation(pointer), observations: Domql.#getObservations(window), reportError: Domql.#createErrorReporter(window), handler, + answerOf: call => Domql.#answerOf(DispatchTable.get(call.declaration).answers), react, throttle: throttle ?? null, timers: throttle === undefined ? undefined : Domql.#timersOf(window), @@ -586,7 +669,9 @@ class Domql { return null; } - const location = resolution.getLocation(call.pointer); + // Where the call stands, read once a failure is located there. + let location = null; + const locate = () => (location ??= resolution.getLocation(call.pointer)); const { name } = call.declaration; const { module, behavior } = DispatchTable.get(call.declaration); const reached = behavior === null ? {} : { instance: Domql.#behaviors.find(module, behavior, owner, call.receiver) }; @@ -597,7 +682,7 @@ class Domql { execute = Domql.#implementationOf(call); if (reached.instance === null) { - throw NexoError.evaluation('DOMQL5016', `No '${behavior}' runs for this owner on this receiver, and the command '${name}' reaches its running instance alone`, location); + throw NexoError.evaluation('DOMQL5016', `No '${behavior}' runs for this owner on this receiver, and the command '${name}' reaches its running instance alone`, locate()); } } catch (error) { call.dispose(); @@ -606,7 +691,7 @@ class Domql { } const reportError = Domql.#createErrorReporter(window); - const createExecutionError = error => NexoError.evaluation('DOMQL5001', `The execution '${name}' failed: ${error?.message ?? String(error)}`, location, { cause: error }); + const createExecutionError = error => NexoError.evaluation('DOMQL5001', `The execution '${name}' failed: ${error?.message ?? String(error)}`, locate(), { cause: error }); return new Promise((resolve, reject) => { let isSettled = false; @@ -642,7 +727,7 @@ class Domql { let value; try { - value = call.project === undefined ? null : Domql.#projectResult(evaluator, call, result, location); + value = call.project === undefined ? null : Domql.#projectResult(evaluator, call, result, locate); } catch (error) { settle(() => reject(error)); @@ -746,7 +831,9 @@ class Domql { // A resolution stays current until a registration may change what it recognizes, which Nexo alone can tell. if (resolution === undefined || !resolution.isCurrent) { try { - resolution = Domql.#moduleRegistry.resolve(query.definition, bindings); + const manifest = Domql.#manifestOf(DomqlQuery.optionsOf(query)); + + resolution = Domql.#moduleRegistry.resolve(query.definition, bindings, manifest === undefined ? undefined : { manifest }); } catch (error) { throw Domql.#unloadedImportOf(query.definition, error) ?? error; } @@ -877,7 +964,7 @@ class Domql { * Projects a once execution's result through its prepared call, or, where a module registered while it ran made the request stale, through the call prepared again, which the execution's own declaration must be, * refusing it otherwise; the execution's effect stands either way. */ - static #projectResult(evaluator, call, result, location) { + static #projectResult(evaluator, call, result, locate) { try { return call.project(result).value; } catch (error) { @@ -892,7 +979,7 @@ class Domql { again.dispose?.(); if (again.kind !== 'prepared' || again.declaration !== call.declaration) { - throw NexoError.evaluation('DOMQL5015', `A module registered since made the request of '${call.declaration.name}' stale, and preparing it again reaches ${again.kind === 'prepared' ? 'another host call' : 'no host call'}; carry it out again`, location); + throw NexoError.evaluation('DOMQL5015', `A module registered since made the request of '${call.declaration.name}' stale, and preparing it again reaches ${again.kind === 'prepared' ? 'another host call' : 'no host call'}; carry it out again`, locate()); } return again.project(result).value; @@ -1012,17 +1099,38 @@ class Domql { } /** - * Runs a query directly, in one call, as the query object its text or definition makes with the bindings runs it: the options hold the query's `types` beside the operation's own, which it is given without them, and options that - * are no object reach the operation as they are, which refuses them. + * Opens a connection that carries this instance's operations across a boundary as messages: the requests a host sends, and the deliveries `deliver` receives, each batch's promise settling once the host has applied it. + * A `deliver` that is no function is refused. + */ +const connect = (deliver, options) => { + if (typeof deliver !== 'function') { + throw NexoError.structure('DOMQL2022', 'A connection delivers through the function it is given, deliver(deliveries), which answers a promise that settles once the host has applied them', {}); + } + + return new Connection(domql, deliver, options ?? undefined); +}; + +/** The options a query takes, which an operation run directly is given beside its own. */ +const QUERY_OPTIONS = ['types', 'manifest']; + +/** + * Runs a query directly, in one call, as the query object its text or definition makes with the bindings runs it: the options hold the query's `types` and `manifest` beside the operation's own, which it is given without + * them, and options that are no object reach the operation as they are, which refuses them. */ const carryOut = (source, bindings, options, operate, handler) => { - if (options === null || typeof options !== 'object' || !Object.hasOwn(options, 'types')) { + if (options === null || typeof options !== 'object' || !QUERY_OPTIONS.some(key => Object.hasOwn(options, key))) { return operate(Domql.query(source, bindings), options, handler); } - const { types, ...operation } = options; + const operation = { ...options }; + const queryOptions = {}; + + for (const key of QUERY_OPTIONS.filter(name => Object.hasOwn(options, name))) { + queryOptions[key] = options[key]; + delete operation[key]; + } - return operate(Domql.query(source, bindings, { types }), operation, handler); + return operate(Domql.query(source, bindings, queryOptions), operation, handler); }; /** The operations that run a query directly, each a query object's own. */ @@ -1048,10 +1156,12 @@ export const domql = Object.freeze({ executeAsync: async (source, bindings, options) => carryOut(source, bindings, options, AT_ONCE.executeAsync), run: (source, bindings, options) => carryOut(source, bindings, options, AT_ONCE.run), format: source => Domql.format(source), - createModule: (name, contents) => Domql.createModule(name, contents), - registerModule: module => Domql.registerModule(module), - registerModuleLoader: (name, load) => Domql.registerModuleLoader(name, load), + prepare: (modules, options) => Domql.prepare(modules, options), + createModule: (name, contents, options) => Domql.createModule(name, contents, options), + registerModule: (module, options) => Domql.registerModule(module, options), + registerModuleLoader: (name, load, options) => Domql.registerModuleLoader(name, load, options), loadModulesAsync: modules => Domql.loadModulesAsync(modules), + connect: (deliver, options) => connect(deliver, options), info: Object.freeze({ versions: Object.freeze({ runtime: Versions.runtime, specification: Versions.specification, language: Versions.language }) }), }); diff --git a/tests/DocumentExamples.test.js b/tests/DocumentExamples.test.js index e0cecea..4c90258 100644 --- a/tests/DocumentExamples.test.js +++ b/tests/DocumentExamples.test.js @@ -87,6 +87,7 @@ const DOCUMENTS = { 'spec/vocabulary.md': [ { about: 'a member of each kind', each: true, context: COMPARED }, { about: 'scrolling', each: true, context: COMPARED }, + { about: 'the size layout gives a box', each: true, context: COMPARED }, { about: 'built-in executions', each: true }, ], 'spec/evaluation.md': [], @@ -114,6 +115,7 @@ const DOCUMENTS = { 'spec/executions.md': [], 'spec/behaviors.md': [], 'spec/api.md': [], + 'spec/connections.md': [], 'spec/examples.md': [ { about: 'a complete query' }, ], diff --git a/tests/DocumentLinks.test.js b/tests/DocumentLinks.test.js index 5b61e55..6aa418a 100644 --- a/tests/DocumentLinks.test.js +++ b/tests/DocumentLinks.test.js @@ -6,8 +6,8 @@ import { describe, it, expect } from 'vitest'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -/** The folders that hold no document of DOMQL's: Git's, dependencies, build outputs, the browser CI installs, and the notes Git ignores. */ -const SKIPPED = new Set(['.git', '.local', '.playwright', '.vs', '.idea', 'artifacts', 'bin', 'node_modules', 'obj', 'wwwroot']); +/** The folders that hold no document of DOMQL's: Git's, dependencies, build outputs, the browser CI installs, and the sandbox Git ignores. */ +const SKIPPED = new Set(['.git', '.sandbox', '.playwright', '.vs', '.idea', 'artifacts', 'bin', 'node_modules', 'obj', 'wwwroot']); /** The kinds of file a link into Nexo may stand in; a document's own links are read in Markdown alone. */ const LINKING = new Set(['.md', '.js', '.mjs', '.ts', '.ps1', '.yml', '.json']); diff --git a/tests/Domql.browser.js b/tests/Domql.browser.js index 581abed..b6af046 100644 --- a/tests/Domql.browser.js +++ b/tests/Domql.browser.js @@ -68,24 +68,24 @@ describe('domql evaluateAsync in a browser', () => { it('follows the layout a browser decides, reporting a snapshot when the size changes', async () => { const snapshots = []; - const watch = domql.query('item.size', { item: inside }).watch(); + const watch = domql.query('item.layoutSize', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); watches.push(watch); await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }]); inside.style.height = '60px'; await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }, { width: 200, height: 60 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }, { inline: 200, block: 60 }]); expect(watch.status).toBe('ready'); }); it('follows what a function call reads, the branch a changed condition selects in its body, and what it captures, made anew at each evaluation', async () => { const snapshots = []; - const watch = domql.query('let wide = item["data-wide"] == "yes"\nlet measure = function(box) if wide then box.size?.width ?? 0 else box.size?.height ?? 0 end end\nreturn measure(item)', { item: inside }).watch(); + const watch = domql.query('let wide = item["data-wide"] == "yes"\nlet measure = function(box) if wide then box.layoutSize?.inline ?? 0 else box.layoutSize?.block ?? 0 end end\nreturn measure(item)', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); watches.push(watch); @@ -302,7 +302,7 @@ describe('domql evaluateAsync in a browser', () => { it('stops reporting once it is disposed', async () => { const snapshots = []; - const watch = domql.query('item.size', { item: inside }).watch(); + const watch = domql.query('item.layoutSize', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); await frame(); @@ -310,7 +310,7 @@ describe('domql evaluateAsync in a browser', () => { inside.style.height = '80px'; await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }]); }); describe('subscribe', () => { diff --git a/tests/Domql.test.js b/tests/Domql.test.js index e27dbc7..248b240 100644 --- a/tests/Domql.test.js +++ b/tests/Domql.test.js @@ -1,8 +1,9 @@ import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'; import { DomqlQuery } from '#domql/dom/DomqlQuery.mjs'; import { domql } from '#domql/domql.js'; -import { NexoError } from '@formaui-net/nexo'; +import { nexo, NexoError } from '@formaui-net/nexo'; import { ParsedTexts } from '#nexo/language/ParsedTexts.mjs'; +import { ModuleManifest } from '#domql/dom/ModuleManifest.mjs'; /** The error a call throws. */ const getError = call => { @@ -1287,7 +1288,7 @@ describe('domql evaluates', () => { try { const query = domql.query(text, { panel }); - expect(parse).toHaveBeenCalledWith(text, [{ module: 'Domql' }]); + expect(parse).toHaveBeenCalledWith(text, [{ module: 'Domql' }], null); expect(parse.mock.results[0].value).toBe(query.definition); } finally { parse.mockRestore(); @@ -1436,13 +1437,13 @@ describe('domql evaluates', () => { }); it('is the same whatever the options, the policy of a watch checked against it each time, and made again for bindings of other types or other selecting values', () => { - const query = domql.query('panel?.size', { panel }); + const query = domql.query('panel?.layoutSize', { panel }); const before = query.resolve(); expect(query.resolve({ watch: true, acceptPartialObservation: true })).toBe(before); expect(query.resolve({ watch: true })).toBe(before); expect(() => domql.query('panel.rect', { panel }).resolve({ watch: true })).toThrow(expect.objectContaining({ kind: 'validation', code: 'DOMQL3003', message: expect.stringContaining('accepts partial observation') })); - expect(domql.query('panel?.size', { panel: null }).resolve()).not.toBe(before); + expect(domql.query('panel?.layoutSize', { panel: null }).resolve()).not.toBe(before); expect(domql.query('panel.on(type) { button = it.button }', { panel, type: 'click' }).resolve()).not.toBe(domql.query('panel.on(type) { button = it.button }', { panel, type: 'pointerdown' }).resolve()); }); @@ -4533,8 +4534,8 @@ describe('domql object root', () => { expect(refusalOf('{ a = 1, b = if f then root else null end }', { f: true }).message).toContain(heldBy('b')); }); - it('refuses root where no object expression encloses it, its receiver included, with a structure error', () => { - const message = "'root' refers to the outermost object being built, and no object expression encloses it here"; + it('refuses root where no object expression encloses it, its receiver included, with a structure error saying that a binding named root is read as ~root', () => { + const message = "'root' refers to the outermost object being built, and no object expression encloses it here; a script parameter named root is read as ~root"; expect(getError(() => domql.query('root.a'))).toMatchObject({ kind: 'structure', code: 'NEXO2018', message: expect.stringContaining(message) }); expect(getError(() => domql.query('root { a = 1 }'))).toMatchObject({ kind: 'structure', code: 'NEXO2018', message: expect.stringContaining(message) }); @@ -6411,3 +6412,143 @@ describe('domql executions carried out in one task', () => { document.body.innerHTML = ''; }); }); + +describe('domql manifests', () => { + // Each test loads its own copy of domql, with a registry of its own. + let isolated; + let panel; + let Manifest; + let parse; + let resolve; + + /** The instances of the Mark module's continuous execution, `mark(tone)`, in the order they started. */ + const marks = []; + const markContents = () => ({ + types: [elementExtension('MarkElements', [{ + name: 'mark', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'continuous', arguments: 'positional', + parameters: [{ name: 'tone', kind: 'value', type: 'String', required: true }], + impl: ({ receiver, args: { tone } }) => { + const instance = { receiver, tone, update: () => {}, dispose: () => {} }; + + marks.push(instance); + + return instance; + }, + }])], + }); + const scripts = [ + { script: 'panel.children.count', types: { panel: 'Domql.Element' } }, + { script: 'import Mark\npanel:mark(tone)', bindings: { tone: 'warm' }, types: { panel: 'Domql.Element' } }, + ]; + + /** The manifest of the Mark module and the scripts, as a host keeps it, as JSON. */ + const prepare = () => JSON.parse(JSON.stringify(isolated.prepare([{ name: 'Mark', contents: markContents() }], { scripts }))); + + beforeEach(async () => { + vi.resetModules(); + ({ domql: isolated } = await import('#domql/domql.js')); + ({ Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs')); + + const { Parser } = await import('#nexo/language/Parser.mjs'); + const { LanguageResolver } = await import('#nexo/language/LanguageResolver.mjs'); + + parse = vi.spyOn(Parser.prototype, 'parse'); + resolve = vi.spyOn(LanguageResolver.prototype, 'resolveDefinition'); + document.body.innerHTML = '
'; + panel = document.getElementById('panel'); + marks.length = 0; + }); + + afterEach(() => { + parse.mockRestore(); + resolve.mockRestore(); + document.body.innerHTML = ''; + }); + + it('prepares the modules given after DOMQL\'s own, and each script as domql.query reads it, its text read with Domql supplied', () => { + const manifest = prepare(); + + expect(manifest).toMatchObject({ implementation: nexo.info.versions.implementation }); + expect(manifest.modules.map(({ name, after }) => [name, after.map(before => before.name)])).toEqual([['Domql', []], ['Mark', ['Domql']]]); + // DOMQL's module stands at the digest its own manifest gives it, which it was created under, so a module after it registers without its checks. + expect(manifest.modules[0].digest).toBe(ModuleManifest.modules[0].digest); + expect(manifest.scripts.map(({ text, imports, resolutions }) => [text, imports, resolutions.map(({ key }) => key)])).toEqual([ + ['panel.children.count', [{ module: 'Domql' }], ['panel:Domql.Element']], + ['import Mark\npanel:mark(tone)', [{ module: 'Domql' }], ['panel:Domql.Element;tone:Nexo.String="warm"']], + ]); + }); + + it('creates and registers a module under its manifest without the checks it records, and reads a query from it, neither parsing its text nor resolving it', () => { + const manifest = prepare(); + + parse.mockClear(); + resolve.mockClear(); + + const module = isolated.createModule('Mark', markContents(), { manifest }); + + isolated.registerModule(module, { manifest }); + + expect(Manifest.recordOf(module)?.digest).toBe(manifest.modules[1].digest); + expect(isolated.query('panel.children.count', { panel }, { manifest }).evaluate()).toBe(2); + isolated.query('import Mark\npanel:mark(tone)', { panel, tone: 'warm' }, { manifest }).run().dispose(); + expect(isolated.evaluate('panel.children.count', { panel: panel.firstElementChild }, { manifest })).toBe(0); + expect(marks.map(({ receiver, tone }) => [receiver, tone])).toEqual([[panel, 'warm']]); + expect(parse).not.toHaveBeenCalled(); + expect(resolve).not.toHaveBeenCalled(); + }); + + it('resolves a query whose bindings the manifest holds no resolution for, and one made without the manifest, as it resolves any', () => { + const manifest = prepare(); + + isolated.registerModule(isolated.createModule('Mark', markContents(), { manifest }), { manifest }); + resolve.mockClear(); + + const marking = isolated.query('import Mark\npanel:mark(tone)', { panel, tone: 'warm' }, { manifest }); + + marking.with({ panel, tone: 'cold' }).run().dispose(); + expect(resolve).toHaveBeenCalledTimes(1); + expect(isolated.query('panel.children.count', { panel }).evaluate()).toBe(2); + expect(marks.map(({ tone }) => tone)).toEqual(['cold']); + }); + + it('registers a module a loader answers under the options it was registered with, and refuses options that are no object', async () => { + const manifest = prepare(); + const entryOf = vi.spyOn(Manifest, 'entryOf'); + + try { + isolated.registerModuleLoader('Mark', () => isolated.createModule('Mark', markContents(), { manifest }), { manifest }); + await isolated.loadModulesAsync(['Mark']); + + expect(entryOf.mock.results.map(({ value }) => value?.name)).toEqual(['Mark', 'Mark']); + } finally { + entryOf.mockRestore(); + } + + expect(getError(() => isolated.registerModuleLoader('Other', () => null, 'manifest'))).toMatchObject({ kind: 'structure', code: 'DOMQL2013', message: expect.stringContaining("The options the module 'Other' is registered with are an object") }); + }); + + it('creates and resolves everything with every check under a manifest of another implementation, which holds nothing', () => { + const manifest = { ...prepare(), implementation: '0.0.0' }; + const module = isolated.createModule('Mark', markContents(), { manifest }); + + isolated.registerModule(module, { manifest }); + resolve.mockClear(); + + expect(Manifest.recordOf(module)).toBeUndefined(); + expect(isolated.query('panel.children.count', { panel }, { manifest }).evaluate()).toBe(2); + expect(resolve).toHaveBeenCalledTimes(1); + }); + + it('refuses a script that gives imports of its own and a module declaring observation targets, and leaves to Nexo what Nexo refuses', () => { + const targets = { observationTargets: [{ name: 'shelf', resolve: () => null }] }; + + expect(getError(() => isolated.prepare([], { scripts: [{ script: 'panel.size', imports: ['Domql'] }] }))).toMatchObject({ kind: 'structure', code: 'DOMQL2021', message: expect.stringContaining('so a script it prepares gives no imports, and script 0 gives them') }); + expect(getError(() => isolated.prepare([{ name: 'Shelf', contents: targets }]))).toMatchObject({ kind: 'module', code: 'DOMQL4008', location: { module: 'Shelf', declarationKey: 'observationTargets' } }); + expect(getError(() => isolated.prepare('Mark'))).toMatchObject({ code: 'NEXO4565' }); + expect(getError(() => isolated.prepare())).toMatchObject({ code: 'NEXO4565' }); + expect(getError(() => isolated.prepare([], { script: [] }))).toMatchObject({ code: 'NEXO2048' }); + expect(getError(() => isolated.createModule('Mark', markContents(), { prepared: {} }))).toMatchObject({ code: 'NEXO2048' }); + expect(getError(() => isolated.query('panel.size', { panel }, { manifest: 'manifest' }))).toMatchObject({ code: 'NEXO4566' }); + expect(getError(() => isolated.query('panel.size', { panel }, { types: { panel: 'Element' }, manifesto: null }))).toMatchObject({ code: 'NEXO2048' }); + }); +}); diff --git a/tests/PackageReadme.test.js b/tests/PackageReadme.test.js index 33f9950..80d7860 100644 --- a/tests/PackageReadme.test.js +++ b/tests/PackageReadme.test.js @@ -70,6 +70,7 @@ const examples = [ { file: '21-module.js', observed: 'reads', answers: [['{ childCount: 3 }']] }, { file: '37-declared-types.js', observed: 'reads', answers: [["'submit'"]] }, { file: '31-load-on-request.js', observed: 'reads', answers: [['7']] }, + { file: '38-prepare-ahead-of-time.js', observed: 'reads', answers: [["'none'"]] }, { file: '22-execute-once.js', observed: 'reads', answers: [['true']] }, { file: '23-run-continuously.js', observed: 'printed', answers: [["'gold'"], ["'teal'"], ['undefined']] }, { file: '36-anchor.js', observed: 'printed', answers: [["'disposed'"]] }, diff --git a/tests/_conformance/change-sets.json b/tests/_conformance/change-sets.json new file mode 100644 index 0000000..c970053 --- /dev/null +++ b/tests/_conformance/change-sets.json @@ -0,0 +1,137 @@ +[ + { + "name": "replaces a field", + "previous": { "count": 1, "label": "a" }, + "changes": [{ "op": "replace", "path": "/count", "value": 2 }], + "result": { "count": 2, "label": "a" } + }, + { + "name": "replaces the whole result", + "previous": { "count": 1 }, + "changes": [{ "op": "replace", "path": "", "value": { "count": 2, "label": "b" } }], + "result": { "count": 2, "label": "b" } + }, + { + "name": "replaces a nested field with null", + "previous": { "panel": { "size": { "inline": 640, "block": 480 }, "hasFocus": false } }, + "changes": [{ "op": "replace", "path": "/panel/size", "value": null }], + "result": { "panel": { "size": null, "hasFocus": false } } + }, + { + "name": "replaces a null with an object", + "previous": { "panel": { "size": null } }, + "changes": [{ "op": "replace", "path": "/panel/size", "value": { "inline": 10, "block": 20 } }], + "result": { "panel": { "size": { "inline": 10, "block": 20 } } } + }, + { + "name": "adds an item inside a list", + "previous": { "items": [{ "key": "a1" }, { "key": "a3" }] }, + "changes": [{ "op": "add", "path": "/items/1", "value": { "key": "a2" } }], + "result": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] } + }, + { + "name": "adds an item at a list's end, by its length", + "previous": { "items": [{ "key": "a1" }] }, + "changes": [{ "op": "add", "path": "/items/1", "value": { "key": "a2" } }], + "result": { "items": [{ "key": "a1" }, { "key": "a2" }] } + }, + { + "name": "adds an item to an empty list", + "previous": { "items": [] }, + "changes": [{ "op": "add", "path": "/items/0", "value": 7 }], + "result": { "items": [7] } + }, + { + "name": "removes an item", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "remove", "path": "/items/0" }], + "result": { "items": [{ "key": "a2" }, { "key": "a3" }] } + }, + { + "name": "moves an item forward, its path read once the item has left", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "move", "from": "/items/0", "path": "/items/2" }], + "result": { "items": [{ "key": "a2" }, { "key": "a3" }, { "key": "a1" }] } + }, + { + "name": "moves an item back", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "move", "from": "/items/2", "path": "/items/0" }], + "result": { "items": [{ "key": "a3" }, { "key": "a1" }, { "key": "a2" }] } + }, + { + "name": "changes inside an item where a move left it", + "previous": { "items": [{ "key": "a1", "selected": false }, { "key": "a2", "selected": false }] }, + "changes": [ + { "op": "move", "from": "/items/0", "path": "/items/1" }, + { "op": "replace", "path": "/items/1/selected", "value": true } + ], + "result": { "items": [{ "key": "a2", "selected": false }, { "key": "a1", "selected": true }] } + }, + { + "name": "removes, adds and moves in one change set, each where the one before left the list", + "previous": { "items": [{ "key": "a" }, { "key": "b" }, { "key": "c" }, { "key": "d" }] }, + "changes": [ + { "op": "remove", "path": "/items/1" }, + { "op": "add", "path": "/items/0", "value": { "key": "e" } }, + { "op": "move", "from": "/items/3", "path": "/items/1" } + ], + "result": { "items": [{ "key": "e" }, { "key": "d" }, { "key": "a" }, { "key": "c" }] } + }, + { + "name": "reads escaped tokens, ~1 as / and ~0 as ~", + "previous": { "a/b": { "m~n": 1 } }, + "changes": [{ "op": "replace", "path": "/a~1b/m~0n", "value": 2 }], + "result": { "a/b": { "m~n": 2 } } + }, + { + "name": "reads ~01 as ~1, unescaping ~1 first", + "previous": { "~1": 1 }, + "changes": [{ "op": "replace", "path": "/~01", "value": 2 }], + "result": { "~1": 2 } + }, + { + "name": "replaces an item of a list of lists", + "previous": { "rows": [[1, 2], [3, 4]] }, + "changes": [{ "op": "replace", "path": "/rows/1/0", "value": 5 }], + "result": { "rows": [[1, 2], [5, 4]] } + }, + { + "name": "replaces a list whole", + "previous": { "items": [1, 2, 3] }, + "changes": [{ "op": "replace", "path": "/items", "value": [4] }], + "result": { "items": [4] } + }, + { + "name": "changes a result that is a list", + "previous": [{ "key": "a1" }, { "key": "a2" }], + "changes": [ + { "op": "remove", "path": "/0" }, + { "op": "add", "path": "/1", "value": { "key": "a3" } } + ], + "result": [{ "key": "a2" }, { "key": "a3" }] + }, + { + "name": "applies two change sets concatenated, as a host joins those of consecutive events", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }], "count": 2 }, + "changes": [ + { "op": "add", "path": "/items/2", "value": { "key": "a3" } }, + { "op": "replace", "path": "/count", "value": 3 }, + { "op": "move", "from": "/items/2", "path": "/items/0" }, + { "op": "remove", "path": "/items/2" }, + { "op": "replace", "path": "/count", "value": 2 } + ], + "result": { "items": [{ "key": "a3" }, { "key": "a1" }], "count": 2 } + }, + { + "name": "keeps numbers, Booleans, strings and nulls as they are", + "previous": { "values": [0, false, "", null] }, + "changes": [ + { "op": "replace", "path": "/values/0", "value": -1.5 }, + { "op": "replace", "path": "/values/1", "value": true }, + { "op": "replace", "path": "/values/2", "value": "é ☃" }, + { "op": "replace", "path": "/values/3", "value": { "nested": [null] } } + ], + "result": { "values": [-1.5, true, "é ☃", { "nested": [null] }] } + } +] diff --git a/tests/_examples/38-prepare-ahead-of-time.js b/tests/_examples/38-prepare-ahead-of-time.js new file mode 100644 index 0000000..cd37983 --- /dev/null +++ b/tests/_examples/38-prepare-ahead-of-time.js @@ -0,0 +1,24 @@ +const badges = { + types: [{ + name: 'BadgeElements', + kind: 'extension', + target: 'Domql.Element', + members: [{ + name: 'badge', + kind: 'property', + result: 'String?', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-badge'] }] }, + impl: ({ receiver: element }) => element.getAttribute('data-badge') + }] + }] +}; + +// At build time: the module and the query, checked once, as a manifest kept as JSON. +const manifest = domql.prepare([{ name: 'Badges', contents: badges }], { + scripts: [{ script: 'import Badges\npanel:badge ?? "none"', types: { panel: 'Domql.Element' } }] +}); + +// At the page's start: the same module and query, from the manifest. +domql.registerModule(domql.createModule('Badges', badges, { manifest }), { manifest }); +domql.query('import Badges\npanel:badge ?? "none"', { panel }, { manifest }).evaluate(); +// 'none' diff --git a/tests/_types/usage.ts b/tests/_types/usage.ts index 1d2b452..a0ec59b 100644 --- a/tests/_types/usage.ts +++ b/tests/_types/usage.ts @@ -1,6 +1,6 @@ // How a TypeScript caller uses DOMQL, which the declarations must accept; the test compiles this file. import { domql, NexoError } from '../../src/domql.js'; -import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions } from '../../src/domql.js'; +import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlManifestOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlPrepareOptions, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions, NexoManifest, DomqlConnection, DomqlConnectionAnswer, DomqlConnectionDelivery, DomqlConnectionRequest } from '../../src/domql.js'; const panel = document.createElement('div'); const controller = new AbortController(); @@ -268,6 +268,7 @@ const ownedWatch: DomqlWatch = domql.query('panel.children.count // An event source of a behavior names it, and the behavior hands it each occurrence, awaiting its acknowledgment where it needs one. const drops: DomqlMemberDeclaration = { name: 'drops', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'dropZone', result: 'Domql.Element' }; +const destinations: DomqlMemberDeclaration = { name: 'destinations', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'dropZone', result: 'String', answers: 'String?' }; const dropZone: DomqlMemberDeclaration = { name: 'dropZone', kind: 'function', @@ -276,7 +277,7 @@ const dropZone: DomqlMemberDeclaration = { executionMode: 'continuous', impl: ({ receiver, deliver }) => { const drop = async (event: Event) => { - const applied: Promise | undefined = deliver?.('drops', event.target); + const applied: Promise | undefined = deliver?.('drops', event.target); await applied; }; @@ -431,8 +432,25 @@ const lamps: DomqlModuleContents = { // @ts-expect-error A module declares its states as members, properties whose result is a Boolean, and no predicates. domql.createModule('Tests', { predicates: [] }); -// @ts-expect-error A module is created from its contents alone, each declaration carrying its implementation. -domql.createModule('Metrics', contents, {}); +// A host's build prepares its modules and its queries, and its start gives the manifest back, sparing the checks it records. +const prepareOptions: DomqlPrepareOptions = { scripts: [{ script: 'import Metrics\npanel.children.count', types: { panel: 'Domql.Element' } }, { script: definition, bindings: { panel } }] }; +const manifest: NexoManifest = domql.prepare([{ name: 'Metrics', contents }], prepareOptions); +const manifestOptions: DomqlManifestOptions = { manifest }; +const fromManifest: DomqlModule = domql.createModule('Metrics', contents, manifestOptions); + +domql.registerModule(fromManifest, { manifest }); +domql.registerModuleLoader('Prepared', () => domql.createModule('Prepared', { types: [] }, { manifest }), { manifest }); +domql.query('import Metrics\npanel.children.count', { panel }, { manifest }).evaluate(); +domql.evaluate('import Metrics\npanel.children.count', { panel }, { manifest, types: { panel: 'Domql.Element' }, owner: 'circuit' }); +domql.query('panel.size', { panel }, { manifest: null }); + +const manifestKept: string = JSON.stringify(manifest); + +// @ts-expect-error A module is created from its contents, under the manifest its options give, which name no other. +domql.createModule('Metrics', contents, { prepared: manifest }); + +// @ts-expect-error A prepared query is read with Domql supplied, as domql.query reads it, and gives no imports. +domql.prepare([], { scripts: [{ script: 'panel.size', imports: ['Domql'] }] }); // @ts-expect-error A reference type says whether a value belongs to it. domql.createModule('Partial', { types: [{ name: 'Lamp', kind: 'reference' }] }); @@ -519,4 +537,24 @@ const listed: DomqlDefinitionNode = { kind: 'list', items: [{ kind: 'literal', v const last: DomqlDefinitionNode = { kind: 'indexerAccess', receiver: { kind: 'local', name: 'rows' }, argument: { kind: 'fromEndIndex', offset: { kind: 'literal', value: 1 } } }; const imported: DomqlDefinition = { version: 38, imports: [{ module: 'Domql' }], expression: { kind: 'memberAccess', receiver: { kind: 'namespace', name: 'Domql' }, name: 'document' } }; -export { routing, following, painting, styled, trapped, counting, drops, dropZone, release, owned, released, ownedCount, ownedWatch, bound, version, specificationVersion, languageVersion, formatted, formattedText, kind, typeText, count, anything, waited, shorthand, selected, selectedAsync, selectedWatch, key, listening, status, snapshot, failure, ready, refreshed, viewed, viewStatus, viewReady, smaller, held, livingSnapshot, livingReady, livingRefreshed, watchedAgain, keptAgain, clicking, source, moved, stepped, trapping, reported }; +export { routing, following, painting, styled, trapped, counting, drops, destinations, dropZone, release, owned, released, ownedCount, ownedWatch, bound, version, specificationVersion, languageVersion, formatted, formattedText, kind, typeText, count, anything, waited, shorthand, selected, selectedAsync, selectedWatch, key, listening, status, snapshot, failure, ready, refreshed, viewed, viewStatus, viewReady, smaller, held, livingSnapshot, livingReady, livingRefreshed, watchedAgain, keptAgain, clicking, source, moved, stepped, trapping, reported }; + +// A host across a boundary connects, sends its requests in batches, and applies each batch of deliveries, answering an event with its own answer. +const connection: DomqlConnection = domql.connect(async (deliveries: readonly DomqlConnectionDelivery[]) => deliveries.map(delivery => ('event' in delivery ? 'answered' : null))); +const requests: DomqlConnectionRequest[] = [ + { request: 'watch', handle: 1, owner: 'panel', query: { key: 'size', text: 'panel.layoutSize' }, bindings: { panel }, options: { schedule: 'immediate' } }, + { request: 'subscribe', handle: 2, owner: 'panel', query: { key: 'clicks', text: 'panel.on("click")' }, bindings: { panel }, options: { throttle: 16 } }, + { request: 'update', handle: 1, generation: 1, bindings: { panel: document.body } }, + { request: 'refresh' }, + { request: 'release', owner: 'panel' }, +]; +const connectionAnswers: Promise = connection.requestAsync(requests); +const isClosed: boolean = connection.isClosed; + +connection.close(); + +// @ts-expect-error A request names what it asks for, among those a connection carries out. +connection.requestAsync([{ request: 'copy', handle: 3 }]); + +// @ts-expect-error A connection delivers through a function. +domql.connect('deliver'); diff --git a/tests/connections/Connection.test.js b/tests/connections/Connection.test.js new file mode 100644 index 0000000..8f07dd6 --- /dev/null +++ b/tests/connections/Connection.test.js @@ -0,0 +1,397 @@ +import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'; + +/** The error a call throws. */ +const getError = call => { + try { + call(); + } catch (error) { + return error; + } + + throw new Error('The call threw nothing'); +}; + +/** Settles once the current task and those it queued at once have run: a mutation observed, a watch evaluated, its delivery flushed. */ +const nextTask = () => new Promise(resolve => setTimeout(resolve, 0)); + +describe('a connection', () => { + // Each test loads its own copy of DOMQL, with a registry of its own. + let isolated; + let panel; + let presses; + let finish; + let marks; + let host; + + /** + * A module of an event source answered with a String?, `presses()`, whose deliver the tests keep; a property, `fragile`, that fails while its element is marked broken; a once execution, `later()`, that settles as the tests finish it; and a continuous execution, `mark(tone)`, + * whose instances the tests keep. + */ + const deskModule = () => isolated.createModule('Desk', { + types: [{ + name: 'DeskElements', kind: 'extension', target: 'Domql.Element', + members: [ + { + name: 'presses', kind: 'function', invokedBy: 'host', requestKind: 'subscription', result: 'Number', answers: 'String?', + impl: ({ deliver }) => { + presses = deliver; + + return { stop: () => { presses = null; } }; + }, + }, + { + name: 'fragile', kind: 'property', result: 'Number', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-broken'] }] }, + impl: ({ receiver }) => { + if (receiver.hasAttribute('data-broken')) { + throw new Error('broken'); + } + + return 1; + }, + }, + { name: 'later', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'once', result: 'Number', impl: () => new Promise(resolve => { finish = resolve; }) }, + { + name: 'mark', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'continuous', arguments: 'positional', + parameters: [{ name: 'tone', kind: 'value', type: 'String', required: true }], + impl: ({ args: { tone }, env, reportError }) => { + const instance = { tone, owner: env.owner, isDisposed: false, reportError, update: (receiver, next) => { instance.tone = next.tone; }, dispose: () => { instance.isDisposed = true; } }; + + marks.push(instance); + + return instance; + }, + }, + ], + }], + }); + + /** + * A host: the connection it opened, the batches of deliveries it received, in order, and what settles each, its answers given or one null for each delivery; a batch it rejects rejects its promise. + */ + const openHost = () => { + const batches = []; + const settlers = []; + const connection = isolated.connect(deliveries => new Promise((resolve, reject) => { + batches.push(deliveries); + settlers.push({ resolve: answers => resolve(answers ?? deliveries.map(() => null)), reject }); + }), { window }); + + return { connection, batches, settle: (index, answers) => settlers[index].resolve(answers), reject: (index, error) => settlers[index].reject(error) }; + }; + + const count = { key: 'count', text: '{ count = panel.children.count }' }; + const immediately = { schedule: 'immediate' }; + + beforeEach(async () => { + vi.resetModules(); + ({ domql: isolated } = await import('#domql/domql.js')); + document.body.innerHTML = '
'; + panel = document.getElementById('panel'); + presses = null; + finish = null; + marks = []; + isolated.registerModule(deskModule()); + host = openHost(); + }); + + afterEach(() => { + host.connection.close(); + document.body.innerHTML = ''; + }); + + it('is refused a deliver that is no function', () => { + expect(getError(() => isolated.connect('deliver'))).toMatchObject({ kind: 'structure', code: 'DOMQL2022' }); + }); + + it('answers a batch\'s requests in order once its task has ended: a watch with its snapshot, an execution and an evaluation with their values, each malformed request with its own failure', async () => { + const answers = await host.connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'a', query: count, bindings: { panel }, options: immediately }, + { request: 'watch', handle: 2, owner: 'a', query: 'count', bindings: { panel }, options: immediately }, + { request: 'execute', handle: 3, owner: 'a', query: { key: 'focus', text: 'panel.focus()' }, bindings: { panel } }, + { request: 'evaluate', handle: 4, query: { key: 'n', text: 'panel.children.count' }, bindings: { panel } }, + { request: 'watch', handle: 5, query: 'unknown' }, + { request: 'copy', handle: 6 }, + { request: 'watch', handle: 1, query: 'count', bindings: { panel } }, + { request: 'watch', handle: 7, owner: { name: 'a' }, query: 'count', bindings: { panel } }, + { request: 'watch', handle: 8, query: { key: 'broken', text: 'panel {' } }, + ]); + + expect(answers.slice(0, 4)).toEqual([{ snapshot: { count: 1 } }, { snapshot: { count: 1 } }, { value: true }, { value: 1 }]); + expect(answers.slice(4).map(({ error }) => [error.code, error.kind])).toEqual([['DOMQL2024', 'structure'], ['DOMQL2023', 'structure'], ['DOMQL2025', 'structure'], ['DOMQL2025', 'structure'], ['NEXO1051', 'syntax']]); + expect(answers[8].error.location).toMatchObject({ line: 1 }); + }); + + it('sends the deliveries of one task together, in the order they happened, each watch\'s change set from the snapshot before it', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }, + { request: 'watch', handle: 2, query: 'count', bindings: { panel }, options: immediately }, + ]); + + panel.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[ + { handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }, + { handle: 2, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }, + ]]); + }); + + it('holds a watch\'s next delivery until the host has applied the one before it, joining the change sets meanwhile into one, or into its snapshot whole where that is shorter', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + panel.append(document.createElement('u')); + await nextTask(); + panel.append(document.createElement('s')); + await nextTask(); + + expect(host.batches).toHaveLength(1); + + host.settle(0); + await nextTask(); + + // Two replacements of the count are longer than the snapshot that holds the latest. + expect(host.batches[1]).toEqual([{ handle: 1, generation: 0, snapshot: { count: 4 } }]); + }); + + it('delivers a subscription\'s events as they happen, never behind a watch\'s, each answered with the host\'s answer, which answers the source', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }, + { request: 'subscribe', handle: 2, owner: 'a', query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }, + ]); + + panel.append(document.createElement('i')); + await nextTask(); + + const first = presses(1); + const second = presses(2); + + await nextTask(); + + expect(host.batches.map(batch => batch.map(({ handle, event, changes }) => (event ?? changes?.length) && [handle, event ?? 'changes']))).toEqual([[[1, 'changes']], [[2, 1], [2, 2]]]); + + host.settle(1, ['one', 'two']); + + expect(await Promise.all([first, second])).toEqual(['one', 'two']); + }); + + it('answers an execution still waiting as its task ends as pending, and delivers its value once it settles', async () => { + const [answer] = await host.connection.requestAsync([{ request: 'execute', handle: 1, query: { key: 'later', text: 'import Desk\npanel:later()' }, bindings: { panel } }]); + + expect(answer).toEqual({ pending: true }); + + finish(7); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, value: 7 }]]); + }); + + it('answers a watch whose first evaluation fails as pending with that failure, and delivers its first success whole', async () => { + panel.setAttribute('data-broken', ''); + + const [answer] = await host.connection.requestAsync([{ request: 'watch', handle: 1, query: { key: 'fragile', text: 'import Desk\n{ value = panel:fragile }' }, bindings: { panel }, options: immediately }]); + + expect(answer).toEqual({ pending: true, error: expect.objectContaining({ kind: 'evaluation', message: expect.stringContaining('broken') }) }); + + panel.removeAttribute('data-broken'); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 0, snapshot: { value: 1 } }]]); + }); + + it('runs a continuous execution for its owner, updates it in place, delivers what it reports, and ends it as it is disposed', async () => { + const mark = { key: 'mark', text: 'import Desk\npanel:mark(tone)' }; + + expect(await host.connection.requestAsync([{ request: 'run', handle: 1, owner: 'a', query: mark, bindings: { panel, tone: 'warm' } }])).toEqual([{}]); + expect(marks.map(({ tone, owner }) => [tone, owner])).toEqual([['warm', 'a']]); + expect(await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel, tone: 'cold' } }])).toEqual([{}]); + expect(marks.map(({ tone }) => tone)).toEqual(['cold']); + + marks[0].reportError(new Error('out of ink')); + await nextTask(); + + // A failure the execution reports is its own, so it crosses as its message alone. + expect(host.batches).toEqual([[{ handle: 1, generation: 1, error: { message: 'out of ink' } }]]); + expect(await host.connection.requestAsync([{ request: 'dispose', handle: 1 }])).toEqual([{}]); + expect(marks[0].isDisposed).toBe(true); + }); + + it('watches anew with an update\'s bindings, its snapshot the answer and its deliveries at the update\'s generation', async () => { + const other = document.createElement('div'); + + other.append(document.createElement('b'), document.createElement('b')); + document.body.append(other); + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + expect(await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel: other } }])).toEqual([{ snapshot: { count: 2 } }]); + + panel.append(document.createElement('i')); + other.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 1, changes: [{ op: 'replace', path: '/count', value: 3 }] }]]); + }); + + it('delivers a watch\'s snapshot whole as it is refreshed, changed or not, and resumes one whose delivery the host rejected', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + host.reject(0, new Error('the host lost the delivery')); + await nextTask(); + panel.append(document.createElement('u')); + await nextTask(); + + expect(host.batches).toHaveLength(1); + + await host.connection.requestAsync([{ request: 'refresh' }]); + await nextTask(); + + expect(host.batches[1]).toEqual([{ handle: 1, generation: 0, snapshot: { count: 3 } }]); + }); + + it('ends every handle of an owner as it is released, and every handle as it closes, answering each request after it with DOMQL5027', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'a', query: count, bindings: { panel }, options: immediately }, + { request: 'run', handle: 2, owner: 'a', query: { key: 'mark', text: 'import Desk\npanel:mark(tone)' }, bindings: { panel, tone: 'warm' } }, + { request: 'subscribe', handle: 3, owner: 'b', query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }, + ]); + + expect(await host.connection.requestAsync([{ request: 'release', owner: 'a' }])).toEqual([{}]); + + panel.append(document.createElement('i')); + await nextTask(); + + expect(marks[0].isDisposed).toBe(true); + expect(host.batches).toEqual([]); + expect(presses).not.toBeNull(); + + host.connection.close(); + + expect(presses).toBeNull(); + expect(host.connection.isClosed).toBe(true); + expect((await host.connection.requestAsync([{ request: 'watch', handle: 4, query: count }]))[0].error).toMatchObject({ code: 'DOMQL5027' }); + }); + + it('makes an execution\'s query as its request is carried out, so a later request of the batch names it by its key', async () => { + const answers = await host.connection.requestAsync([ + { request: 'evaluate', handle: 1, query: count, bindings: { panel } }, + { request: 'watch', handle: 2, query: 'count', bindings: { panel }, options: immediately }, + ]); + + expect(answers).toEqual([{ value: { count: 1 } }, { snapshot: { count: 1 } }]); + }); + + it('delivers nothing of a result that settles after its handle ended, and leaves a handle that took its id alone', async () => { + const later = { key: 'later', text: 'import Desk\npanel:later()' }; + + expect(await host.connection.requestAsync([{ request: 'execute', handle: 1, query: later, bindings: { panel } }])).toEqual([{ pending: true }]); + await host.connection.requestAsync([{ request: 'dispose', handle: 1 }, { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + finish(7); + await nextTask(); + panel.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }]]); + expect(await host.connection.requestAsync([{ request: 'refresh', handle: 1 }])).toEqual([{}]); + }); + + it('fails each delivery it drops as it closes, so an event\'s acknowledgment settles', async () => { + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + const pressed = presses(1); + + host.connection.close(); + + // Closing ends the subscription first, which rejects the acknowledgment it hadn't settled. + await expect(pressed).rejects.toMatchObject({ kind: 'evaluation', code: 'DOMQL5017' }); + expect(host.batches).toEqual([]); + }); + + it('sends one task\'s deliveries whole, however many, where earlier batches left none unacknowledged', async () => { + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + for (let index = 0; index < 5000; index++) { + presses(index); + } + + await nextTask(); + + expect(host.batches.map(batch => batch.length)).toEqual([5000]); + expect(host.connection.isClosed).toBe(false); + }); + + it('ends an owner\'s pending execution as the owner is released, and no other owner\'s', async () => { + const later = { key: 'later', text: 'import Desk\npanel:later()' }; + + await host.connection.requestAsync([{ request: 'execute', handle: 1, owner: 'a', query: later, bindings: { panel } }]); + await host.connection.requestAsync([{ request: 'release', owner: null }]); + await host.connection.requestAsync([{ request: 'release', owner: 'a' }]); + + finish(1); + await nextTask(); + + expect(host.batches).toEqual([]); + expect(await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }])).toEqual([{ snapshot: { count: 1 } }]); + }); + + it('delivers again a watch whose delivery the host rejected once it is updated, and a refresh\'s failure once', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: { key: 'fragile', text: 'import Desk\n{ value = panel:fragile, count = panel.children.count }' }, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + host.reject(0, new Error('the host lost the delivery')); + await nextTask(); + await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel } }]); + panel.append(document.createElement('u')); + await nextTask(); + + expect(host.batches[1]).toEqual([{ handle: 1, generation: 1, changes: [{ op: 'replace', path: '/count', value: 3 }] }]); + + host.settle(1); + panel.setAttribute('data-broken', ''); + await nextTask(); + host.settle(2); + await nextTask(); + + // The attribute's change failed the evaluation once; the refresh evaluates again, and its failure is delivered once, as its change, not again as its rejection. + const before = host.batches.length; + + await host.connection.requestAsync([{ request: 'refresh', handle: 1 }]); + await nextTask(); + host.batches.slice(before).forEach((_, index) => host.settle(before + index)); + await nextTask(); + + expect(host.batches.slice(before).flat().filter(delivery => delivery.error !== undefined)).toHaveLength(1); + }); + + it('opens with options of null as with none', () => { + const connection = isolated.connect(() => Promise.resolve([]), null); + + expect(connection.isClosed).toBe(false); + connection.close(); + }); + + it('closes rather than hold more deliveries than its limit while the host acknowledges none, reporting DOMQL5026 to the window', async () => { + const reported = []; + + window.reportError = error => reported.push(error.code); + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + for (let index = 0; index < 4097; index++) { + presses(index); + await Promise.resolve(); + } + + await nextTask(); + delete window.reportError; + + // The window hears it from the connection, and from the subscription whose event it refused. + expect(reported.length).toBeGreaterThan(0); + expect(reported.every(code => code === 'DOMQL5026')).toBe(true); + expect(host.connection.isClosed).toBe(true); + }); +}); diff --git a/tests/dom/Behaviors.test.js b/tests/dom/Behaviors.test.js index ac10b77..e782a53 100644 --- a/tests/dom/Behaviors.test.js +++ b/tests/dom/Behaviors.test.js @@ -285,8 +285,8 @@ describe('Behaviors\' occurrences', () => { const hostCall = (name, overrides) => ({ name, kind: 'function', invokedBy: 'host', ...overrides }); /** - * A module of a zone behavior, `zone(label)`, whose instance delivers what `drop(key)` and `hover(key)` give it to its event sources `drops` and `hovers`, and its deliver as it was given; and `beats`, an event - * source of its own implementation, whose deliver the tests keep. + * A module of a zone behavior, `zone(label)`, whose instance delivers what `drop(key)`, `hover(key)` and `ask(key)` give it to its event sources `drops`, `hovers` and `asks`, the last answered with a drop, and keeps + * its deliver as it was given; and `beats`, an event source of its own implementation, whose deliver the tests keep. */ const zonesModule = () => isolated.createModule('Zones', { types: [ @@ -302,6 +302,7 @@ describe('Behaviors\' occurrences', () => { label, deliver, drop: key => deliver('drops', { key, label: instance.label }), hover: key => deliver('hovers', { key, label: instance.label }), + ask: key => deliver('asks', { key, label: instance.label }), update: (receiver, next) => Object.assign(instance, next), dispose: () => {}, }; @@ -313,6 +314,7 @@ describe('Behaviors\' occurrences', () => { }), hostCall('drops', { requestKind: 'subscription', behavior: 'zone', result: 'Drop' }), hostCall('hovers', { requestKind: 'subscription', behavior: 'zone', result: 'Drop' }), + hostCall('asks', { requestKind: 'subscription', behavior: 'zone', result: 'Drop', answers: 'Zones.Drop?' }), ], }, ], @@ -570,6 +572,86 @@ describe('Behaviors\' occurrences', () => { expect(reported).toEqual([expect.objectContaining({ message: 'broken handler' })]); }); + it('fulfils with the answer of the first subscription to a source that answers, captured as the type it declares, once every subscription has applied the occurrence', async () => { + let finish; + let isSettled = false; + + listen('asks', { zone }, {}, args => ({ key: `${args.value.key}!`, label: 'first', extra: true })); + listen('asks', { zone }, {}, () => new Promise(resolve => { + finish = resolve; + }).then(() => ({ key: 'second', label: 'second' }))); + // A later subscription's answer is never taken, so one the type would refuse fails nothing. + listen('asks', { zone }, {}, () => ({ key: 3 })); + run({ zone }); + + const answered = zones[0].ask('a'); + + answered.then(() => { + isSettled = true; + }); + await Promise.resolve(); + expect(isSettled).toBe(false); + + finish(); + await expect(answered).resolves.toEqual({ key: 'a!', label: 'first' }); + expect(reported).toEqual([]); + }); + + it('takes no answer a handler gives once its subscription has ended, which rejected the occurrence with DOMQL5017 as it ended', async () => { + let finish; + const { listener } = listen('asks', { zone }, {}, () => new Promise(resolve => { + finish = resolve; + })); + + run({ zone }); + + const answered = zones[0].ask('a'); + + listener.dispose(); + finish({ key: 3 }); + + await expect(answered).rejects.toMatchObject({ code: 'DOMQL5017' }); + await Promise.resolve(); + expect(reported).toEqual([]); + }); + + it('answers with what the promise its handler returns fulfils with, null where the handler answers nothing, and rejects an answer its type refuses with DOMQL5025, reporting it', async () => { + listen('asks', { zone }, {}, ({ value: { key } }) => { + if (key === 'none') { + return undefined; + } + + return key === 'wrong' ? { key: 3, label: 'wrong' } : Promise.resolve({ key, label: 'later' }); + }); + run({ zone }); + + await expect(zones[0].ask('a')).resolves.toEqual({ key: 'a', label: 'later' }); + await expect(zones[0].ask('none')).resolves.toBeNull(); + await expect(zones[0].ask('wrong')).rejects.toMatchObject({ kind: 'evaluation', code: 'DOMQL5025', cause: expect.objectContaining({ code: 'NEXO2045' }) }); + expect(reported).toEqual([expect.objectContaining({ code: 'DOMQL5025' })]); + }); + + it('reads where a call stands only as a failure is located there, so a start, a subscription, a delivery and an execution that fail nowhere read no text again', async () => { + const { TextLocations } = await import('#nexo/language/TextLocations.mjs'); + const locate = vi.spyOn(TextLocations.prototype, 'locate'); + + try { + const { received } = listen('drops', { zone }); + + run({ zone }); + await zones[0].drop('a'); + await isolated.query('zone.focus()', { zone }).executeAsync(); + + expect(received).toEqual([{ key: 'a', label: 'files' }]); + expect(locate).not.toHaveBeenCalled(); + + await expect(zones[0].hover('b')).rejects.toMatchObject({ code: 'DOMQL5017', location: { pointer: '/expression/chain', line: 2, column: 1 } }); + expect(locate).toHaveBeenCalledTimes(1); + } finally { + locate.mockRestore(); + } + }); + it('rejects where no subscription listens, or one ends before it applies the occurrence, with DOMQL5017', async () => { run({ zone }); @@ -693,6 +775,31 @@ describe('Behaviors\' occurrences', () => { await expect(deliver(2)).rejects.toMatchObject({ code: 'DOMQL5017' }); expect(received).toEqual([1]); }); + + it('answers an event an event source of a module\'s own delivers with its subscription\'s answer, where the source declares one', async () => { + let deliver; + + isolated.registerModule(isolated.createModule('Questions', { + types: [{ + name: 'QuestionElements', kind: 'extension', target: 'Domql.Element', + members: [hostCall('questions', { + requestKind: 'subscription', result: 'Number', answers: 'Number?', + impl: ({ deliver: delivers }) => { + deliver = delivers; + + return { stop: () => {} }; + }, + })], + }], + })); + + const questions = isolated.query('import Questions\nzone:questions()', { zone }).subscribe((sender, args) => args.value * 2); + + await expect(deliver(21)).resolves.toBe(42); + // What else the source passes beside the event, as forEach's index, reaches no subscription: each answer is taken. + await expect(Promise.all([1, 2].map(deliver))).resolves.toEqual([2, 4]); + questions.dispose(); + }); }); describe('a behavior\'s event source', () => { @@ -720,6 +827,14 @@ describe('Behaviors\' occurrences', () => { }); }); + it('is the one declaration that answers, refused where anything else declares answers, or answers no type by its notation, with DOMQL4016', () => { + const refusal = 'An event source declares what its subscription answers each event with as answers, the type of the answer, written as the type of a declared binding is; nothing else answers'; + + expect(refusalOf([lamp, hostCall('switch', { requestKind: 'execution', executionMode: 'once', behavior: 'lamp', result: 'Number', answers: 'Number' })])).toEqual({ code: 'DOMQL4016', message: refusal, module: 'Desk', type: 'DeskElements', declaration: 'switch', declarationKey: 'answers' }); + expect(refusalOf([lamp, { name: 'brightness', kind: 'property', result: 'Number', answers: 'Number' }]).code).toBe('DOMQL4016'); + expect(refusalOf([lamp, hostCall('glows', { requestKind: 'subscription', behavior: 'lamp', result: 'Number', answers: '' })]).code).toBe('DOMQL4016'); + }); + it('is refused where its behavior is no continuous execution of its module', () => { expect(refusalOf([lamp, hostCall('glows', { requestKind: 'subscription', behavior: 'lantern', result: 'Number' })]).code).toBe('DOMQL4012'); }); diff --git a/tests/dom/BrowserModule.test.js b/tests/dom/BrowserModule.test.js index 0c2e482..2eb8daa 100644 --- a/tests/dom/BrowserModule.test.js +++ b/tests/dom/BrowserModule.test.js @@ -55,4 +55,18 @@ describe('BrowserModule', () => { it('leaves the DOM vocabulary alone declaring, with no implementation to carry anything out', () => { expect(declarationsOf(BrowserVocabularyDeclarations.module).filter(declaration => implementationOf(declaration) !== undefined)).toEqual([]); }); + + it('is created under the manifest its prepare makes as the module it is with every check, carried out alike, and the vocabulary alone is not', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = BrowserModule.prepare(); + const created = BrowserModule.create({ moduleManifest: manifest }); + const namesOf = declared => declarationsOf(declared).map(declaration => [declaration.name, typeof implementationOf(declaration)]); + + expect(manifest.modules).toEqual([{ name: 'Domql', digest: expect.any(String), after: [] }]); + expect(Manifest.recordOf(created)?.digest).toBe(manifest.modules[0].digest); + expect(Manifest.recordOf(module)).toBeUndefined(); + expect(namesOf(created)).toEqual(namesOf(module)); + // A declaration carrying an implementation digests apart from one carrying none, so the vocabulary alone is created with every check. + expect(Manifest.recordOf(BrowserVocabularyDeclarations.createModule({}, { moduleManifest: manifest }))).toBeUndefined(); + }); }); diff --git a/tests/dom/BrowserObservationImplementations.test.js b/tests/dom/BrowserObservationImplementations.test.js index 6e3e9ba..5f4d278 100644 --- a/tests/dom/BrowserObservationImplementations.test.js +++ b/tests/dom/BrowserObservationImplementations.test.js @@ -236,6 +236,92 @@ describe('BrowserObservationImplementations', () => { }); }); + describe('layoutSize', () => { + /** A window whose resize observer the test controls: it records what it observes, unobserves and disconnects, with the box it observes. */ + const createResizeWindow = () => { + const fake = { + observer: null, + ResizeObserver: class { + constructor(callback) { + this.callback = callback; + this.steps = []; + fake.observer = this; + } + + observe(target, options) { + this.steps.push(['observe', target, options]); + } + + unobserve(target) { + this.steps.push(['unobserve', target]); + } + + disconnect() { + this.steps.push(['disconnect']); + } + }, + }; + + return fake; + }; + + const element = document.createElement('div'); + const start = (fake, notify = () => {}) => BrowserObservationImplementations.implementations.observeLayoutSize({ request: { type: 'layoutSize', target: element, arguments: {} }, notify, env: { window: fake } }); + const report = (inlineSize, blockSize) => ({ borderBoxSize: [{ inlineSize, blockSize }] }); + + it('is pending until the browser first reports the element, and holds the border box of its latest report along its writing mode after', () => { + const fake = createResizeWindow(); + let changes = 0; + const observation = start(fake, () => changes++); + + expect(fake.observer.steps).toEqual([['observe', element, { box: 'border-box' }]]); + expect(observation.sample()).toEqual({ pending: true, value: null }); + + fake.observer.callback([report(10, 20), report(300, 40)]); + + expect(observation.sample()).toEqual({ pending: false, value: { inline: 300, block: 40 } }); + expect(changes).toBe(1); + }); + + it('reads a border box an engine reports alone, outside a list', () => { + const fake = createResizeWindow(); + const observation = start(fake); + + fake.observer.callback([{ borderBoxSize: { inlineSize: 50, blockSize: 12 } }]); + + expect(observation.sample()).toEqual({ pending: false, value: { inline: 50, block: 12 } }); + }); + + it('takes a new sample by observing the element again, settling at the report that follows, once for every ask before it, and settles one it waits for as it stops', async () => { + const fake = createResizeWindow(); + const observation = start(fake); + const settled = []; + + fake.observer.callback([report(100, 20)]); + + const first = observation.resampleAsync().then(() => settled.push('first')); + const second = observation.resampleAsync().then(() => settled.push('second')); + + expect(fake.observer.steps.slice(1)).toEqual([['unobserve', element], ['observe', element, { box: 'border-box' }]]); + + await Promise.resolve(); + expect(settled).toEqual([]); + + fake.observer.callback([report(120, 20)]); + await Promise.all([first, second]); + + expect(settled).toEqual(['first', 'second']); + expect(observation.sample()).toEqual({ pending: false, value: { inline: 120, block: 20 } }); + + const waiting = observation.resampleAsync(); + + observation.stop(); + + await expect(waiting).resolves.toBeUndefined(); + expect(fake.observer.steps.at(-1)).toEqual(['disconnect']); + }); + }); + describe('selector', () => { /** Starts the observation of what the selector reads in the document, and answers how often it has reported. */ const observe = selector => { diff --git a/tests/dom/BrowserVocabularyDeclarations.test.js b/tests/dom/BrowserVocabularyDeclarations.test.js index 311ed78..e090b35 100644 --- a/tests/dom/BrowserVocabularyDeclarations.test.js +++ b/tests/dom/BrowserVocabularyDeclarations.test.js @@ -50,10 +50,11 @@ describe('BrowserVocabularyDeclarations', () => { it('declares the DOM\'s reference types, the views of an element and the structured types of its measurements and events', () => { expect(module.types.map(type => `${type.kind} ${type.name}${type.supertype === undefined ? '' : ` : ${type.supertype}`}${type.abstract ? ', abstract' : ''}`)).toEqual([ 'reference Node, abstract', 'reference Element : Node', 'reference Document : Node', 'reference DocumentFragment : Node', 'reference ShadowRoot : Node', 'reference Window', 'reference Shadow', 'reference Aria', 'reference Range', - 'structured Size', 'structured Rectangle', 'structured Selection', 'structured DocumentSelection', 'structured Grid', 'structured Scroll', 'structured ScrollAxis', 'structured Playback', 'structured Location', 'structured SizeLimits', 'structured File', 'structured ClipboardContent', 'structured ClipboardEntry', 'structured Listening', 'structured DomEvent', 'structured FocusEvent', 'structured InputEvent', 'structured ClipboardEvent', 'structured CompositionEvent', 'structured ToggleEvent', 'structured AnimationEvent', 'structured PointerEvent', 'structured TouchEvent', 'structured Touch', 'structured WheelEvent', 'structured KeyboardEvent', 'structured DragEvent', + 'structured Size', 'structured LogicalSize', 'structured Rectangle', 'structured Selection', 'structured DocumentSelection', 'structured Grid', 'structured Scroll', 'structured ScrollAxis', 'structured Playback', 'structured Location', 'structured SizeLimits', 'structured File', 'structured ClipboardContent', 'structured ClipboardEntry', 'structured Listening', 'structured DomEvent', 'structured FocusEvent', 'structured InputEvent', 'structured ClipboardEvent', 'structured CompositionEvent', 'structured ToggleEvent', 'structured AnimationEvent', 'structured PointerEvent', 'structured TouchEvent', 'structured Touch', 'structured WheelEvent', 'structured KeyboardEvent', 'structured DragEvent', ]); expect(module.types.filter(type => type.kind === 'structured').map(type => `${type.name} { ${type.members.filter(member => member.kind === 'property').map(member => `${member.name}: ${member.result}`).join(', ')} }`)).toEqual([ 'Size { width: Number, height: Number }', + 'LogicalSize { inline: Number, block: Number }', 'Rectangle { left: Number, top: Number, right: Number, bottom: Number, width: Number, height: Number }', 'Selection { start: Number, end: Number }', 'DocumentSelection { type: String, collapsed: Boolean, rangeCount: Number, anchorElement: Element?, focusElement: Element?, range: Range? }', @@ -89,7 +90,7 @@ describe('BrowserVocabularyDeclarations', () => { 'Node.children', 'Node.parent', 'Node.root', 'Node.host', 'Node.first', 'Node.all', 'Node.contains', 'Element.disabled', 'Element.readonly', 'Element.textEditable', 'Element.focused', 'Element.focusWithin', 'Element.displayed', 'Element.focusable', 'Element.hovered', 'Element.popoverOpen', 'Element.checked', 'Element.indeterminate', 'Element.autofilled', 'Element.localName', 'Element.classes', 'Element.text', 'Element.html', 'Element.value', 'Element.playback', 'Element.inlineStyle', 'Element.files', 'Element.sizeLimits', - 'Element.rect', 'Element.clientRect', 'Element.size', 'Element.clientSize', 'Element.scroll', 'Element.grid', 'Element.selection', 'Element.shadow', 'Element.aria', 'Element.direction', 'Element.attached', 'Element.hasChildren', 'Element.hasSelection', + 'Element.rect', 'Element.clientRect', 'Element.size', 'Element.layoutSize', 'Element.clientSize', 'Element.scroll', 'Element.grid', 'Element.selection', 'Element.shadow', 'Element.aria', 'Element.direction', 'Element.attached', 'Element.hasChildren', 'Element.hasSelection', 'Element.previousSibling', 'Element.nextSibling', 'Element.index', 'Element.hasPointerCapture', 'Element[]', 'Element.attribute', 'Element.class', 'Element.style', 'Element.intersects', 'Element.overlaps', 'Element.matches', 'Element.rectRelativeTo', 'Element.closest', 'Element.scrollContainer', 'Element.on', 'Element.dispatch', 'Element.focus', 'Element.scrollTo', 'Element.scrollBy', 'Element.scrollIntoView', 'Element.showPopover', 'Element.hidePopover', 'Element.showModal', 'Element.capturePointer', 'Element.releasePointer', 'Element.play', 'Element.pause', 'Element.mute', 'Element.unmute', 'Element.markIndeterminate', 'Element.clearIndeterminate', 'Element.replaceValue', 'Element.select', 'Element.ownAttribute', 'Element.ownClass', 'Element.ownStyle', 'Element.ownText', 'Element.ownFileSource', 'Element.close', @@ -134,7 +135,7 @@ describe('BrowserVocabularyDeclarations', () => { const measured = typeMembers.filter(({ member }) => member.updates?.tolerance !== undefined).map(({ type, member }) => `${nameOf(type, member)} within ${member.updates.tolerance}`); expect(measured).toEqual([ - 'Element.rect within 0.05', 'Element.clientRect within 0.05', 'Element.size within 0.05', 'Element.clientSize within 0.05', 'Element.scroll within 0.05', 'Element.grid within 0.05', 'Element.rectRelativeTo within 0.05', + 'Element.rect within 0.05', 'Element.clientRect within 0.05', 'Element.size within 0.05', 'Element.layoutSize within 0.05', 'Element.clientSize within 0.05', 'Element.scroll within 0.05', 'Element.grid within 0.05', 'Element.rectRelativeTo within 0.05', 'Window.size within 0.05', 'Window.scroll within 0.05', 'Range.rect within 0.05', ]); }); @@ -291,7 +292,7 @@ describe('BrowserVocabularyDeclarations', () => { result: '@selected', parameters: [{ name: 'type', type: 'String', fixed: true, selects: 'type', selector: 'event' }, { name: 'options', type: 'Listening?', required: false, default: null, nulls: 'accept' }], }); - expect(DispatchTable.get(member)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: undefined, type: type.name, module: 'Domql', behavior: null }); + expect(DispatchTable.get(member)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: undefined, type: type.name, module: 'Domql', behavior: null, answers: null }); } expect(module.typeSelectors).toEqual([{ name: 'event' }]); @@ -392,10 +393,10 @@ describe('BrowserVocabularyDeclarations', () => { expect([...new Set(named)].sort()).toEqual(module.observationTargets.map(target => target.name).sort()); }); - it('are maintained only for the member that reads maintained values', () => { + it('are maintained only for the members that read maintained values', () => { const maintained = evaluated.filter(declaration => declaration.updates.observations.some(observation => registry.getObservationType(observation.type).contract === 'maintained')); - expect(maintained.map(declaration => declaration.name)).toEqual(['intersects']); + expect(maintained.map(declaration => declaration.name)).toEqual(['layoutSize', 'intersects']); expect(maintained.every(declaration => declaration.updates.reads === 'maintained')).toBe(true); }); }); diff --git a/tests/dom/DispatchTable.test.js b/tests/dom/DispatchTable.test.js index 591cce0..4ad085e 100644 --- a/tests/dom/DispatchTable.test.js +++ b/tests/dom/DispatchTable.test.js @@ -1,4 +1,6 @@ import { describe, it, expect } from 'vitest'; +import { nexo } from '@formaui-net/nexo'; +import { BrowserVocabularyDeclarations } from '#domql/dom/BrowserVocabularyDeclarations.mjs'; import { DispatchTable } from '#domql/dom/DispatchTable.mjs'; /** The module error creating a module throws: its code, its message, and where its location says it is. */ @@ -33,13 +35,23 @@ describe('DispatchTable', () => { }); const [beats, mark, size] = module.members; - expect(DispatchTable.get(beats)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: null, module: 'Desk', behavior: null }); - expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'once', implementation: execute, type: null, module: 'Desk', behavior: null }); + expect(DispatchTable.get(beats)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: null, module: 'Desk', behavior: null, answers: null }); + expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'once', implementation: execute, type: null, module: 'Desk', behavior: null, answers: null }); expect(DispatchTable.get(size)).toBeUndefined(); expect([beats, mark].map(declaration => ['requestKind', 'executionMode', 'impl'].some(key => key in declaration))).toEqual([false, false]); expect(typeof size.impl).toBe('function'); }); + it('keeps the type an event source answers each event with, and gives Nexo the declaration without it', () => { + const module = DispatchTable.createModule('Desk', { + members: [hostCall({ name: 'asks', requestKind: 'subscription', result: 'Number', answers: 'String?', impl: () => ({ stop: () => {} }) })], + }); + const [asks] = module.members; + + expect(DispatchTable.get(asks).answers).toBe('String?'); + expect(Object.keys(asks)).not.toContain('answers'); + }); + it('keeps a host call standing within a type, and one declaration standing in several types for each declaration the module makes of it', () => { const start = () => ({ stop: () => {} }); const beats = hostCall({ name: 'beats', requestKind: 'subscription', result: 'Number', impl: start }); @@ -52,17 +64,17 @@ describe('DispatchTable', () => { }); const [lamp, fan, extension] = module.types; - expect(DispatchTable.get(lamp.members[0])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Lamp', module: 'Desk', behavior: null }); - expect(DispatchTable.get(fan.members[1])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Fan', module: 'Desk', behavior: null }); + expect(DispatchTable.get(lamp.members[0])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Lamp', module: 'Desk', behavior: null, answers: null }); + expect(DispatchTable.get(fan.members[1])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Fan', module: 'Desk', behavior: null, answers: null }); expect(DispatchTable.get(fan.members[0])).toBeUndefined(); - expect(DispatchTable.get(extension.members[0])).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: 'DeskElements', module: 'Desk', behavior: null }); + expect(DispatchTable.get(extension.members[0])).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: 'DeskElements', module: 'Desk', behavior: null, answers: null }); expect('impl' in lamp.members[0]).toBe(false); }); it('keeps a host call declared without an implementation, resolved against and never carried out', () => { const [mark] = DispatchTable.createModule('Desk', { members: [hostCall({ requestKind: 'execution', executionMode: 'continuous' })] }).members; - expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: null, module: 'Desk', behavior: null }); + expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: null, module: 'Desk', behavior: null, answers: null }); }); it('refuses a host call whose request kind is missing or unknown', () => { @@ -110,4 +122,49 @@ describe('DispatchTable', () => { expect(refusalOf({ members: {} })).toEqual({ code: 'NEXO4503', module: 'Desk', declarationKey: 'members', message: expect.stringContaining("A module's members are a list") }); expect(refusalOf({ members: [hostCall({ requestKind: 'execution', executionMode: 'once', result: 'Boolean', updates: { changes: 'constant', reads: 'fresh' } })] })).toEqual({ code: 'NEXO4030', module: 'Desk', declaration: 'mark', declarationKey: 'updates', message: expect.stringContaining('so it declares no updates') }); }); + + describe('a manifest', () => { + const execute = () => true; + const contents = () => ({ types: [elementExtension([hostCall({ requestKind: 'execution', executionMode: 'once', result: 'Boolean', impl: execute })])] }); + + /** The error a call throws: its code, and where its location says it is. */ + const failureOf = call => { + try { + call(); + } catch (error) { + return { code: error.code, ...error.location }; + } + + throw new Error('The call threw nothing'); + }; + + it('is the one Nexo makes of the contents the table gives it, without the keys it keeps, each module in the order given', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = DispatchTable.prepare([{ name: 'Domql', contents: BrowserVocabularyDeclarations.contentsOf() }, { name: 'Desk', contents: contents() }]); + // Desk as Nexo is given it: its host call without the request kind, the execution mode and the implementation the table keeps. + const declared = { types: [elementExtension([{ name: 'mark', kind: 'function', invokedBy: 'host', parameters: [], result: 'Boolean' }])] }; + + expect(manifest).toMatchObject({ implementation: nexo.info.versions.implementation, scripts: [] }); + expect(manifest.modules.map(({ name, after }) => [name, after.map(before => before.name)])).toEqual([['Domql', []], ['Desk', ['Domql']]]); + expect(manifest.modules[1].digest).toBe(Manifest.digestOf(declared)); + }); + + it('creates a module of the same contents under it with none of Nexo\'s checks it records, keeping each host call as the table keeps it, and one of other contents with every check', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = DispatchTable.prepare([{ name: 'Domql', contents: BrowserVocabularyDeclarations.contentsOf() }, { name: 'Desk', contents: contents() }]); + const module = DispatchTable.createModule('Desk', contents(), undefined, { manifest }); + const [declaration] = module.types[0].members; + + expect(Manifest.recordOf(module)?.digest).toBe(manifest.modules[1].digest); + expect(DispatchTable.get(declaration)).toMatchObject({ requestKind: 'execution', executionMode: 'once', implementation: execute, module: 'Desk', type: 'DeskElements' }); + expect(Manifest.recordOf(DispatchTable.createModule('Desk', { members: [] }, undefined, { manifest }))).toBeUndefined(); + expect(Manifest.recordOf(DispatchTable.createModule('Desk', contents()))).toBeUndefined(); + }); + + it('refuses what creating the module refuses, and leaves what Nexo refuses to Nexo', () => { + expect(failureOf(() => DispatchTable.prepare([{ name: 'Desk', contents: { members: [hostCall()] } }]))).toEqual({ code: 'DOMQL4002', module: 'Desk', declaration: 'mark', declarationKey: 'requestKind' }); + expect(failureOf(() => DispatchTable.prepare('Desk')).code).toBe('NEXO4565'); + expect(failureOf(() => DispatchTable.prepare([{ name: 'Desk', contents: [] }])).code).toBe('NEXO4501'); + }); + }); }); diff --git a/tests/dom/LayoutSize.browser.js b/tests/dom/LayoutSize.browser.js new file mode 100644 index 0000000..28b460c --- /dev/null +++ b/tests/dom/LayoutSize.browser.js @@ -0,0 +1,112 @@ +import { afterEach, beforeEach, describe, it, expect } from 'vitest'; +import { domql } from '#domql/domql.js'; + +/** Adds an element with the style to the document, which a real browser lays out. */ +const add = (style, parent = document.body) => { + const element = document.createElement('div'); + + element.style.cssText = style; + parent.append(element); + + return element; +}; + +/** The size layout gives a box, which each engine's resize observer reports, its first report included, in Chromium, Firefox and WebKit. */ +describe('layoutSize in a browser', () => { + beforeEach(() => { + document.body.style.margin = '0'; + }); + + afterEach(() => { + document.body.innerHTML = ''; + }); + + describe('the size layout gives a box', () => { + // Settles once the browser has laid out and painted twice, so a resize observer has reported what changed; a test ends with it, so the next one starts no observation while the browser still delivers + // the resize observer's reports, which it would report as undelivered. + const afterLayout = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + + it('is its border box along the axes of its writing mode, as the resize observer measures it, pending until its first report', async () => { + const box = add('width: 120px; height: 40px; padding: 10px; border: 2px solid'); + const vertical = add('writing-mode: vertical-rl; width: 40px; height: 300px'); + + expect(await domql.query('{ box = box.layoutSize, vertical = vertical.layoutSize }', { box, vertical }).evaluateAsync()).toEqual({ + box: { inline: 144, block: 64 }, vertical: { inline: 300, block: 40 }, + }); + await afterLayout(); + }); + + it('leaves a transform aside, which changes the size a box is drawn at, and so a watch of size, which misses it, but not its layout', async () => { + const box = add('width: 200px; height: 50px; transform-origin: 0 0'); + + box.style.transform = 'scale(0.5)'; + + expect(await domql.query('{ drawn = box.size, laidOut = box.layoutSize }', { box }).evaluateAsync()).toEqual({ + drawn: { width: 100, height: 25 }, laidOut: { inline: 200, block: 50 }, + }); + await afterLayout(); + }); + + it('is null where the element is no one box: detached, not rendered, or an inline box of text, but an inline image and an SVG shape are one', async () => { + const hidden = add('display: none; width: 30px; height: 30px'); + const span = document.createElement('span'); + const image = document.createElement('img'); + const drawing = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + + span.textContent = 'words that flow'; + image.style.cssText = 'display: inline; width: 16px; height: 12px'; + drawing.innerHTML = ''; + document.body.append(span, image, drawing); + + const shape = drawing.firstElementChild; + + expect(await domql.query('{ detached = detached.layoutSize, hidden = hidden.layoutSize, span = span.layoutSize, image = image.layoutSize, shape = shape.layoutSize }', { detached: document.createElement('div'), hidden, span, image, shape }).evaluateAsync()).toEqual({ + detached: null, hidden: null, span: null, image: { inline: 16, block: 12 }, shape: { inline: 40, block: 10 }, + }); + await afterLayout(); + }); + + it('is null for a box of no size, which a resize observer tells from no box by no report, so a watch follows a box as it stops and starts being laid out', async () => { + const sentinel = add('position: absolute'); + const snapshots = []; + const watch = domql.query('sentinel.layoutSize', { sentinel }).watch({ schedule: 'immediate' }); + + watch.subscribe('change', (sender, args) => snapshots.push(args.value)); + await watch.readyAsync(); + await afterLayout(); + sentinel.style.display = 'none'; + await afterLayout(); + sentinel.style.display = ''; + await afterLayout(); + sentinel.style.width = '30px'; + sentinel.style.height = '10px'; + await afterLayout(); + sentinel.remove(); + await afterLayout(); + watch.dispose(); + + expect(snapshots).toEqual([null, { inline: 30, block: 10 }, null]); + expect(await domql.query('sentinel.layoutSize', { sentinel }).evaluateAsync()).toBeNull(); + await afterLayout(); + }); + + it('is watched from the size laid out first, under a transform too, and follows each resize, with no partial observation to accept', async () => { + const box = add('width: 200px; height: 50px; transform: scale(0.5)'); + const snapshots = []; + const watch = domql.query('box.layoutSize', { box }).watch({ schedule: 'immediate' }); + + watch.subscribe('change', (sender, args) => snapshots.push(args.value)); + await watch.readyAsync(); + + // Ready settles inside the resize observer's report, so the box is resized once the browser has delivered it. + await afterLayout(); + box.style.width = '240px'; + await afterLayout(); + box.style.transform = 'scale(2)'; + await afterLayout(); + watch.dispose(); + + expect(snapshots).toEqual([{ inline: 200, block: 50 }, { inline: 240, block: 50 }]); + }); + }); +}); diff --git a/tests/dom/ModuleManifest.test.js b/tests/dom/ModuleManifest.test.js new file mode 100644 index 0000000..8fe9c57 --- /dev/null +++ b/tests/dom/ModuleManifest.test.js @@ -0,0 +1,32 @@ +import { readFile } from 'node:fs/promises'; +import { describe, it, expect, vi } from 'vitest'; +import { nexo } from '@formaui-net/nexo'; +import { moduleManifestPath, moduleManifestText } from '../../scripts/module-manifest.mjs'; +import { ModuleManifest } from '#domql/dom/ModuleManifest.mjs'; + +describe('ModuleManifest', () => { + it('is the manifest Nexo makes of DOMQL\'s own module, as npm run manifest writes it', async () => { + expect(await readFile(moduleManifestPath, 'utf8'), 'The manifest of DOMQL\'s own module is not current: run npm run manifest from the repository root').toBe(moduleManifestText()); + }); + + it('records DOMQL\'s module alone, registered first, as the Nexo DOMQL runs on made it', () => { + expect(ModuleManifest).toMatchObject({ implementation: nexo.info.versions.implementation, scripts: [] }); + expect(ModuleManifest.modules).toEqual([{ name: 'Domql', digest: expect.any(String), after: [] }]); + }); + + it('is the one DOMQL creates its module and its registry under, each finding the module it records', async () => { + vi.resetModules(); + + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const entryOf = vi.spyOn(Manifest, 'entryOf'); + + try { + await import('#domql/domql.js'); + + expect(entryOf.mock.calls.map(([manifest, name]) => [manifest, name])).toEqual([[ModuleManifest, 'Domql'], [ModuleManifest, 'Domql']]); + expect(entryOf.mock.results.map(({ value }) => value)).toEqual([ModuleManifest.modules[0], ModuleManifest.modules[0]]); + } finally { + entryOf.mockRestore(); + } + }); +}); diff --git a/tests/dom/QueryEvaluator.test.js b/tests/dom/QueryEvaluator.test.js index 24aebd9..eba0a16 100644 --- a/tests/dom/QueryEvaluator.test.js +++ b/tests/dom/QueryEvaluator.test.js @@ -623,6 +623,30 @@ describe('QueryEvaluator', () => { expect(read('e.autofilled', { e: document.getElementById('field') })).toBe(false); }); + + it('follows a field being filled and emptied where the style of the page starts an animation on it as it is, as a rule for :autofill does', async () => { + document.body.innerHTML = ''; + const field = document.getElementById('field'); + let isFilled = false; + const matches = field.matches.bind(field); + + field.matches = selector => (selector === ':autofill' || selector === ':-webkit-autofill' ? isFilled : matches(selector)); + + const watch = domql.query('e.autofilled', { e: field }).watch({ schedule: 'immediate', acceptPartialObservation: true }); + const values = []; + + watch.subscribe('change', (sender, args) => values.push(args.value)); + await watch.readyAsync(); + isFilled = true; + field.dispatchEvent(new window.Event('animationstart')); + await new Promise(resolve => setTimeout(resolve)); + isFilled = false; + field.dispatchEvent(new window.Event('animationcancel')); + await new Promise(resolve => setTimeout(resolve)); + watch.dispose(); + + expect(values).toEqual([false, true, false]); + }); }); describe('size limits and files', () => { diff --git a/tests/language/LanguageResolver.test.js b/tests/language/LanguageResolver.test.js index f88eeec..115c231 100644 --- a/tests/language/LanguageResolver.test.js +++ b/tests/language/LanguageResolver.test.js @@ -511,8 +511,15 @@ describe('LanguageResolver', () => { expect(error.message).toContain("'Element.rect' (which misses a move its own size"); }); + it('refuses a watch of the size a box is drawn at unless it accepts partial observation, since a transform changes it without resizing the box', () => { + const error = failure('DOMQL3003', 'panel.size', { panel }, { watch: true }); + + expect(error.message).toContain("'Element.size' (which misses a transform or an animation, its own or an ancestor's"); + expect(() => resolve('panel.size', { panel }, { watch: true, acceptPartialObservation: true })).not.toThrow(); + }); + it('lets a watch follow what is observable', () => { - expect(() => resolve('panel.size', { panel }, { watch: true })).not.toThrow(); + expect(() => resolve('panel.layoutSize', { panel }, { watch: true })).not.toThrow(); }); it('lists the declarations a request uses', () => { diff --git a/tests/snapshots/SnapshotPatcher.test.js b/tests/snapshots/SnapshotPatcher.test.js index be2e12f..f0ae51a 100644 --- a/tests/snapshots/SnapshotPatcher.test.js +++ b/tests/snapshots/SnapshotPatcher.test.js @@ -1,3 +1,6 @@ +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, it, expect } from 'vitest'; import { nexo } from '@formaui-net/nexo'; import { SnapshotPatcher } from '#domql/snapshots/SnapshotPatcher.mjs'; @@ -363,4 +366,17 @@ describe('SnapshotPatcher', () => { expect(() => SnapshotPatcher.applyInPlace(thaw({ rows: [{ k: 'a' }] }), operations)).toThrow(TypeError); }); }); + + describe('the conformance corpus', () => { + // Each case a previous result, a change set and the result they give, which DOMQL.NET's applier passes too. + const cases = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '..', '_conformance', 'change-sets.json'), 'utf8')); + + it.each(cases.map(entry => [entry.name, entry]))('%s', (name, { previous, changes, result }) => { + const target = structuredClone(previous); + + SnapshotPatcher.applyInPlace(target, changes); + + expect(target).toEqual(result); + }); + }); }); diff --git a/tests/vitest.engines.config.js b/tests/vitest.engines.config.js index 9e12bbe..7efe82a 100644 --- a/tests/vitest.engines.config.js +++ b/tests/vitest.engines.config.js @@ -4,13 +4,13 @@ import { defineConfig } from 'vitest/config'; const resolved = path => decodeURIComponent(new URL(path, import.meta.url).pathname); // The browser tests of what browser engines decide differently, run in Chromium, Firefox and WebKit: where a focus event inside a shadow root reaches and whether -// removing the focused element fires one, and where a box's scroll origin lies. `npm run test:engines` runs them. +// removing the focused element fires one, where a box's scroll origin lies, and what a resize observer first reports of a box, the size layout gives it. `npm run test:engines` runs them. export default defineConfig({ resolve: { alias: [{ find: '#domql/', replacement: resolved('../src/') }], }, test: { - include: ['dom/FocusChain.browser.js', 'dom/ReversedScrolling.browser.js'], + include: ['dom/FocusChain.browser.js', 'dom/ReversedScrolling.browser.js', 'dom/LayoutSize.browser.js'], browser: { enabled: true, provider: 'playwright',