@gramlot/gramlot 0.2.11 → 0.2.14

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 (44) hide show
  1. package/dist/gramlot.js +394 -181
  2. package/dist/gramlot.min.js +42 -0
  3. package/package.json +5 -5
  4. package/src/binding/inline.js +1 -1
  5. package/src/binding/installation.js +14 -7
  6. package/src/binding/providers.js +69 -6
  7. package/src/binding/runtime.js +3 -3
  8. package/src/bootstrap.d.ts +2 -2
  9. package/src/bootstrap.js +4 -4
  10. package/src/builder/binding.json +87 -0
  11. package/src/builder/gramlot-builder.js +2 -2
  12. package/src/builder/source.js +3 -1
  13. package/src/gramlot.d.ts +12 -10
  14. package/src/gramlot.js +7 -6
  15. package/src/handlers/rpc-handler.d.ts +44 -7
  16. package/src/handlers/rpc-handler.js +32 -5
  17. package/src/handlers/source-handler.d.ts +1 -1
  18. package/src/handlers/source-handler.js +5 -3
  19. package/src/http-transport.d.ts +27 -0
  20. package/src/{transport.js → http-transport.js} +11 -18
  21. package/src/index.d.ts +5 -3
  22. package/src/index.js +3 -2
  23. package/src/renderer/gramlot-renderer.js +1 -1
  24. package/src/server/assets.d.ts +12 -0
  25. package/src/server/assets.js +30 -0
  26. package/src/server/conformance.d.ts +9 -0
  27. package/src/server/conformance.js +187 -0
  28. package/src/{adapters/file-host.d.ts → server/gramlot-file-server.d.ts} +15 -7
  29. package/src/{adapters/file-host.js → server/gramlot-file-server.js} +26 -13
  30. package/src/{adapters/host.d.ts → server/gramlot-server.d.ts} +50 -27
  31. package/src/server/gramlot-server.js +208 -0
  32. package/src/server/index.d.ts +17 -0
  33. package/src/server/index.js +16 -0
  34. package/src/server/page.d.ts +46 -0
  35. package/src/server/page.js +76 -0
  36. package/src/{adapters → server}/resources.d.ts +3 -1
  37. package/src/{adapters → server}/resources.js +2 -2
  38. package/src/view/button.js +7 -7
  39. package/src/adapters/host.js +0 -137
  40. package/src/adapters/index.d.ts +0 -13
  41. package/src/adapters/index.js +0 -13
  42. package/src/adapters/page.d.ts +0 -36
  43. package/src/adapters/page.js +0 -43
  44. package/src/transport.d.ts +0 -34
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.11",
3
+ "version": "0.2.14",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -12,7 +12,7 @@
12
12
  "scripts": {
13
13
  "test": "node --test tests/*.test.js tests/binding-contracts/gramlot-quiet-write.test.mjs tests/upstream-regressions/builder-symbolic-attribute.test.mjs",
14
14
  "build": "node scripts/build-runtime.mjs",
15
- "test:host": "node --test tests/host.test.js",
15
+ "test:server": "node --test tests/gramlot-server.test.js",
16
16
  "prepack": "node scripts/build-runtime.mjs"
17
17
  },
18
18
  "dependencies": {
@@ -27,10 +27,10 @@
27
27
  },
28
28
  "exports": {
29
29
  ".": "./src/index.js",
30
- "./server": "./src/adapters/index.js",
30
+ "./server": "./src/server/index.js",
31
31
  "./runtime": "./dist/gramlot.js",
32
- "./page": "./src/adapters/page.js",
33
- "./host": "./src/adapters/host.js",
32
+ "./page": "./src/server/page.js",
33
+ "./gramlot-server": "./src/server/gramlot-server.js",
34
34
  "./themes/*": "./themes/*",
35
35
  "./assets/branding/*": "./assets/branding/*"
36
36
  },
@@ -4,7 +4,7 @@ import {isExpression, templateParameters} from '../renderer/attributes.js';
4
4
  /**
5
5
  * Inline code of one Gramlot page (source plan §4.10): the `formula`/`script` bodies, `_if`/`_else`,
6
6
  * `action`, `connect_on<event>` and the `==` expressions, compiled with `this` = the Source node. Imported
7
- * only by the page runtime: never by `adapters/*`, `builder/*` or a WorkerHost, so a page with named logic
7
+ * only by the page runtime: never by `server/*`, `builder/*` or a GramlotWorkerServer, so a page with named logic
8
8
  * only runs under a CSP without `'unsafe-eval'`.
9
9
  *
10
10
  * Only the inline code received with the Source runs: the text activated by SourceHandler.prepareSource
@@ -169,18 +169,25 @@ export function requireInstallable(branch) {
169
169
  }
170
170
  }
171
171
 
172
- // Provider attributes (§4.8): only a `dataFormula` or a `dataController` carries them.
172
+ // Provider attributes (§4.8): only a `dataFormula`, a `dataController` or a `dataRpc` carries them;
173
+ // the callbacks of the call only a `dataRpc`.
173
174
  const PROVIDER_ATTRIBUTES = ['_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges'];
174
- const PROVIDER_TAGS = new Set(['dataFormula', 'dataController']);
175
+ const PROVIDER_TAGS = new Set(['dataFormula', 'dataController', 'dataRpc']);
176
+ const RPC_ATTRIBUTES = ['_onCalling', '_onResult', '_onError'];
175
177
  // The lifecycle attributes: true, false, null or a number (a delay in ms, P22); a pointer is not read.
176
178
  const LIFECYCLE_ATTRIBUTES = ['_init', '_onBuilt', '_onStart'];
177
179
 
178
180
  /**
179
- * A provider attribute on any other node is an error before any write; so is a `==` expression in an
180
- * attribute of a `dataFormula` or `dataController` (S09: `==` belongs to the visual nodes), and a
181
- * lifecycle attribute whose value is not `true`, `false`, null or a number.
181
+ * A provider attribute on any other node is an error before any write, and so is an rpc callback
182
+ * outside a `dataRpc`; so is a `==` expression in an attribute of a provider node (S09: `==` belongs
183
+ * to the visual nodes), and a lifecycle attribute whose value is not `true`, `false`, null or a number.
182
184
  */
183
185
  function requireProviderAttributes(node) {
186
+ const isSet = name => node.getAttr(name) !== null && node.getAttr(name) !== undefined;
187
+ if (node.nodeTag !== 'dataRpc') {
188
+ const callback = RPC_ATTRIBUTES.find(isSet);
189
+ if (callback) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${callback}' is allowed only on dataRpc`);
190
+ }
184
191
  if (PROVIDER_TAGS.has(node.nodeTag)) {
185
192
  const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression(value));
186
193
  if (expression) {
@@ -194,8 +201,8 @@ function requireProviderAttributes(node) {
194
201
  }
195
202
  return;
196
203
  }
197
- const name = PROVIDER_ATTRIBUTES.find(each => node.getAttr(each) !== null && node.getAttr(each) !== undefined);
198
- if (name) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${name}' is allowed only on dataFormula and dataController`);
204
+ const name = PROVIDER_ATTRIBUTES.find(isSet);
205
+ if (name) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${name}' is allowed only on dataFormula, dataController and dataRpc`);
199
206
  }
200
207
 
201
208
  /** The nodes of `branch` (a SourceBagNode or a SourceBag), depth first, in document order. */
@@ -1,12 +1,12 @@
1
1
  import {Bag} from '@genrojs/bag';
2
2
 
3
3
  /**
4
- * Providers of one Gramlot page (source plan §4.8): the semantic runtime of a `dataFormula` or a
5
- * `dataController`, owned by its NodeBinding.
4
+ * Providers of one Gramlot page (source plan §4.8): the semantic runtime of a `dataFormula`, a
5
+ * `dataController` or a `dataRpc`, owned by its NodeBinding.
6
6
  *
7
7
  * One owner per trigger (B7): the router delivers the Data changes of the `^` pointers to
8
8
  * `receive`; `_timing` is started by `register`; `_init`, `_onBuilt` and `_onStart` are invoked by
9
- * BindingRuntime; the click of a button invokes the controller nested in it, through ButtonBinding. Every timer is tracked on the NodeBinding, so the close of the node cancels it.
9
+ * BindingRuntime; the click of a button invokes the controller or the rpc nested in it, through ButtonBinding. Every timer is tracked on the NodeBinding, so the close of the node cancels it.
10
10
  * A body is named logic (P20), the group method given by `LogicRegistry.resolve`, or inline code
11
11
  * compiled by the page's InlineCompiler (S09); there is no fallback from a name to inline.
12
12
  */
@@ -16,6 +16,7 @@ import {Bag} from '@genrojs/bag';
16
16
  const CONTROL_ATTRIBUTES = new Set([
17
17
  'destination_path', 'result_path', 'func', 'formula', 'script', 'if', 'else',
18
18
  '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
19
+ 'method', 'timeout', '_onCalling', '_onResult', '_onError',
19
20
  ]);
20
21
 
21
22
  export class Provider {
@@ -24,6 +25,8 @@ export class Provider {
24
25
  #timingRegistration = null;
25
26
  #stopTiming = null;
26
27
  #cancelDelay = null;
28
+ // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
29
+ #rpcCall = null;
27
30
 
28
31
  constructor(binding) {
29
32
  this.#binding = binding;
@@ -35,8 +38,8 @@ export class Provider {
35
38
 
36
39
  get binding() { return this.#binding; }
37
40
  get node() { return this.binding.node; }
38
- /** 'formula' | 'controller'. */
39
- get kind() { throw new Error('Provider.kind is defined by FormulaProvider and ControllerProvider'); }
41
+ /** 'formula' | 'controller' | 'rpc'. */
42
+ get kind() { throw new Error('Provider.kind is defined by FormulaProvider, ControllerProvider and RpcProvider'); }
40
43
 
41
44
  /**
42
45
  * Step 4 of §5.1, and every rebinding: the `^` pointers are registered again from the current
@@ -87,12 +90,14 @@ export class Provider {
87
90
  * `_else` are inline (Q11.1): a false `_if` stops, or `_else` replaces the body (D5); an empty `_if`
88
91
  * is absent and an empty `_else` or body is none, as legacy. A body is
89
92
  * the inline `formula`/`script`, compiled by the page's InlineCompiler, or the named `func`. An
90
- * error propagates to the caller (P12). A closed node runs nothing.
93
+ * error propagates to the caller (P12). A closed node runs nothing. The body of a `dataRpc` is the
94
+ * call: `invoke` returns its promise, and a false `_if` runs `_else` as inline code without calling.
91
95
  */
92
96
  invoke(trigger) {
93
97
  if (this.binding.closed) return;
94
98
  const node = this.node;
95
99
  const formula = this.kind === 'formula';
100
+ const rpc = this.kind === 'rpc';
96
101
  const kwargs = this.readArguments(trigger);
97
102
  let [attr, body] = [formula ? 'formula' : 'script', node.getAttr(formula ? 'formula' : 'script')];
98
103
  // Truthiness of `_if`, `_else` and the body, as legacy (`gnrdomsource.js:371-385, 473-482`).
@@ -100,7 +105,12 @@ export class Provider {
100
105
  if (condition && !this.#inline('_if', condition, `return (${condition})`, kwargs, false)) {
101
106
  [attr, body] = ['_else', node.getAttr('_else')];
102
107
  if (!body) return;
108
+ if (rpc) {
109
+ this.#inline(attr, body, body, kwargs, true);
110
+ return;
111
+ }
103
112
  }
113
+ if (rpc) return this.#call(kwargs);
104
114
  const func = node.getAttr('func');
105
115
  let result;
106
116
  if (body) {
@@ -193,6 +203,54 @@ export class Provider {
193
203
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({...kwargs, _kwargs: kwargs});
194
204
  }
195
205
 
206
+ /**
207
+ * The call of a `dataRpc`: `_onCalling`, then `gramlot.rpc.call('data', method, …)` with the author
208
+ * arguments, then the value written at `result_path` when present and `_onResult`. The previous
209
+ * call of the node is aborted and its answer dropped (latest wins); the close of the node aborts
210
+ * the call too. `timeout` > 0 ms aborts it with a `TimeoutError`. A failure goes to `_onError`, or
211
+ * rejects the returned promise when the node declares none.
212
+ */
213
+ async #call(kwargs) {
214
+ const node = this.node;
215
+ const [onCalling, onResult, onError] = ['_onCalling', '_onResult', '_onError'].map(name => node.getAttr(name));
216
+ if (onCalling) this.#inline('_onCalling', onCalling, onCalling, kwargs, true);
217
+ this.#rpcCall?.abort();
218
+ const controller = new AbortController();
219
+ this.#rpcCall = controller;
220
+ const release = this.binding.track(() => controller.abort());
221
+ const timeout = this.#resolved('timeout');
222
+ const timer = timeout > 0 ? setTimeout(() => {
223
+ const error = new Error(`${node.nodeTag} '${node.label}': no answer within ${timeout} ms`);
224
+ error.name = 'TimeoutError';
225
+ controller.abort(error);
226
+ }, timeout) : null;
227
+ const aborted = new Promise((resolve, reject) => {
228
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {once: true});
229
+ });
230
+ let outcome;
231
+ try {
232
+ const call = this.binding.runtime.gramlot.rpc.call('data', this.#resolved('method'), authorArguments(kwargs),
233
+ {signal: controller.signal});
234
+ outcome = {result: await Promise.race([call, aborted])};
235
+ } catch (error) {
236
+ outcome = {error};
237
+ }
238
+ clearTimeout(timer);
239
+ release();
240
+ // Superseded by a newer call, or the node closed: the answer is dropped.
241
+ const current = this.#rpcCall === controller && !this.binding.closed;
242
+ if (this.#rpcCall === controller) this.#rpcCall = null;
243
+ if (!current) return;
244
+ if ('error' in outcome) {
245
+ if (!onError) throw outcome.error;
246
+ this.#inline('_onError', onError, onError, {...kwargs, error: outcome.error}, true);
247
+ return;
248
+ }
249
+ const {result} = outcome;
250
+ if (node.getAttr('result_path') != null) node.setRelativeData(node.pathAttribute('result_path'), result);
251
+ if (onResult) this.#inline('_onResult', onResult, onResult, {...kwargs, result}, true);
252
+ }
253
+
196
254
  #closeRegistrations() {
197
255
  for (const registration of this.#registrations.splice(0)) registration.close();
198
256
  this.#timingRegistration = null;
@@ -209,6 +267,11 @@ export class ControllerProvider extends Provider {
209
267
  get kind() { return 'controller'; }
210
268
  }
211
269
 
270
+ /** The provider of a `dataRpc`: the body is the call of a server endpoint through `gramlot.rpc`. */
271
+ export class RpcProvider extends Provider {
272
+ get kind() { return 'rpc'; }
273
+ }
274
+
212
275
  // The trigger fields of the kwargs, in the legacy order of the inline parameters.
213
276
  const TRIGGER_FIELDS = ['_node', '_triggerpars', '_reason'];
214
277
  // The fields a click adds (P9): locals of the inline bodies, never author arguments.
@@ -1,11 +1,11 @@
1
1
  import {SourceBag} from '@genrojs/builders';
2
2
  import {DataRouter} from './router.js';
3
3
  import {DataInstaller} from './installation.js';
4
- import {ControllerProvider, FormulaProvider} from './providers.js';
4
+ import {ControllerProvider, FormulaProvider, RpcProvider} from './providers.js';
5
5
  import {InlineCompiler} from './inline.js';
6
6
 
7
7
  // The Provider class of each provider data-element (§4.8).
8
- const PROVIDERS = {dataFormula: FormulaProvider, dataController: ControllerProvider};
8
+ const PROVIDERS = {dataFormula: FormulaProvider, dataController: ControllerProvider, dataRpc: RpcProvider};
9
9
 
10
10
  // Attributes whose change moves the Data context of a whole branch (§4.4, upd_attrs row).
11
11
  const CONTEXT_ATTRIBUTES = ['datapath', '_anchor', 'node_id', 'form', 'formId'];
@@ -345,7 +345,7 @@ export class NodeBinding {
345
345
  get closed() { return this.#closed; }
346
346
  /** The active DataRegistrations of the node. */
347
347
  get registrations() { return [...this.#registrations]; }
348
- /** The Provider of a `dataFormula` or `dataController`, as a list of zero or one. */
348
+ /** The Provider of a `dataFormula`, `dataController` or `dataRpc`, as a list of zero or one. */
349
349
  get providers() { return this.#provider ? [this.#provider] : []; }
350
350
 
351
351
  /** The clicks counted by the node's ButtonBinding since the node entered the Source (P9). */
@@ -14,7 +14,7 @@ export interface PageResources {
14
14
  js: {url: string; group: string | null}[];
15
15
  }
16
16
 
17
- /** The configuration written by the host into the bootstrap HTML. */
17
+ /** The configuration written by the server into the bootstrap HTML. */
18
18
  export interface PageBootstrapOptions {
19
19
  /** The options of the `Gramlot` instance, with the page id. */
20
20
  config: GramlotOptions;
@@ -25,7 +25,7 @@ export interface PageBootstrapOptions {
25
25
  }
26
26
 
27
27
  /**
28
- * The browser start of one page. The host writes
28
+ * The browser start of one page. The server writes
29
29
  * `await new PageBootstrap({config, resources}).run()` into the bootstrap HTML.
30
30
  */
31
31
  export class PageBootstrap {
package/src/bootstrap.js CHANGED
@@ -6,10 +6,10 @@
6
6
  */
7
7
  import {Gramlot} from './gramlot.js';
8
8
  import {LogicRegistry} from './binding/logic.js';
9
- import {MainTransport} from './transport.js';
9
+ import {HttpTransport} from './http-transport.js';
10
10
 
11
11
  /**
12
- * The browser start of one page (source plan §4.12). The host writes
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
15
  * with the mount prefix.
@@ -71,8 +71,8 @@ export class PageBootstrap {
71
71
 
72
72
  /** The close request of a page that never got its Gramlot instance: a beacon, as `Gramlot` sends on pagehide. */
73
73
  closePage() {
74
- const {mainUrl, sourceUrl, closeUrl, pageId} = this.config;
75
- new MainTransport(mainUrl, undefined, sourceUrl, closeUrl, this.document.defaultView.navigator)
74
+ const {rpcUrl, closeUrl, pageId} = this.config;
75
+ new HttpTransport(rpcUrl, {closeUrl, navigator: this.document.defaultView.navigator})
76
76
  .close(pageId, {beacon: true});
77
77
  }
78
78
  }
@@ -211,6 +211,93 @@
211
211
  "_meta": {
212
212
  "data_element": true
213
213
  }
214
+ },
215
+ "dataRpc": {
216
+ "doc": "Server endpoint called through gramlot.rpc; the value is written at result_path when given.",
217
+ "sub_tags": "",
218
+ "parent_tags": null,
219
+ "inherits_from": null,
220
+ "ns": null,
221
+ "attributes": {
222
+ "parameters": [
223
+ {
224
+ "name": "method",
225
+ "kind": "positional_or_keyword",
226
+ "role": "attribute",
227
+ "annotation": {
228
+ "kind": "type",
229
+ "module": "builtins",
230
+ "name": "str"
231
+ },
232
+ "has_default": false
233
+ },
234
+ {
235
+ "name": "result_path",
236
+ "kind": "positional_or_keyword",
237
+ "role": "attribute",
238
+ "annotation": {
239
+ "kind": "union",
240
+ "items": [
241
+ {
242
+ "kind": "type",
243
+ "module": "builtins",
244
+ "name": "str"
245
+ },
246
+ {
247
+ "kind": "type",
248
+ "module": "builtins",
249
+ "name": "NoneType"
250
+ }
251
+ ]
252
+ },
253
+ "has_default": true,
254
+ "default": null
255
+ },
256
+ {
257
+ "name": "timeout",
258
+ "kind": "positional_or_keyword",
259
+ "role": "attribute",
260
+ "annotation": {
261
+ "kind": "union",
262
+ "items": [
263
+ {
264
+ "kind": "type",
265
+ "module": "builtins",
266
+ "name": "int"
267
+ },
268
+ {
269
+ "kind": "type",
270
+ "module": "builtins",
271
+ "name": "float"
272
+ },
273
+ {
274
+ "kind": "type",
275
+ "module": "builtins",
276
+ "name": "NoneType"
277
+ }
278
+ ]
279
+ },
280
+ "has_default": true,
281
+ "default": null
282
+ },
283
+ {
284
+ "name": "params",
285
+ "kind": "var_keyword",
286
+ "role": "attribute",
287
+ "annotation": {
288
+ "kind": "any"
289
+ },
290
+ "has_default": false
291
+ }
292
+ ],
293
+ "accepts_var_keyword": true,
294
+ "accepts_var_positional": false
295
+ },
296
+ "node_label": null,
297
+ "collection_key": null,
298
+ "_meta": {
299
+ "data_element": true
300
+ }
214
301
  }
215
302
  }
216
303
  }
@@ -17,13 +17,13 @@ import BINDING from './binding.json' with {type: 'json'};
17
17
  // P19: `data` is ambiguous between the legacy data-element and the HTML5 element.
18
18
  const DATA_FORBIDDEN = 'data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element';
19
19
  // Declarations outside Gramlot 0.2.0 that fail explicitly (source plan, section 2).
20
- const EXCLUDED_ELEMENTS = new Set(['datarpc', 'dataremote']);
20
+ const EXCLUDED_ELEMENTS = new Set(['dataremote']);
21
21
  const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id', 'remote', '_ask', 'ask']);
22
22
  const EXCLUDED_ATTRIBUTE_PREFIXES = ['subscribe_', 'selfsubscribe_', 'formsubscribe_'];
23
23
 
24
24
  // P18 and B8: the Data path of each data-element, which does not accept `?attr`,
25
25
  // and its inline attribute, which excludes `func` on the same node, as `_if` does (Q11.1).
26
- const DATA_PATH_ATTRIBUTES = {dataSetter: 'destination_path', dataFormula: 'result_path'};
26
+ const DATA_PATH_ATTRIBUTES = {dataSetter: 'destination_path', dataFormula: 'result_path', dataRpc: 'result_path'};
27
27
  const DATA_INLINE_ATTRIBUTES = {dataFormula: 'formula', dataController: 'script'};
28
28
 
29
29
  /** The P18 violation of a data-element's attributes, or null. */
@@ -5,6 +5,7 @@ import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
5
5
  const CODE_ATTRIBUTES = {
6
6
  dataFormula: ['formula', '_if', '_else'],
7
7
  dataController: ['script', '_if', '_else'],
8
+ dataRpc: ['_if', '_else', '_onCalling', '_onResult', '_onError'],
8
9
  button: ['action'],
9
10
  };
10
11
 
@@ -28,7 +29,8 @@ export class GramlotBuilderBagNode extends SourceBagNode {
28
29
 
29
30
  /**
30
31
  * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
31
- * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of both, `action` of a
32
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
33
+ * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
32
34
  * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
33
35
  */
34
36
  codeAttributes() {
package/src/gramlot.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import type {DomElement, DomDocument, DomEvent, DomWindow} from './dom.d.ts';
7
7
  import type {Bag} from '@genrojs/bag';
8
- import type {MainTransport} from './transport.js';
8
+ import type {RpcTransport} from './handlers/rpc-handler.js';
9
9
  import type {SourceHandler} from './handlers/source-handler.js';
10
10
  import type {RpcHandler} from './handlers/rpc-handler.js';
11
11
  import type {DomHandler} from './handlers/dom-handler.js';
@@ -13,22 +13,22 @@ import type {UtilitiesHandler} from './handlers/utilities-handler.js';
13
13
 
14
14
  /** The options of a `Gramlot` instance. */
15
15
  export interface GramlotOptions {
16
- /** The id of the server page, as registered by the host. */
16
+ /** The id of the server page, as registered by the server. */
17
17
  pageId?: string;
18
- /** The URL of the `main` Source endpoint. */
19
- mainUrl?: string;
20
- /** The URL of the remote Source endpoint. */
21
- sourceUrl?: string;
18
+ /** The URL of the rpc endpoint that receives the envelopes. */
19
+ rpcUrl?: string;
22
20
  /** The URL of the page close endpoint. */
23
21
  closeUrl?: string;
24
22
  /** The id of the root element that receives the page. */
25
23
  rootId?: string;
24
+ /** The capabilities announced by the server in the bootstrap. */
25
+ capabilities?: string[];
26
26
  /** The root element; when null it is looked up by `rootId`. */
27
27
  element?: DomElement | null;
28
28
  /** The document of the page. */
29
29
  document?: DomDocument;
30
30
  /** A transport, or `false` for an instance with no server transport. */
31
- transport?: MainTransport | false | null;
31
+ transport?: RpcTransport | false | null;
32
32
  /** Grammar collections loaded into the builder. */
33
33
  collections?: unknown[];
34
34
  }
@@ -40,13 +40,15 @@ export type GramlotState = 'ready' | 'loading' | 'started' | 'failed' | 'dispose
40
40
  export class Gramlot {
41
41
  /** The id of the server page. */
42
42
  pageId: string | undefined;
43
+ /** The capabilities announced by the server in the bootstrap, frozen. */
44
+ capabilities: readonly string[];
43
45
  /** The root group of the named logic of the page. */
44
46
  logic: unknown;
45
47
  /** The Source and every change of it. */
46
48
  src: SourceHandler;
47
49
  /** The Data Bag of the page. */
48
50
  data: Bag;
49
- /** The exchange with the host. */
51
+ /** The exchange with the server. */
50
52
  rpc: RpcHandler;
51
53
  /** The DOM and its correspondence with the Source. */
52
54
  dom: DomHandler;
@@ -58,9 +60,9 @@ export class Gramlot {
58
60
  abort: AbortController;
59
61
  /** The pending `start` promise, while loading. */
60
62
  loading?: Promise<Gramlot> | null;
61
- /** The window whose `pagehide` disposes the page; set only with the default `MainTransport`. */
63
+ /** The window whose `pagehide` disposes the page; set only with the default `HttpTransport`. */
62
64
  window?: DomWindow;
63
- /** The `pagehide` listener that disposes the page with a beacon; set only with the default `MainTransport`. */
65
+ /** The `pagehide` listener that disposes the page with a beacon; set only with the default `HttpTransport`. */
64
66
  pagehide?: (event: DomEvent) => void;
65
67
  /** Create the page instance; the construction order is the one of the source plan. */
66
68
  constructor(options?: GramlotOptions);
package/src/gramlot.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {MainTransport} from './transport.js';
7
+ import {HttpTransport} from './http-transport.js';
8
8
  import {SourceHandler} from './handlers/source-handler.js';
9
9
  import {RpcHandler} from './handlers/rpc-handler.js';
10
10
  import {DomHandler} from './handlers/dom-handler.js';
@@ -15,17 +15,18 @@ import {UtilitiesHandler} from './handlers/utilities-handler.js';
15
15
  * `SourceHandler` creates the builder, the binding runtime and the renderer in the order of source plan §4.3.
16
16
  */
17
17
  export class Gramlot {
18
- constructor({pageId, mainUrl = '/gramlot/main', sourceUrl = '/gramlot/source', closeUrl = '/gramlot/close', rootId = 'gramlot-root',
18
+ constructor({pageId, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
19
19
  element = null, document = globalThis.document, transport = null, collections = []} = {}) {
20
20
  this.pageId = pageId;
21
+ this.capabilities = Object.freeze([...capabilities]);
21
22
  this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId)});
22
23
  this.data = this.src.builder.data;
23
- this.rpc = new RpcHandler(this, {mainUrl, sourceUrl, closeUrl, document, transport});
24
+ this.rpc = new RpcHandler(this, {rpcUrl, closeUrl, document, transport});
24
25
  this.dom = new DomHandler(this);
25
26
  this.utl = new UtilitiesHandler(this, document);
26
27
  this.state = 'ready';
27
28
  this.abort = new AbortController();
28
- if (this.rpc.transport instanceof MainTransport) {
29
+ if (this.rpc.transport instanceof HttpTransport) {
29
30
  this.pagehide = event => { if (!event.persisted) this.dispose({beacon: true}); };
30
31
  document.defaultView.addEventListener('pagehide', this.pagehide);
31
32
  this.window = document.defaultView;
@@ -42,7 +43,7 @@ export class Gramlot {
42
43
  }
43
44
  async loadMain() {
44
45
  try {
45
- const wire = await this.rpc.transport.main(this.pageId, this.abort.signal);
46
+ const wire = await this.rpc.call('source', 'main', {}, {signal: this.abort.signal});
46
47
  if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
47
48
  return this.src.mountMainSource(wire);
48
49
  } catch (error) {
@@ -61,7 +62,7 @@ export class Gramlot {
61
62
  try { this.src.binding.dispose(); }
62
63
  finally { this.src.renderer.dispose(); }
63
64
  } finally {
64
- if (this.rpc.transport instanceof MainTransport) this.rpc.transport.close(this.pageId, {beacon});
65
+ if (this.rpc.transport instanceof HttpTransport) this.rpc.transport.close(this.pageId, {beacon});
65
66
  this.rpc.transport?.dispose?.();
66
67
  }
67
68
  }
@@ -1,21 +1,58 @@
1
1
  /**
2
- * The exchange of one Gramlot page with the host (`gramlot.rpc`).
2
+ * The exchange of one Gramlot page with the server (`gramlot.rpc`).
3
3
  *
4
4
  * @module
5
5
  */
6
6
  import type {SourceBagNode} from '@genrojs/builders';
7
7
  import type {DomDocument} from '../dom.d.ts';
8
8
  import type {Gramlot} from '../gramlot.js';
9
- import type {MainTransport} from '../transport.js';
9
+ import type {HttpTransport} from '../http-transport.js';
10
10
  import {Handler} from './handler.js';
11
11
 
12
- /** The exchange with the host. */
12
+ /** The transport contract of `RpcHandler`: one envelope text in, one envelope text out. */
13
+ export interface RpcTransport {
14
+ /** Send the request envelope text; resolves with the response envelope text. */
15
+ call(text: string, signal?: AbortSignal): Promise<string>;
16
+ /** Ask the server to close the page. */
17
+ close?(pageId: string, options?: {beacon?: boolean}): void;
18
+ /** Release the transport on dispose. */
19
+ dispose?(): void;
20
+ }
21
+
22
+ /** The error outcome of a response envelope. */
23
+ export interface RpcErrorOutcome {
24
+ /** The outcome code (`page_expired`, `not_found`, `not_authenticated`, `not_authorized`, `application_error`). */
25
+ code: string;
26
+ /** The class name of the server exception. */
27
+ name: string;
28
+ /** The message of the server exception. */
29
+ message: string;
30
+ /** The server traceback, with `GRAMLOT_DEV=DEBUG`. */
31
+ details?: string;
32
+ }
33
+
34
+ /** An error outcome answered by the server inside the response envelope. */
35
+ export class RpcError extends Error {
36
+ /** The outcome code. */
37
+ code: string;
38
+ /** The class name of the server exception. */
39
+ remoteName: string;
40
+ /** The server traceback, when the server sent it. */
41
+ details?: string;
42
+ /** Create the error from the `error` field of a response envelope. */
43
+ constructor(outcome: RpcErrorOutcome);
44
+ }
45
+
46
+ /** The exchange with the server. */
13
47
  export class RpcHandler extends Handler {
14
48
  /** The server transport, or null. */
15
- transport: MainTransport | null;
49
+ transport: RpcTransport | null;
16
50
  /** The remote Source requests in progress, by target node. */
17
51
  remoteRequests: Map<SourceBagNode, {controller: AbortController}>;
18
- /** Create the transport of `gramlot`: the given one, none for `false`, else a `MainTransport` on the URLs. */
19
- constructor(gramlot: Gramlot, options: {mainUrl: string; sourceUrl: string; closeUrl: string; document: DomDocument;
20
- transport?: MainTransport | false | null});
52
+ /** Create the transport of `gramlot`: the given one, none for `false`, else an `HttpTransport` on the URLs. */
53
+ constructor(gramlot: Gramlot, options: {rpcUrl: string; closeUrl: string; document: DomDocument;
54
+ transport?: RpcTransport | HttpTransport | false | null});
55
+ /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an `RpcError`. */
56
+ call(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>,
57
+ options?: {signal?: AbortSignal}): Promise<unknown>;
21
58
  }
@@ -1,18 +1,45 @@
1
1
  /* @ts-self-types="./rpc-handler.d.ts" */
2
2
  /**
3
- * The exchange of one Gramlot page with the host (`gramlot.rpc`).
3
+ * The exchange of one Gramlot page with the server (`gramlot.rpc`).
4
4
  *
5
5
  * @module
6
6
  */
7
+ import {fromTytx, toTytx} from '@genrojs/tytx';
7
8
  import {Handler} from './handler.js';
8
- import {MainTransport} from '../transport.js';
9
+ import {HttpTransport} from '../http-transport.js';
9
10
 
10
- /** The exchange with the host. */
11
+ /** A request id: 16 random bytes as 32 hex characters; getRandomValues, unlike randomUUID,
12
+ * exists outside secure contexts too. */
13
+ const requestId = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),
14
+ byte => byte.toString(16).padStart(2, '0')).join('');
15
+
16
+ /** An error outcome answered by the server inside the response envelope. */
17
+ export class RpcError extends Error {
18
+ name = 'RpcError';
19
+ constructor({code, name, message, details}) {
20
+ super(message);
21
+ this.code = code;
22
+ this.remoteName = name;
23
+ if (details !== undefined) this.details = details;
24
+ }
25
+ }
26
+
27
+ /** The exchange with the server. */
11
28
  export class RpcHandler extends Handler {
12
- constructor(gramlot, {mainUrl, sourceUrl, closeUrl, document, transport}) {
29
+ constructor(gramlot, {rpcUrl, closeUrl, document, transport}) {
13
30
  super(gramlot);
14
31
  this.transport = transport === false ? null : transport ??
15
- new MainTransport(mainUrl, undefined, sourceUrl, closeUrl, document.defaultView.navigator);
32
+ new HttpTransport(rpcUrl, {closeUrl, navigator: document.defaultView.navigator});
16
33
  this.remoteRequests = new Map();
17
34
  }
35
+ /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
36
+ async call(contentType, name, params = {}, {signal} = {}) {
37
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
38
+ const id = requestId();
39
+ const text = toTytx({id, pageId: this.gramlot.pageId, contentType, name, params});
40
+ const response = fromTytx(await this.transport.call(text, signal));
41
+ if (response.id !== id) throw new Error('rpc response id mismatch');
42
+ if (response.error) throw new RpcError(response.error);
43
+ return response.value;
44
+ }
18
45
  }