@gramlot/gramlot 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/gramlot.js +1344 -875
  2. package/dist/gramlot.min.js +22 -23
  3. package/package.json +2 -2
  4. package/src/binding/ask-dialog.js +46 -23
  5. package/src/binding/inline.js +7 -5
  6. package/src/binding/installation.js +14 -5
  7. package/src/binding/logic.js +10 -5
  8. package/src/binding/pointer.js +6 -10
  9. package/src/binding/providers.js +105 -82
  10. package/src/binding/remote.js +60 -26
  11. package/src/binding/router.js +2 -4
  12. package/src/binding/rpc-resolver.js +102 -53
  13. package/src/binding/runtime.js +58 -17
  14. package/src/bootstrap.d.ts +8 -1
  15. package/src/bootstrap.js +28 -11
  16. package/src/builder/binding.json +13 -1
  17. package/src/builder/gramlot-builder.d.ts +5 -2
  18. package/src/builder/gramlot-builder.js +15 -7
  19. package/src/builder/name-syntax.d.ts +37 -0
  20. package/src/builder/name-syntax.js +54 -0
  21. package/src/builder/source.js +169 -13
  22. package/src/components/border-container.js +17 -10
  23. package/src/components/inputs.js +22 -3
  24. package/src/components/selected-container.js +19 -18
  25. package/src/dom.d.ts +3 -0
  26. package/src/format.js +3 -10
  27. package/src/frame-messages.js +2 -1
  28. package/src/gramlot.d.ts +12 -4
  29. package/src/gramlot.js +25 -10
  30. package/src/handlers/rpc-handler.d.ts +25 -12
  31. package/src/handlers/rpc-handler.js +57 -13
  32. package/src/handlers/source-handler.d.ts +13 -3
  33. package/src/handlers/source-handler.js +23 -18
  34. package/src/handlers/subscriptions-handler.js +24 -0
  35. package/src/http-transport.d.ts +11 -2
  36. package/src/http-transport.js +31 -11
  37. package/src/index.d.ts +4 -2
  38. package/src/index.js +6 -2
  39. package/src/random-id.js +14 -0
  40. package/src/renderer/attributes.js +1 -1
  41. package/src/renderer/gramlot-html-renderer.js +14 -5
  42. package/src/renderer/gramlot-renderer.js +3 -3
  43. package/src/server/conformance.d.ts +4 -2
  44. package/src/server/conformance.js +70 -9
  45. package/src/server/files.js +40 -0
  46. package/src/server/gramlot-file-server.d.ts +2 -0
  47. package/src/server/gramlot-file-server.js +18 -18
  48. package/src/server/gramlot-server.d.ts +26 -7
  49. package/src/server/gramlot-server.js +153 -33
  50. package/src/server/index-page.js +1 -1
  51. package/src/server/index.d.ts +3 -1
  52. package/src/server/index.js +2 -1
  53. package/src/server/page-base.js +55 -20
  54. package/src/server/page.d.ts +37 -15
  55. package/src/server/page.js +7 -0
  56. package/src/server/resources.d.ts +2 -0
  57. package/src/server-adapter.d.ts +17 -0
  58. package/src/server-adapter.js +23 -0
  59. package/src/view/button.js +5 -5
  60. package/src/view/controls.js +5 -6
  61. package/src/view/html.js +7 -1
  62. package/themes/gramlot-base/README.md +5 -4
  63. package/themes/gramlot-base/theme.css +2 -0
  64. package/themes/gramlot-compact/README.md +5 -12
  65. package/themes/joanna/README.md +2 -3
  66. package/themes/mimi/README.md +2 -3
@@ -1,76 +1,110 @@
1
1
  import {toTytx} from '@genrojs/tytx';
2
+ import {TriggerTimers} from './providers.js';
2
3
 
3
4
  /**
4
5
  * The `remote` attribute of a Source node (GC-095 §105): the content of the element is the fragment of a
5
6
  * `@source` method, requested through `gramlot.src.remoteSource` when the node starts and again when a
6
- * `^` pointer of `remote` or of a `remote_<k>` parameter changes. Owned by the node's NodeBinding; the
7
- * request is cancelled with it by `remoteSource` itself (P24), and the answer of a superseded request is
8
- * dropped there (latest wins).
7
+ * `^` pointer of `remote` or of a `remote_<k>` parameter changes. Owned by the node's NodeBinding. The
8
+ * requests follow the rule of `node.requests` (NodeRequests): one in flight, its fragment always mounted, the
9
+ * first change during the flight waiting with its parameters; the removal of the node cancels them (P24).
9
10
  *
10
- * The control attributes: `_cachedRemote` (no call when name and parameters equal the last mount's), `_if`
11
- * (inline, false → no call, and `_else` runs when present), `_onRemote` (inline, after the fragment is
12
- * mounted). The inline code has the parameters as locals and `this` = the node.
11
+ * The control attributes: `_cachedRemote` (no call when name and parameters equal those of the request in
12
+ * flight, or of the fragment mounted last when none is in flight), `_if` (inline, false → no call, and `_else`
13
+ * runs when present; a readiness condition that never cancels a request), `_onCalling` (inline, before the
14
+ * call; `false` makes no call), `_onRemote` (inline, after the fragment is mounted), `_delay` (ms of debounce
15
+ * of a Data change), `_timing` (seconds between two calls) and `_userChanges` (only the changes of level
16
+ * `node` call). The inline code has the parameters as locals and `this` = the node.
13
17
  */
14
18
  export class RemoteBinding {
15
19
  #binding;
16
- // The name and TYTX parameters of the last mounted call, captured before sending it.
20
+ #timers;
21
+ // The name and TYTX parameters of the fragment mounted last on the node, whoever requested it.
17
22
  #lastName = null;
18
23
  #lastParams = null;
19
24
 
20
25
  constructor(binding) {
21
26
  this.#binding = binding;
27
+ this.#timers = new TriggerTimers(binding);
22
28
  }
23
29
 
24
30
  get binding() { return this.#binding; }
25
31
  get node() { return this.binding.node; }
26
32
  get closed() { return this.binding.closed; }
27
33
 
34
+ /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
35
+ register() {
36
+ this.#timers.startTiming(this.#control('_timing'), () => this.update());
37
+ }
38
+
39
+ /**
40
+ * A Data change of `remote` or of a `remote_<k>` parameter: `_userChanges` lets only the level `node`
41
+ * through; `_delay` debounces, the last change wins and the parameters are read when the call starts.
42
+ */
43
+ receive(change) {
44
+ if (this.#control('_userChanges') && change.level !== 'node') return;
45
+ const delay = this.#control('_delay');
46
+ if (delay > 0) this.#timers.debounce(delay, () => this.update());
47
+ else this.update();
48
+ }
49
+
28
50
  /**
29
51
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
30
- * on a closed node, without a name, or when `_if` or `_cachedRemote` stop the call; a false `_if`
31
- * also cancels the request in flight, so its fragment is not mounted after `_else`. A cache hit
32
- * cancels a pending request too, keeping the mounted fragment. A failure of the request rejects
33
- * with an error naming the node, its cause attached.
52
+ * on a closed node, or when `_if`, `_cachedRemote` or `_onCalling` stop the call. A call made while a
53
+ * request is in flight waits, or does nothing when another call already waits (NodeRequests). A failure
54
+ * of the request, a method name outside the syntax included, rejects with an error naming the node, its
55
+ * cause attached.
34
56
  */
35
57
  async update() {
36
58
  if (this.closed || !this.binding.hasStamp('start')) return;
37
59
  const node = this.node;
38
- const [, attrs] = node.builder.runtimeValues(node);
60
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
39
61
  const name = attrs.remote;
40
- if (!name) return;
41
62
  const params = {};
42
63
  for (const [key, value] of Object.entries(attrs)) {
43
64
  if (key.startsWith('remote_')) params[key.slice('remote_'.length)] = value;
44
65
  }
45
66
  const condition = node.getAttr('_if');
46
67
  if (condition && !this.#inline('_if', condition, `return (${condition})`, params)) {
47
- this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
48
68
  const otherwise = node.getAttr('_else');
49
69
  if (otherwise) this.#inline('_else', otherwise, otherwise, params);
50
70
  return;
51
71
  }
52
72
  let mounted;
53
- let text;
54
73
  try {
55
- text = toTytx(params);
56
- if (attrs._cachedRemote && name === this.#lastName && text === this.#lastParams) {
57
- // Keeping the mounted fragment also supersedes any different request still in flight.
58
- this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
59
- return;
60
- }
74
+ const text = toTytx(params);
75
+ if (attrs._cachedRemote && this.#cached(name, text)) return;
76
+ const onCalling = node.getAttr('_onCalling');
77
+ if (!node.requests.calling(onCalling ? () => this.#inline('_onCalling', onCalling, onCalling, params) : null)) return;
61
78
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
62
79
  } catch (error) {
63
80
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, {cause: error});
64
81
  }
65
- // Only a mounted fragment is the last call `_cachedRemote` compares: a failed request is retried.
66
- if (mounted) {
67
- this.#lastName = name;
68
- this.#lastParams = text;
69
- }
70
82
  const onRemote = node.getAttr('_onRemote');
71
83
  if (mounted && onRemote) this.#inline('_onRemote', onRemote, onRemote, params);
72
84
  }
73
85
 
86
+ /**
87
+ * Record the fragment `remoteSource` mounted on the node, with its method and the TYTX of its parameters:
88
+ * `_cachedRemote` compares with it. A fragment requested from code replaces the record too.
89
+ */
90
+ fragmentMounted(method, text) {
91
+ this.#lastName = method;
92
+ this.#lastParams = text;
93
+ }
94
+
95
+ /** Whether `name` and `text` equal the request in flight, or the fragment mounted last when none is in flight. */
96
+ #cached(name, text) {
97
+ const inflight = this.node.requests.inflight;
98
+ if (inflight) return inflight.method === name && toTytx(inflight.params) === text;
99
+ return name === this.#lastName && text === this.#lastParams;
100
+ }
101
+
102
+ /** The current value of a control attribute: a pointer is read from Data. */
103
+ #control(name) {
104
+ const [, attrs] = this.node.rootBuilder.runtimeValues(this.node);
105
+ return attrs[name] ?? null;
106
+ }
107
+
74
108
  #inline(attr, code, source, params) {
75
109
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
76
110
  }
@@ -2,14 +2,12 @@
2
2
  * Data routing of one Gramlot page (source plan §4.5).
3
3
  *
4
4
  * The router receives every event of Builder's Data wrapper through the one
5
- * subscription of BindingRuntime, strips the first segment `_root_` and
5
+ * subscription of BindingRuntime, strips the first segment `_root_` (Builder's `DATA_ROOT`) and
6
6
  * delivers the event to the registrations its path reaches, through a trie
7
7
  * by segment: the work of one event does not depend on the unconnected
8
8
  * branches.
9
9
  */
10
-
11
- // Builder's content node under the Data wrapper (`_dataroot` → `_root_`).
12
- const DATA_ROOT = '_root_';
10
+ import {DATA_ROOT} from '@genrojs/builders';
13
11
 
14
12
  /** One trie level: the registrations of one path and the next segments. */
15
13
  class RouteNode {
@@ -2,71 +2,98 @@ import {BagResolver} from '@genrojs/bag';
2
2
 
3
3
  /**
4
4
  * The resolver a `dataRemote` installs on its Data node: the value is the answer of the endpoint
5
- * `method`, called through `gramlot.rpc.call('data', method, params)` when the node is read and its
6
- * cache has expired. `cacheTime` in seconds, as legacy: below 0 once, 0 at every read, above 0 again
7
- * after that many seconds.
5
+ * `method` when the node is read and its cache has expired. `cacheTime` in seconds, as legacy: below 0
6
+ * once, 0 at every read, above 0 again after that many seconds.
8
7
  *
9
- * A read never waits: it returns the node's current value (null before the first load) and, when the
10
- * cache has expired, starts the load. A read made while a load is in flight starts no other load. The
11
- * loaded value is written on the node with its Data event, so every `^` consumer of the path is
8
+ * With `sync` (the `sync` attribute, default true, when the transport supports it) a read waits, as in the
9
+ * legacy: the expired read calls `gramlot.rpc.callSync('data', method, params)` and returns its value through
10
+ * `BagResolver.resolve`, which stores it on the node, without the Data event, and records the cache time. The
11
+ * page is blocked while it waits. `_onCalling` false makes no call and returns the current value. A failed
12
+ * call throws to the reader through `onError`, naming the node.
13
+ *
14
+ * Without `sync`, or on a transport without synchronous calls (the serverless Worker), a read never waits:
15
+ * it returns the node's current value (null before the first load) and, when the cache has expired, starts
16
+ * the load through `gramlot.rpc.call`. A read made while a load is in flight or waiting starts no other load.
17
+ * The loaded value is written on the node with its Data event, so every `^` consumer of the path is
12
18
  * projected again; with `cacheTime: 0` it is written without the event, as legacy: a value per
13
19
  * explicit read, never a source for `^` consumers, whose projection would read and load again.
14
- * A failed load writes nothing: `loading` rejects with its error and `onError` receives it; an aborted
15
- * load writes nothing, even when its answer had already arrived. `abort()` cancels the pending load.
20
+ *
21
+ * Both paths record what BagResolver `resolve` records: the cache time and the fingerprint of the parameters. A
22
+ * `sync` read that follows a load, however it was made, finds the cache of that load while the parameters are the
23
+ * same and the cache has not expired, and sends no call.
24
+ *
25
+ * A load is a call of the `dataRemote` node and follows the rule of `node.requests` (NodeRequests): one
26
+ * request in flight for the node, its answer always written, even when this resolver was replaced or removed
27
+ * meanwhile; the first load asked during the flight waits and is sent at the answer. `onCalling` (the
28
+ * `_onCalling` of the node) runs before each load and a result `false` makes no load. A failed load writes
29
+ * nothing: `loading` rejects with its error and `onError` receives it. A load aborted by the removal of the
30
+ * node writes nothing, even when its answer had already arrived; a load ignored by `cancel()` writes nothing.
16
31
  */
17
32
  export class RpcResolver extends BagResolver {
18
33
  static classKwargs = {...BagResolver.classKwargs, asBag: false};
19
- static internalParams = new Set([...BagResolver.internalParams, 'gramlot', 'method', 'params', 'onError']);
34
+ static internalParams = new Set([...BagResolver.internalParams, 'binding', 'method', 'params', 'onCalling', 'onError',
35
+ 'sync']);
20
36
 
21
- constructor({gramlot, method, params, cacheTime, onError}) {
37
+ constructor({binding, method, params, cacheTime, onCalling = null, onError, sync = false}) {
22
38
  // null: resolve once, as a negative cacheTime.
23
39
  super({cacheTime: cacheTime ?? -1});
24
- this.gramlot = gramlot;
40
+ // The NodeBinding of the `dataRemote` node.
41
+ this.binding = binding;
42
+ // A read waits for the answer of a synchronous call.
43
+ this.sync = sync;
25
44
  this.method = method;
26
45
  this.params = params;
46
+ this.onCalling = onCalling;
27
47
  // Receives the error of a failed load, never an abort.
28
48
  this.onError = onError;
29
- // The AbortController and the promise of the pending load, or null.
30
- this.controller = null;
49
+ // The promise of the load in flight or waiting, or null.
31
50
  this.loading = null;
32
51
  // A load has written its value; the loaded value is being written.
33
52
  this.loaded = false;
34
53
  this.writing = false;
35
54
  }
36
55
 
37
- /** The current value; a non-static read starts the load when the cache has expired. */
38
- resolve({static: isStatic = false} = {}) {
39
- if (!isStatic && !this.loading && !this.writing && this.expired) this.refresh();
40
- return this.cachedValue;
56
+ /**
57
+ * The current value. With `sync` an expired read calls the endpoint and returns its value (BagResolver
58
+ * `resolve`, then `load`); without, it starts the load and returns the current value. A static read, or
59
+ * a read during a load or its write, returns the current value.
60
+ */
61
+ resolve(options = {}) {
62
+ const {static: isStatic = false} = options;
63
+ if (isStatic || this.loading || this.writing) return this.cachedValue;
64
+ if (!this.sync) {
65
+ if (this.expired) this.refresh();
66
+ return this.cachedValue;
67
+ }
68
+ if (this.expired && !this.binding.node.requests.calling(this.onCalling)) return this.cachedValue;
69
+ return super.resolve(options);
41
70
  }
42
71
 
43
- /** Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns `loading`. */
72
+ /** The synchronous call of a `sync` read: BagResolver `resolve` stores the value it returns. */
73
+ load() {
74
+ let value;
75
+ try {
76
+ value = this.binding.callSync('data', this.method, this.params);
77
+ } catch (error) {
78
+ this.onError(error);
79
+ }
80
+ this.loaded = true;
81
+ return value;
82
+ }
83
+
84
+ /**
85
+ * Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns
86
+ * `loading`, which settles with the written value, or undefined when nothing was written. A false
87
+ * `_onCalling` starts no load and returns null.
88
+ */
44
89
  refresh() {
90
+ const requests = this.binding.node.requests;
91
+ if (!requests.calling(this.onCalling)) return null;
92
+ const loading = requests.submit(this.method, this.params, request => this.#load(request));
45
93
  const settle = () => {
46
- if (this.loading !== loading) return;
47
- this.controller = null;
48
- this.loading = null;
94
+ if (this.loading === loading) this.loading = null;
49
95
  };
50
- const load = this.load();
51
- const {signal} = this.controller;
52
- const loading = load.then(value => {
53
- settle();
54
- // Aborted after the answer arrived: the answer belongs to a removed or replaced resolver.
55
- if (signal.aborted) throw signal.reason;
56
- this._lastUpdate = Date.now();
57
- this.loaded = true;
58
- this.writing = true;
59
- try {
60
- if (this._node) this._node.setValue(value, this.cacheTime !== 0);
61
- else this.cachedValue = value;
62
- } finally {
63
- this.writing = false;
64
- }
65
- return value;
66
- }, error => {
67
- settle();
68
- throw error;
69
- });
96
+ loading.then(settle, settle);
70
97
  this.loading = loading;
71
98
  // A load nobody awaits: its failure reaches `onError`, an abort is not a failure.
72
99
  loading.catch(error => {
@@ -75,19 +102,41 @@ export class RpcResolver extends BagResolver {
75
102
  return loading;
76
103
  }
77
104
 
78
- /** The call of the endpoint with the params given at construction; the read kwargs are not sent. */
79
- load() {
80
- const controller = new AbortController();
81
- const aborted = new Promise((_, reject) => {
82
- controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {once: true});
83
- });
84
- const call = this.gramlot.rpc.call('data', this.method, this.params, {signal: controller.signal});
85
- this.controller = controller;
86
- return Promise.race([call, aborted]);
105
+ /**
106
+ * The fingerprint of the parameters of a read without call kwargs, as `BagResolver.resolve` computes it:
107
+ * the kwargs of the resolver and the attributes of its node that are not internal.
108
+ */
109
+ #fingerprint() {
110
+ const kwargs = {...this._kw};
111
+ for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
112
+ if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
113
+ }
114
+ return this._computeEffectiveFingerprint(kwargs);
87
115
  }
88
116
 
89
- /** Cancel the pending load, if any. */
90
- abort() {
91
- this.controller?.abort();
117
+ /** The asynchronous call of the endpoint with the params given at construction; the read kwargs are not sent. */
118
+ async #load(request) {
119
+ const binding = this.binding;
120
+ // A waiting load of a node that left the Source sends nothing.
121
+ if (binding.closed) return undefined;
122
+ // The parameters of this load, as `resolve` takes them before a load: the value answers these.
123
+ const fingerprint = this.#fingerprint();
124
+ const value = await binding.call('data', request);
125
+ if (binding.closed || request.ignored) return undefined;
126
+ // The cache time and the fingerprint of the parameters of BagResolver: no public member records a load made
127
+ // outside `resolve`. A `sync` read loads through `resolve`, which records both and does not write them here;
128
+ // this asynchronous load is a debt of the async-resolvers plan. Without the fingerprint, the first explicit
129
+ // read after this load finds another one, loads again and sends a call the cache should have answered.
130
+ this._lastUpdate = Date.now();
131
+ this._lastEffectiveFingerprint = fingerprint;
132
+ this.loaded = true;
133
+ this.writing = true;
134
+ try {
135
+ if (this.node) this.node.setValue(value, this.cacheTime !== 0);
136
+ else this.cachedValue = value;
137
+ } finally {
138
+ this.writing = false;
139
+ }
140
+ return value;
92
141
  }
93
142
  }
@@ -4,6 +4,8 @@ import {DataInstaller} from './installation.js';
4
4
  import {ControllerProvider, FormulaProvider, RemoteProvider, RpcProvider} from './providers.js';
5
5
  import {InlineCompiler} from './inline.js';
6
6
  import {RemoteBinding} from './remote.js';
7
+ import {AskDialog} from './ask-dialog.js';
8
+ import {randomId} from '../random-id.js';
7
9
  import {pointerDependencies} from '@genrojs/builders';
8
10
 
9
11
 
@@ -32,18 +34,23 @@ export class BindingRuntime {
32
34
  #router;
33
35
  #installer;
34
36
  #inlineCompiler;
35
- #subscription = `gramlot-data-${Array.from(crypto.getRandomValues(new Uint8Array(16)),
36
- byte => byte.toString(16).padStart(2, '0')).join('')}`;
37
+ #askDialog;
38
+ #subscriptions;
39
+ #subscription = `gramlot-data-${randomId()}`;
37
40
  #disposed = false;
38
41
 
39
- constructor(gramlot) {
42
+ constructor(gramlot, {subscriptions}) {
40
43
  this.#gramlot = gramlot;
44
+ this.#subscriptions = subscriptions;
41
45
  this.#router = new DataRouter(this);
42
46
  this.#installer = new DataInstaller(this);
43
47
  this.#inlineCompiler = new InlineCompiler(this);
48
+ this.#askDialog = new AskDialog(this);
44
49
  }
45
50
 
46
51
  get gramlot() { return this.#gramlot; }
52
+ /** The page topics and Source self-topics: the private `_subscriptions` of the Gramlot instance, given at construction. */
53
+ get subscriptions() { return this.#subscriptions; }
47
54
  get builder() { return this.gramlot.src.builder; }
48
55
  get renderer() { return this.gramlot.src.renderer; }
49
56
  get logicRegistry() { return this.gramlot.src.logicRegistry; }
@@ -58,6 +65,8 @@ export class BindingRuntime {
58
65
  get installer() { return this.#installer; }
59
66
  /** The compiler of the page's inline code (§4.10). */
60
67
  get inlineCompiler() { return this.#inlineCompiler; }
68
+ /** The ask dialogs of the page (`_ask` of a provider, `ask` of a button). */
69
+ get askDialog() { return this.#askDialog; }
61
70
  /** `node_id → node` of the Source nodes with an open NodeBinding (R06). */
62
71
  get nodeIds() { return this.#nodeIds; }
63
72
 
@@ -344,6 +353,8 @@ export class NodeBinding {
344
353
  #remote = null;
345
354
  // The registrations of `remote` and of the `remote_<k>` parameters: their changes request the fragment again.
346
355
  #remoteRegistrations = new Set();
356
+ // The registrations of the `_timing` of a `remote` node: their changes restart its timer.
357
+ #remoteTimingRegistrations = new Set();
347
358
  // The clicks of a button, counted for its whole semantic life: a rebuild keeps them (P9, S12).
348
359
  #clickCount = 0;
349
360
  // The registration of the node's own variable datapath, read in the parent's context.
@@ -387,7 +398,8 @@ export class NodeBinding {
387
398
  * pointer on a null path (Q7) is not registered. The `datapath` pointer is resolved in the
388
399
  * parent's context. A `dataSetter` registers nothing; a `dataFormula` or `dataController`
389
400
  * registers its `datapath` here and the rest through its Provider, created once (§5.1 step 4).
390
- * A node whose `remote` is a string gets its RemoteBinding, created once.
401
+ * A node whose `remote` is a string gets its RemoteBinding, created once, whose `_timing` starts
402
+ * again from its current value.
391
403
  */
392
404
  registerPointers() {
393
405
  // Data elements have semantic lifetime but no rendered item to register their reference.
@@ -400,6 +412,7 @@ export class NodeBinding {
400
412
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
401
413
  if (!dataElement && typeof node.getAttr('remote') === 'string') this.#remote ??= new RemoteBinding(this);
402
414
  const remoteDependencies = new Set();
415
+ const timingDependencies = this.remote ? pointerDependencies(node, node.getAttr('_timing')) : new Set();
403
416
  if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
404
417
  if (name.startsWith('remote_')) for (const dependency of pointerDependencies(node, raw)) remoteDependencies.add(dependency);
405
418
  }
@@ -413,9 +426,11 @@ export class NodeBinding {
413
426
  this.#registrations.push(registration);
414
427
  if (name === 'datapath') this.#datapathRegistrations.add(registration);
415
428
  if (this.remote && (name === 'remote' || name.startsWith('remote_') || remoteDependencies.has(name))) this.#remoteRegistrations.add(registration);
429
+ if (this.remote && (name === '_timing' || timingDependencies.has(name))) this.#remoteTimingRegistrations.add(registration);
416
430
  }
417
431
  if (!dataElement) {
418
432
  this.#registerTopics();
433
+ this.remote?.register();
419
434
  return;
420
435
  }
421
436
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
@@ -425,27 +440,21 @@ export class NodeBinding {
425
440
  /** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
426
441
  #registerTopics() {
427
442
  const node = this.node;
428
- const subscriptions = this.runtime.gramlot._subscriptions;
429
- for (const [name, handler] of Object.entries(node.getAttr())) {
430
- const prefix = name.startsWith('selfsubscribe_') ? 'selfsubscribe_' : name.startsWith('subscribe_') ? 'subscribe_' : null;
431
- if (!prefix) continue;
443
+ this.#registrations.push(...this.runtime.subscriptions.subscribeNode(node, (name, handler) => {
432
444
  if (typeof handler !== 'string' || !handler) throw new TypeError(`${name} requires a handler`);
433
- const topic = prefix === 'selfsubscribe_'
434
- ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
435
- const handle = subscriptions.subscribe(topic, payload => {
445
+ return payload => {
436
446
  if (this.closed) return;
437
447
  if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
438
448
  const {group, method} = this.runtime.logicRegistry.resolve(handler, node);
439
449
  return method.call(group, node, payload);
440
450
  }
441
- const [, attrs] = node.builder.runtimeValues(node);
451
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
442
452
  const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
443
453
  !key.startsWith('subscribe_') && !key.startsWith('selfsubscribe_')));
444
454
  const values = {...this.runtime.renderer.references.resolveArguments(authored), p_0: payload};
445
455
  return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
446
- });
447
- this.#registrations.push({close: () => subscriptions.unsubscribe(handle)});
448
- }
456
+ };
457
+ }));
449
458
  }
450
459
 
451
460
  /** Close the registrations and make them again from the current pointers, the provider's included (D1). */
@@ -456,14 +465,16 @@ export class NodeBinding {
456
465
 
457
466
  /**
458
467
  * Router recipient: the node's datapath rebinds its branch; any other registration projects the node,
459
- * after a registration of `remote` or of a `remote_<k>` parameter requested the fragment again.
468
+ * after a registration of `remote` or of a `remote_<k>` parameter reached the RemoteBinding, and a
469
+ * registration of its `_timing` restarted the timer.
460
470
  */
461
471
  receive(change) {
462
472
  if (this.#datapathRegistrations.has(change.registration)) {
463
473
  this.runtime.rebindBranch(this.node);
464
474
  return;
465
475
  }
466
- if (this.#remoteRegistrations.has(change.registration)) this.remote.update();
476
+ if (this.#remoteRegistrations.has(change.registration)) this.remote.receive(change);
477
+ if (this.#remoteTimingRegistrations.has(change.registration)) this.remote.register();
467
478
  this.runtime.renderer.project(this.node, change);
468
479
  }
469
480
 
@@ -477,6 +488,35 @@ export class NodeBinding {
477
488
  };
478
489
  }
479
490
 
491
+ /**
492
+ * Send `request`, the request of this node in flight (NodeRequests), through `gramlot.rpc.call` as
493
+ * `contentType`; resolves with the value. The close of the node aborts it until the answer arrives, also
494
+ * when the answer arrived and was not yet received here: the call then rejects with the abort reason.
495
+ * Used by `dataRpc`, `dataRemote` and `remoteSource`.
496
+ */
497
+ async call(contentType, request) {
498
+ const {controller} = request;
499
+ const release = this.track(() => controller.abort());
500
+ try {
501
+ const value = await this.runtime.gramlot.rpc.call(contentType, request.method, request.params,
502
+ {signal: controller.signal});
503
+ if (controller.signal.aborted) throw controller.signal.reason;
504
+ return value;
505
+ } finally {
506
+ release();
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Send the synchronous call of `method` with `params` as `contentType` through `gramlot.rpc.callSync` and
512
+ * return its value: the page waits. It follows the rule of the node's requests (`submitSync`): no request of
513
+ * the node in flight, a method within the name syntax. Used by a `dataRemote` with `sync`.
514
+ */
515
+ callSync(contentType, method, params) {
516
+ return this.node.requests.submitSync(method,
517
+ () => this.runtime.gramlot.rpc.callSync(contentType, method, params));
518
+ }
519
+
480
520
  /** Close the registrations, then run the disposers in reverse order and collect their errors. */
481
521
  close() {
482
522
  if (this.closed) return;
@@ -494,5 +534,6 @@ export class NodeBinding {
494
534
  for (const registration of this.#registrations.splice(0)) registration.close();
495
535
  this.#datapathRegistrations.clear();
496
536
  this.#remoteRegistrations.clear();
537
+ this.#remoteTimingRegistrations.clear();
497
538
  }
498
539
  }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type {DomDocument} from './dom.d.ts';
7
7
  import type {Gramlot, GramlotOptions} from './gramlot.js';
8
+ import type {ServerAdapter} from './server-adapter.js';
8
9
 
9
10
  /** The JavaScript modules and CSS links of a page, in load order and with the mount prefix. */
10
11
  export interface PageResources {
@@ -14,6 +15,8 @@ export interface PageResources {
14
15
  collections?: string[];
15
16
  /** JavaScript module URLs, each with its Logic group (null for the page logic). */
16
17
  js: {url: string; group: string | null}[];
18
+ /** The module whose default export is the ServerAdapter class of the page, when the server names one. */
19
+ serverAdapter?: string;
17
20
  }
18
21
 
19
22
  /** The configuration written by the server into the bootstrap HTML. */
@@ -37,6 +40,8 @@ export class PageBootstrap {
37
40
  resources: PageResources;
38
41
  /** The document of the page. */
39
42
  document: DomDocument;
43
+ /** The server adapter of the page: the HTTP `ServerAdapter` of the core, replaced by `run` when the server names another. */
44
+ serverAdapter: ServerAdapter;
40
45
  /** Create the bootstrap of one page. */
41
46
  constructor(options: PageBootstrapOptions);
42
47
  /**
@@ -45,6 +50,8 @@ export class PageBootstrap {
45
50
  * page closed during the imports.
46
51
  */
47
52
  run(): Promise<Gramlot | null>;
48
- /** Send the close request of a page that never got its `Gramlot` instance. */
53
+ /** An instance of the default export of the module `url`, the ServerAdapter the server names in `resources.serverAdapter`. */
54
+ loadServerAdapter(url: string): Promise<ServerAdapter>;
55
+ /** Send the close request of a page that never got its `Gramlot` instance, through the server adapter. */
49
56
  closePage(): void;
50
57
  }
package/src/bootstrap.js CHANGED
@@ -6,30 +6,34 @@
6
6
  */
7
7
  import {Gramlot} from './gramlot.js';
8
8
  import {LogicRegistry} from './binding/logic.js';
9
- import {HttpTransport} from './http-transport.js';
9
+ import {ServerAdapter} from './server-adapter.js';
10
10
 
11
11
  /**
12
12
  * The browser start of one page (source plan §4.12). The server writes
13
13
  * `await new PageBootstrap({config, resources}).run()` into the bootstrap HTML;
14
14
  * `resources` is `{css: [url], js: [{url, group}]}`, already in load order and
15
- * with the mount prefix.
15
+ * with the mount prefix, with `collections` and `serverAdapter` when the server has them.
16
16
  */
17
17
  export class PageBootstrap {
18
18
  constructor({config, resources, document = globalThis.document}) {
19
19
  this.config = config;
20
20
  this.resources = resources;
21
21
  this.document = document;
22
+ // The HTTP ServerAdapter of the core, replaced by run when the server names another (loadServerAdapter).
23
+ this.serverAdapter = new ServerAdapter();
22
24
  }
23
25
 
24
26
  /**
25
- * CSS links, all JS imports awaited, the Logic check (2bis), `new Gramlot`,
26
- * logic registration in received order, `start()`. Resolves with the app, or
27
- * with null when the page closed during the imports. A failed import or check
28
- * rejects naming the resource; the CSS links stay and the server page is closed.
27
+ * The server adapter the server names (imported first), CSS links, all JS imports awaited, the Logic
28
+ * check (2bis), `new Gramlot`, logic registration in received order, `start()`. Resolves with the app,
29
+ * or with null when the page closed during the imports. A failed import or check rejects naming the
30
+ * resource; the CSS links stay and the server page is closed. A failed import of the server adapter
31
+ * rejects before any of this and leaves the server page to its TTL.
29
32
  */
30
33
  async run() {
31
34
  const {config, resources, document} = this;
32
35
  const window = document.defaultView;
36
+ if (resources.serverAdapter !== undefined) this.serverAdapter = await this.loadServerAdapter(resources.serverAdapter);
33
37
  for (const url of resources.css) {
34
38
  const link = document.createElement('link');
35
39
  link.rel = 'stylesheet';
@@ -68,7 +72,7 @@ export class PageBootstrap {
68
72
  } finally {
69
73
  window.removeEventListener('pagehide', pagehide);
70
74
  }
71
- const app = new Gramlot({...config, document,
75
+ const app = new Gramlot({...config, document, serverAdapter: this.serverAdapter,
72
76
  collections: [...(config.collections ?? []), ...collections.map(collection => collection.toDocument())]});
73
77
  for (const {logicClass, group, resource} of entries) app.src.logicRegistry.register(logicClass, {group, resource});
74
78
  window.gramlot = app;
@@ -76,10 +80,23 @@ export class PageBootstrap {
76
80
  return app;
77
81
  }
78
82
 
79
- /** The close request of a page that never got its Gramlot instance: a beacon, as `Gramlot` sends on pagehide. */
83
+ /**
84
+ * The ServerAdapter the server names in `resources.serverAdapter`: an instance of the default export of the
85
+ * module `url`, which imports the core through the import map and so shares the runtime already loaded. A
86
+ * failed import rejects naming the module.
87
+ */
88
+ async loadServerAdapter(url) {
89
+ let module;
90
+ try { module = await import(new URL(url, this.document.baseURI).href); }
91
+ catch (error) { throw new Error(`${url}: server adapter import failed: ${error.message}`, {cause: error}); }
92
+ return new module.default();
93
+ }
94
+
95
+ /** The close request of a page that never got its Gramlot instance: through a transport of the server adapter,
96
+ * with a beacon, as `Gramlot` sends on pagehide. */
80
97
  closePage() {
81
- const {rpcUrl, closeUrl, pageId} = this.config;
82
- new HttpTransport(rpcUrl, {closeUrl, navigator: this.document.defaultView.navigator})
83
- .close(pageId, {beacon: true});
98
+ const transport = this.serverAdapter.createTransport({...this.config, document: this.document});
99
+ transport.close(this.config.pageId, {beacon: true});
100
+ transport.dispose();
84
101
  }
85
102
  }