@gramlot/gramlot 0.3.5 → 0.3.7

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 +1374 -905
  2. package/dist/gramlot.min.js +22 -23
  3. package/package.json +3 -3
  4. package/src/binding/ask-dialog.js +47 -24
  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 +73 -32
  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 +17 -9
  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 +170 -14
  22. package/src/components/border-container.js +17 -10
  23. package/src/components/selected-container.js +19 -18
  24. package/src/dom.d.ts +3 -0
  25. package/src/format.js +3 -10
  26. package/src/frame-messages.js +2 -1
  27. package/src/gramlot.d.ts +12 -4
  28. package/src/gramlot.js +25 -10
  29. package/src/handlers/rpc-handler.d.ts +25 -12
  30. package/src/handlers/rpc-handler.js +57 -13
  31. package/src/handlers/source-handler.d.ts +13 -3
  32. package/src/handlers/source-handler.js +23 -18
  33. package/src/handlers/subscriptions-handler.js +26 -2
  34. package/src/http-transport.d.ts +11 -2
  35. package/src/http-transport.js +31 -11
  36. package/src/index-page-runtime.js +2 -2
  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
@@ -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
  }
@@ -300,7 +300,7 @@
300
300
  }
301
301
  },
302
302
  "dataRemote": {
303
- "doc": "Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires.",
303
+ "doc": "Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",
304
304
  "sub_tags": "",
305
305
  "parent_tags": null,
306
306
  "inherits_from": null,
@@ -356,6 +356,18 @@
356
356
  "has_default": true,
357
357
  "default": null
358
358
  },
359
+ {
360
+ "name": "sync",
361
+ "kind": "positional_or_keyword",
362
+ "role": "attribute",
363
+ "annotation": {
364
+ "kind": "type",
365
+ "module": "builtins",
366
+ "name": "bool"
367
+ },
368
+ "has_default": true,
369
+ "default": true
370
+ },
359
371
  {
360
372
  "name": "params",
361
373
  "kind": "var_keyword",
@@ -7,6 +7,7 @@ import {HtmlBuilder} from '@genrojs/builders';
7
7
  import type {SourceAttributes, SourceBag, SourceBagNode, ValidateNodeOptions} from '@genrojs/builders';
8
8
  import type {GramlotHtmlRenderer} from '../renderer/gramlot-html-renderer.js';
9
9
  import type {SourceReference} from '../references.js';
10
+ import type {NameSyntax} from './name-syntax.js';
10
11
 
11
12
  /** Gramlot vocabulary and inert authoring on the shared builder grammar. */
12
13
  export class GramlotBuilder extends HtmlBuilder {
@@ -14,11 +15,13 @@ export class GramlotBuilder extends HtmlBuilder {
14
15
  static _name: string;
15
16
  /** Tag prefixes of the parent dialects, from the names of the classes above `GramlotBuilder`. */
16
17
  static get dialectPrefixes(): string[];
17
- /** Create a builder; `collections` are grammar documents loaded into it; `auth` evaluates the `auth` rules of the elements when the Source is serialised. */
18
+ /** Create a builder; `collections` are grammar documents loaded into it; `auth` evaluates the `auth` rules of the elements when the Source is serialised; `nameSyntax` checks the method names of `remote` (default `NAME_SYNTAX`). */
18
19
  constructor(name?: string | null, options?: {collections?: unknown[];
19
- auth?: ((rule: string) => null | 'not_authenticated' | 'not_authorized') | null});
20
+ auth?: ((rule: string) => null | 'not_authenticated' | 'not_authorized') | null; nameSyntax?: NameSyntax});
20
21
  /** The `auth` evaluator, or null: without it every element is serialised. */
21
22
  readonly auth: ((rule: string) => null | 'not_authenticated' | 'not_authorized') | null;
23
+ /** The NameSyntax of the method names of `remote`: the server's, the page's, or the core default `NAME_SYNTAX`. */
24
+ readonly nameSyntax: NameSyntax;
22
25
  /** The binding runtime of the Gramlot page that owns this builder, or null for authoring alone; set by `Gramlot` right after creating the builder. */
23
26
  binding: unknown;
24
27
  /** The node with `nodeId`; inside a Gramlot page it reads the node ids of the binding runtime. */
@@ -12,17 +12,19 @@ import {toTytx} from '@genrojs/tytx';
12
12
  // Loading the Gramlot Source classes adds GramlotBuilderBag to the TYTX subtype
13
13
  // dictionary of X, so every GramlotBuilder user can encode and decode it.
14
14
  import {GramlotBuilderBag} from './source.js';
15
+ import {NAME_SYNTAX, NameSyntax} from './name-syntax.js';
15
16
  import {GramlotHtmlRenderer} from '../renderer/gramlot-html-renderer.js';
16
17
  // Byte copy of src/gramlot/collections/binding.json: the JS package ships js/ only.
17
18
  import BINDING from './binding.json' with {type: 'json'};
18
19
  import WEBCOMPONENT from './webcomponent.json' with {type: 'json'};
19
20
  import {webcomponentCode} from '../webcomponent.js';
21
+ import {randomId} from '../random-id.js';
20
22
  import {pointerTransform} from '@genrojs/builders';
21
23
 
22
24
 
23
25
  // P19: `data` is ambiguous between the legacy data-element and the HTML5 element.
24
26
  const DATA_FORBIDDEN = 'data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element';
25
- // Declarations outside Gramlot 0.2.0 that fail explicitly (source plan, section 2).
27
+ // Declarations that Gramlot does not accept and that fail explicitly (source plan, section 2).
26
28
  const EXCLUDED_ELEMENTS = new Set();
27
29
  const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id']);
28
30
  const EXCLUDED_ATTRIBUTE_PREFIXES = ['formsubscribe_'];
@@ -85,10 +87,12 @@ export class GramlotBuilder extends HtmlBuilder {
85
87
  return prefixes;
86
88
  }
87
89
 
88
- constructor(name = null, {collections = [], auth = null} = {}) {
90
+ constructor(name = null, {collections = [], auth = null, nameSyntax = NAME_SYNTAX} = {}) {
91
+ if (!(nameSyntax instanceof NameSyntax)) throw new TypeError(`nameSyntax must be a NameSyntax, not ${nameSyntax}`);
89
92
  super(name);
90
93
  this._binding = null;
91
94
  this._auth = auth;
95
+ this._nameSyntax = nameSyntax;
92
96
  for (const collection of collections) this.loadCollection(collection);
93
97
  }
94
98
 
@@ -96,6 +100,11 @@ export class GramlotBuilder extends HtmlBuilder {
96
100
  * without it every element is serialised. */
97
101
  get auth() { return this._auth; }
98
102
 
103
+ /** The NameSyntax of the method names of `remote`: the one of the server that built this builder
104
+ * (`GramlotServer.nameSyntax`) or of the page (`Gramlot` option `nameSyntax`), the core default
105
+ * `NAME_SYNTAX` otherwise. */
106
+ get nameSyntax() { return this._nameSyntax; }
107
+
99
108
  /** The BindingRuntime of the Gramlot page that owns this builder, or null for authoring alone. */
100
109
  get binding() { return this._binding; }
101
110
  /** Set by Gramlot right after creating the builder (§4.3). */
@@ -108,11 +117,11 @@ export class GramlotBuilder extends HtmlBuilder {
108
117
  : null;
109
118
  }
110
119
 
111
- /** Builder's nodeById; inside a Gramlot page it reads the node_id map of the BindingRuntime (R06). */
120
+ /** Builder's nodeById; inside a Gramlot page it reads the nodeId map of the BindingRuntime (R06). */
112
121
  nodeById(nodeId) {
113
122
  if (!this.binding) return super.nodeById(nodeId);
114
123
  const node = this.binding.nodeIds.get(nodeId);
115
- if (!node) throw new Error(`node_id not found: ${nodeId}`);
124
+ if (!node) throw new Error(`nodeId not found: ${nodeId}`);
116
125
  return node.builder.wrapSource(node);
117
126
  }
118
127
  loadCollection(document) {
@@ -134,7 +143,7 @@ export class GramlotBuilder extends HtmlBuilder {
134
143
  if (lookup.startsWith(`${GramlotBuilder._name}_`)) {
135
144
  throw new Error(`${name}: the tag prefix '${GramlotBuilder._name}_' is not accepted; use the prefix '${prefixes[0]}'`);
136
145
  }
137
- if (EXCLUDED_ELEMENTS.has(lookup)) throw new Error(`${name}: excluded from Gramlot 0.2.0`);
146
+ if (EXCLUDED_ELEMENTS.has(lookup)) throw new Error(`${name}: excluded from Gramlot`);
138
147
  const tag = this.schemaTagNames[lookup];
139
148
  if (tag) return tag;
140
149
  for (const prefix of prefixes) {
@@ -160,7 +169,7 @@ export class GramlotBuilder extends HtmlBuilder {
160
169
  }
161
170
  if (tag === 'webcomponent') webcomponentCode(attrs);
162
171
  const excluded = excludedAttribute(attrs);
163
- if (excluded) throw new Error(`${tag}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
172
+ if (excluded) throw new Error(`${tag}: attribute '${excluded}' is excluded from Gramlot`);
164
173
  const error = dataElementError(tag, attrs);
165
174
  if (error) throw new Error(`${tag}: ${error}`);
166
175
  return super.validateNodeValues(tag, value, attrs);
@@ -173,7 +182,7 @@ export class GramlotBuilder extends HtmlBuilder {
173
182
  }
174
183
  if (node.nodeTag === 'webcomponent') webcomponentCode(options.attrs ?? node.getAttr());
175
184
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
176
- if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
185
+ if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot`);
177
186
  const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
178
187
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
179
188
  return super.validateNode(node, options);
@@ -231,8 +240,7 @@ export class GramlotBuilder extends HtmlBuilder {
231
240
  }
232
241
  let id = node.getAttr('__ref');
233
242
  if (id === null || id === undefined) {
234
- id = Array.from(crypto.getRandomValues(new Uint8Array(16)),
235
- byte => byte.toString(16).padStart(2, '0')).join('');
243
+ id = randomId();
236
244
  node.setAttr({__ref: id});
237
245
  }
238
246
  return {$gramlotRef: id, kind};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The syntax of a method name, declared by the server.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ /** The descriptor of a portable regex of genro-builders, as the bootstrap carries it. */
8
+ export interface NameSyntaxDescriptor {
9
+ kind: 'regex';
10
+ /** The pattern, matched whole, without the constructs Python and JavaScript read differently. */
11
+ pattern: string;
12
+ /** The Python `re` flags: only MULTILINE (8), DOTALL (16) and UNICODE (32). */
13
+ flags: number;
14
+ }
15
+
16
+ /**
17
+ * The syntax of a method name of `remote`, `dataRpc`, `dataRemote` and `remoteSource`, declared by the server
18
+ * (`GramlotServer.nameSyntax`) and carried to the browser by the bootstrap (`nameSyntax`). A portable regex of
19
+ * genro-builders, matched whole; a construct that Python and JavaScript do not read the same way is a TypeError.
20
+ */
21
+ export class NameSyntax {
22
+ /** The pattern, matched whole. */
23
+ readonly pattern: string;
24
+ /** The Python `re` flags. */
25
+ readonly flags: number;
26
+ /** Load the portable regex `pattern` with `flags`; a non-portable regex is a TypeError. */
27
+ constructor(pattern: string, flags?: number);
28
+ /** The syntax of a descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
29
+ static fromJSON(descriptor: NameSyntaxDescriptor): NameSyntax;
30
+ /** The descriptor `{kind: 'regex', pattern, flags}`, as the bootstrap carries it. */
31
+ toJSON(): NameSyntaxDescriptor;
32
+ /** Whether `name` is a string the syntax matches whole. */
33
+ matches(name: unknown): boolean;
34
+ }
35
+
36
+ /** The core default syntax: `a.b.c.method`, each segment an ASCII letter followed by ASCII letters, digits and `_`. */
37
+ export const NAME_SYNTAX: NameSyntax;
@@ -0,0 +1,54 @@
1
+ /* @ts-self-types="./name-syntax.d.ts" */
2
+ /**
3
+ * The syntax of a method name, declared by the server.
4
+ *
5
+ * @module
6
+ */
7
+ import {CustomTypes} from '@genrojs/builders';
8
+
9
+ /**
10
+ * The syntax of a method name of `remote`, `dataRpc`, `dataRemote` and `remoteSource`, declared by the server
11
+ * (`GramlotServer.nameSyntax`) and carried to the browser by the bootstrap (`nameSyntax`, GC-230 §010).
12
+ *
13
+ * A portable regex in the format of genro-builders (`Regex(pattern, flags)` exported as
14
+ * `{kind: 'regex', pattern, flags}`), matched whole. It is loaded as genro-builders loads the regex of a grammar
15
+ * (`CustomTypes.fromJSON`): a construct that Python and JavaScript do not read the same way (`\w`, `(?P<…>)`,
16
+ * an inline flag such as `(?i)`, the flag `IGNORECASE`…) is a TypeError. The Python counterpart is `NameSyntax`
17
+ * of `src/gramlot/page/name_syntax.py`.
18
+ */
19
+ export class NameSyntax {
20
+ #test;
21
+
22
+ constructor(pattern, flags = 0) {
23
+ this.pattern = pattern;
24
+ this.flags = flags;
25
+ this.#test = CustomTypes.fromJSON({nameSyntax: {kind: 'annotated',
26
+ base: {kind: 'type', module: 'builtins', name: 'str'}, metadata: [this.toJSON()]}}).resolve('nameSyntax').test;
27
+ Object.freeze(this);
28
+ }
29
+
30
+ /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
31
+ static fromJSON(descriptor) {
32
+ const keys = descriptor !== null && typeof descriptor === 'object' ? Object.keys(descriptor).sort() : [];
33
+ if (keys.join() !== 'flags,kind,pattern' || descriptor.kind !== 'regex') {
34
+ throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
35
+ }
36
+ return new NameSyntax(descriptor.pattern, descriptor.flags);
37
+ }
38
+
39
+ /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
40
+ toJSON() {
41
+ return {kind: 'regex', pattern: this.pattern, flags: this.flags};
42
+ }
43
+
44
+ /** Whether `name` is a string the syntax matches whole. */
45
+ matches(name) {
46
+ return this.#test(name);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * The core default syntax: the method of the page, or a path of public attributes from the page ending in the
52
+ * method, `a.b.c.method`. Each segment is an ASCII letter followed by ASCII letters, digits and `_`.
53
+ */
54
+ export const NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
@@ -1,6 +1,6 @@
1
1
  import {BagCbResolver} from '@genrojs/bag';
2
2
  import {SourceBag, SourceBagNode, sourceAttributeItems, wrapSource} from '@genrojs/builders';
3
- import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
3
+ import {fromTytx, getSubtypeDict, setSubtypeDict, toTytx} from '@genrojs/tytx';
4
4
  import {pointerTransform, pointerDependencies} from '@genrojs/builders';
5
5
  import {resolvePointerAttribute} from '../binding/pointer.js';
6
6
 
@@ -9,14 +9,160 @@ const CODE_ATTRIBUTES = {
9
9
  dataFormula: ['formula', '_if', '_else', '_ask_if', '_ask_onCancel'],
10
10
  dataController: ['script', '_if', '_else', '_ask_if', '_ask_onCancel'],
11
11
  dataRpc: ['_ask_if', '_ask_onCancel', '_if', '_else', '_onCalling', '_onResult', '_onError'],
12
- dataRemote: ['_if', '_else'],
12
+ dataRemote: ['_if', '_else', '_onCalling'],
13
13
  };
14
14
 
15
15
  // The control attributes of `remote`, written on the node as they are; every other parameter becomes `remote_<k>`.
16
- const REMOTE_CONTROLS = ['_cachedRemote', '_if', '_else', '_onRemote'];
16
+ const REMOTE_CONTROLS = ['_cachedRemote', '_if', '_else', '_onRemote', '_onCalling', '_delay', '_timing', '_userChanges'];
17
17
  // The inline code attributes of any node whose `remote` is a string.
18
- const REMOTE_CODE_ATTRIBUTES = ['_if', '_else', '_onRemote'];
19
- const REMOTE_NAME = /^[A-Za-z]\w*$/;
18
+ const REMOTE_CODE_ATTRIBUTES = ['_if', '_else', '_onRemote', '_onCalling'];
19
+
20
+ /**
21
+ * The requests of one Source node, read as `node.requests`: the one rule of `remote`, `dataRpc`, `dataRemote`
22
+ * and `gramlot.src.remoteSource` (GC-095 §105).
23
+ *
24
+ * - One request is in flight. It always finishes and its answer is applied; only the removal of the node, the
25
+ * close of the page or the `timeout` of a `dataRpc` aborts it.
26
+ * - The first call made while a request is in flight waits, with its method and its parameters of that moment
27
+ * (`pending`). The calls after it do nothing. When the answer arrives, the waiting call is sent.
28
+ * - `inflight.cancel()` makes the node ignore the answer of the request in flight and frees it at once. The call
29
+ * whose `_onCalling` runs the cancel is then sent, in place of a waiting call; a cancel made elsewhere sends
30
+ * the waiting call.
31
+ * - A method name that is null, empty or outside the name syntax of the page builder (`nameSyntax` of the
32
+ * `rootBuilder` of the node) rejects the call when it is sent.
33
+ *
34
+ * `inflight` is `{method, params, sentAt, cancel()}` and `pending` is `{method, params}`, each null when empty;
35
+ * `params` is a copy of the parameters as sent or saved, `sentAt` the send time in ms (`Date.now()`).
36
+ */
37
+ export class NodeRequests {
38
+ #nameSyntax;
39
+ #inflight = null;
40
+ #pending = null;
41
+ // True while the `_onCalling` of a new call runs: a cancel then frees the request for that call.
42
+ #calling = false;
43
+
44
+ /** The requests of a node whose method names follow `nameSyntax` (a NameSyntax). */
45
+ constructor(nameSyntax) {
46
+ this.#nameSyntax = nameSyntax;
47
+ }
48
+
49
+ /** The request in flight, `{method, params, sentAt, cancel()}`, or null. */
50
+ get inflight() {
51
+ return this.#inflight?.view ?? null;
52
+ }
53
+
54
+ /** The call waiting for the answer of the request in flight, `{method, params}`, or null. */
55
+ get pending() {
56
+ const pending = this.#pending;
57
+ if (!pending) return null;
58
+ return Object.freeze({method: pending.method, get params() { return fromTytx(pending.text); }});
59
+ }
60
+
61
+ /**
62
+ * Run `onCalling`, the `_onCalling` of a call, before the call: a result `false` blocks it. Without
63
+ * `onCalling` the call is allowed. A refused or failed `onCalling` that cancelled the request in flight
64
+ * sends the waiting call.
65
+ */
66
+ calling(onCalling) {
67
+ if (!onCalling) return true;
68
+ let allowed = false;
69
+ const outer = this.#calling;
70
+ this.#calling = true;
71
+ try {
72
+ allowed = onCalling() !== false;
73
+ } finally {
74
+ this.#calling = outer;
75
+ if (!allowed && !this.#inflight) this.#next();
76
+ }
77
+ return allowed;
78
+ }
79
+
80
+ /**
81
+ * Send the call of `method` with `params` now, keep it waiting, or drop it, by the rule of the class.
82
+ * `perform(request)` sends it and applies the answer; `request` has `method`, `params`, `text` (the TYTX of
83
+ * the parameters), `controller` (its AbortController, aborted by the removal of the node, the close of the
84
+ * page or a `timeout`) and `ignored` (true after `cancel()`). Returns the promise of `perform`, settled when the call has
85
+ * run; a dropped call, or a waiting call never sent, gives undefined.
86
+ */
87
+ submit(method, params, perform) {
88
+ try {
89
+ const text = toTytx(params);
90
+ if (this.#inflight) {
91
+ if (this.#pending) return Promise.resolve(undefined);
92
+ return new Promise((resolve, reject) => {
93
+ this.#pending = {method, text, perform, resolve, reject};
94
+ });
95
+ }
96
+ // A call sent while another waits follows a cancel made by its `_onCalling`: it is newer, the waiting one is dropped.
97
+ this.#pending?.resolve(undefined);
98
+ this.#pending = null;
99
+ return this.#start(method, params, text, perform);
100
+ } catch (error) {
101
+ return Promise.reject(error);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Run the synchronous call of `method` now: `perform()` sends it and returns its value, which this method
107
+ * returns. It is never in flight for another call: nothing else runs while it waits. A request of the node
108
+ * in flight, or a method outside the name syntax, is an error.
109
+ */
110
+ submitSync(method, perform) {
111
+ if (this.#inflight) throw new Error('A synchronous call cannot start while a request of the node is in flight');
112
+ if (!this.#nameSyntax.matches(method)) {
113
+ throw new TypeError(`Method name must match ${this.#nameSyntax.pattern}, not ${JSON.stringify(method)}`);
114
+ }
115
+ return perform();
116
+ }
117
+
118
+ /** Send the waiting call, if any, with its saved method and parameters. */
119
+ #next() {
120
+ const pending = this.#pending;
121
+ if (!pending) return;
122
+ this.#pending = null;
123
+ let result;
124
+ try {
125
+ result = this.#start(pending.method, fromTytx(pending.text), pending.text, pending.perform);
126
+ } catch (error) {
127
+ result = Promise.reject(error);
128
+ }
129
+ result.then(pending.resolve, pending.reject);
130
+ }
131
+
132
+ #start(method, params, text, perform) {
133
+ if (!this.#nameSyntax.matches(method)) {
134
+ return Promise.reject(new TypeError(`Method name must match ${this.#nameSyntax.pattern}, not ${JSON.stringify(method)}`));
135
+ }
136
+ const controller = new AbortController();
137
+ const record = {method, params, text, controller, ignored: false};
138
+ record.view = Object.freeze({method, get params() { return fromTytx(text); }, sentAt: Date.now(),
139
+ cancel: () => this.#cancel(record)});
140
+ this.#inflight = record;
141
+ // An abort ends the request at once: the waiting call does not wait for an answer that is not applied.
142
+ controller.signal.addEventListener('abort', () => this.#finish(record), {once: true});
143
+ let result;
144
+ try {
145
+ result = Promise.resolve(perform(record));
146
+ } catch (error) {
147
+ result = Promise.reject(error);
148
+ }
149
+ result.then(() => this.#finish(record), () => this.#finish(record));
150
+ return result;
151
+ }
152
+
153
+ #finish(record) {
154
+ if (this.#inflight !== record) return;
155
+ this.#inflight = null;
156
+ this.#next();
157
+ }
158
+
159
+ #cancel(record) {
160
+ if (this.#inflight !== record) return;
161
+ record.ignored = true;
162
+ this.#inflight = null;
163
+ if (!this.#calling) this.#next();
164
+ }
165
+ }
20
166
 
21
167
  /** Whether `value` is a `==` expression (Q11.2). */
22
168
  function isExpression(value) {
@@ -35,12 +181,18 @@ export class GramlotBuilderBagNode extends SourceBagNode {
35
181
  #reportedPathPointers = new Set();
36
182
  // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
37
183
  #activatedCode = null;
184
+ #requests = null;
185
+
186
+ /** The requests of this node (NodeRequests): the request in flight and the waiting call of remote, dataRpc and dataRemote. */
187
+ get requests() {
188
+ return this.#requests ??= new NodeRequests(this.rootBuilder.nameSyntax);
189
+ }
38
190
 
39
191
  /**
40
192
  * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
41
- * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
42
- * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
43
- * button, `_if`/`_else`/`_onRemote` of a node whose `remote` is a string, every `connect_on<event>`,
193
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
194
+ * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
195
+ * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
44
196
  * every `==` attribute (canonical name) and a `==` node value (`''`).
45
197
  */
46
198
  codeAttributes() {
@@ -96,12 +248,16 @@ export class GramlotBuilderBagNode extends SourceBagNode {
96
248
  /**
97
249
  * Declare the content of this element as the fragment `name` of a `@source` method: writes
98
250
  * `remote = name` and one `remote_<k> = v` per entry of `params` on this node; the control attributes
99
- * `_cachedRemote`, `_if`, `_else` and `_onRemote` are written as they are. Returns this node. A bad
100
- * name or another `_` parameter is a TypeError.
251
+ * `_cachedRemote`, `_if`, `_else`, `_onRemote`, `_onCalling`, `_delay`, `_timing` and `_userChanges` are
252
+ * written as they are. Returns this node. `name` is a method name, matched by the name syntax of the
253
+ * page builder (`nameSyntax` of `rootBuilder`), or a `^`/`=` pointer to it; any other name, or another
254
+ * `_` parameter, is a TypeError.
101
255
  */
102
256
  remote(name, params = {}) {
103
- if (typeof name !== 'string' || !REMOTE_NAME.test(name)) {
104
- throw new TypeError(`${this.nodeTag} '${this.label}': remote name must match ${REMOTE_NAME.source}, not ${JSON.stringify(name)}`);
257
+ const syntax = this.rootBuilder.nameSyntax;
258
+ if (typeof name !== 'string' || !(this.pointerType(name) || syntax.matches(name))) {
259
+ throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match `
260
+ + `${syntax.pattern}, not ${JSON.stringify(name)}`);
105
261
  }
106
262
  const invalid = Object.keys(params).find(key => key.startsWith('_') && !REMOTE_CONTROLS.includes(key));
107
263
  if (invalid) {
@@ -118,7 +274,7 @@ export class GramlotBuilderBagNode extends SourceBagNode {
118
274
 
119
275
  /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
120
276
  publish(topic, payload = {}) {
121
- return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
277
+ return this.builder.binding.subscriptions.publishNode(this, topic, payload);
122
278
  }
123
279
 
124
280
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
@@ -291,7 +447,7 @@ export class GramlotBuilderBagNode extends SourceBagNode {
291
447
  return path === null ? null : super._finalizeAbsPath(path, attr);
292
448
  }
293
449
 
294
- /** Builder's symbolic resolution; `#<node_id>` reads the node_id map of the page runtime when there is one (R06). */
450
+ /** Builder's symbolic resolution; `#<nodeId>` reads the nodeId map of the page runtime when there is one (R06). */
295
451
  _resolveSymbolicDatapath(path, raw) {
296
452
  const symbol = path.slice(1).split('.', 1)[0];
297
453
  if (symbol === 'FORM' || symbol === 'ANCHOR') return super._resolveSymbolicDatapath(path, raw);