@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
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type {BeaconNavigator} from './dom.d.ts';
6
+ import type {BeaconNavigator, DomXMLHttpRequestClass} from './dom.d.ts';
7
7
 
8
8
  /** The fetch function used by the transport. */
9
9
  export type Fetcher = (input: string, init?: RequestInit) => Promise<Response>;
@@ -18,10 +18,19 @@ export class HttpTransport {
18
18
  closeUrl: string;
19
19
  /** The navigator whose `sendBeacon` sends the close request on page hide. */
20
20
  navigator: BeaconNavigator;
21
+ /** The XMLHttpRequest class of the window, used by `callSync`. */
22
+ XMLHttpRequest: DomXMLHttpRequestClass;
21
23
  /** Create a transport on the rpc URL of the page. */
22
- constructor(rpcUrl: string, options?: {fetcher?: Fetcher; closeUrl?: string; navigator?: BeaconNavigator});
24
+ constructor(rpcUrl: string, options?: {fetcher?: Fetcher; closeUrl?: string; navigator?: BeaconNavigator;
25
+ XMLHttpRequest?: DomXMLHttpRequestClass});
26
+ /** True: HTTP sends a synchronous call with a synchronous XMLHttpRequest. */
27
+ readonly supportsCallSync: true;
23
28
  /** POST the request envelope text; resolves with the response envelope text, rejects on a non-200 status. */
24
29
  call(text: string, signal?: AbortSignal): Promise<string>;
30
+ /** POST the request envelope text with a synchronous XMLHttpRequest; the response envelope text, or a throw on a non-200 status. Blocks the page while it waits. */
31
+ callSync(text: string): string;
25
32
  /** Ask the server to close the page, with a beacon or a best-effort fetch; delivery failure is ignored. */
26
33
  close(pageId: string, options?: {beacon?: boolean}): void;
34
+ /** Release the transport at the dispose of the page; HTTP holds no connection, so nothing is released. */
35
+ dispose(): void;
27
36
  }
@@ -7,11 +7,16 @@
7
7
  /** The page-to-server transport over HTTP: sends the envelope to the rpc URL and closes the server page. */
8
8
  export class HttpTransport {
9
9
  constructor(rpcUrl, {fetcher = globalThis.fetch?.bind(globalThis), closeUrl = '/gramlot/close',
10
- navigator = globalThis.navigator} = {}) {
10
+ navigator = globalThis.navigator, XMLHttpRequest = globalThis.XMLHttpRequest} = {}) {
11
11
  this.rpcUrl = rpcUrl;
12
12
  this.fetcher = fetcher;
13
13
  this.closeUrl = closeUrl;
14
14
  this.navigator = navigator;
15
+ this.XMLHttpRequest = XMLHttpRequest;
16
+ }
17
+ /** HTTP sends a synchronous call (`callSync`) with a synchronous XMLHttpRequest. */
18
+ get supportsCallSync() {
19
+ return true;
15
20
  }
16
21
  async call(text, signal) {
17
22
  const response = await this.fetcher(this.rpcUrl, {
@@ -22,20 +27,35 @@ export class HttpTransport {
22
27
  if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
23
28
  return response.text();
24
29
  }
30
+ /**
31
+ * POST the request envelope text with a synchronous XMLHttpRequest and return the response envelope text;
32
+ * a non-200 status throws. Browsers deprecate the synchronous request on the main thread: the page is
33
+ * blocked until the answer arrives.
34
+ */
35
+ callSync(text) {
36
+ const request = new this.XMLHttpRequest();
37
+ request.open('POST', this.rpcUrl, false);
38
+ request.setRequestHeader('Content-Type', 'application/json');
39
+ request.send(text);
40
+ if (request.status !== 200) throw new Error(`rpc failed: HTTP ${request.status}`);
41
+ return request.responseText;
42
+ }
43
+ /**
44
+ * Send the close message `{pageId}` without waiting for the answer: a beacon on page hide, else a
45
+ * `keepalive` POST. A failed delivery leaves the page to the server TTL; local disposal does not wait.
46
+ */
25
47
  close(pageId, {beacon = false} = {}) {
26
48
  const body = JSON.stringify({pageId});
27
49
  if (beacon) {
28
- try {
29
- this.navigator.sendBeacon(this.closeUrl, new Blob([body], {type: 'application/json'}));
30
- } catch { /* TTL handles delivery failure. */ }
50
+ this.navigator.sendBeacon(this.closeUrl, new Blob([body], {type: 'application/json'}));
31
51
  } else {
32
- // Server cleanup is best effort; local disposal must complete offline.
33
- try {
34
- Promise.resolve(this.fetcher(this.closeUrl, {
35
- method: 'POST', credentials: 'same-origin', keepalive: true,
36
- headers: {'Content-Type': 'application/json'}, body,
37
- })).catch(() => {});
38
- } catch { /* TTL handles delivery failure. */ }
52
+ this.fetcher(this.closeUrl, {
53
+ method: 'POST', credentials: 'same-origin', keepalive: true,
54
+ headers: {'Content-Type': 'application/json'}, body,
55
+ });
39
56
  }
40
57
  }
58
+ /** Release the transport at the dispose of the page: HTTP holds no connection, so nothing is released. The
59
+ * calls in flight are aborted by the page (`RpcHandler.call`). */
60
+ dispose() {}
41
61
  }
@@ -249,7 +249,7 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
249
249
  const source = node(pane);
250
250
  const savedWidth = preferences[widthProperty];
251
251
  if (typeof savedWidth === 'number' && Number.isFinite(savedWidth) && savedWidth > 0) set(pane, {width: `${savedWidth}px`});
252
- const handle = gramlot.subscribe(`${source.getAttr('node_id')}_closable_change`, ({open}) => {
252
+ const handle = gramlot.subscribe(`${source.getAttr('nodeId')}_closable_change`, ({open}) => {
253
253
  if (source.getAttr('hidden') === true || source.getAttr('drawer') === false) return;
254
254
  state.setItem(property, open);
255
255
  set(pane, {drawer: open ? true : 'close'});
@@ -260,7 +260,7 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
260
260
  releases.push(() => gramlot.unsubscribe(handle));
261
261
  }
262
262
  const border = shell.querySelector('[data-index-regions]');
263
- const handle = gramlot.subscribe(`${node(border).getAttr('node_id')}_splitter_resize`, ({region, size}) => {
263
+ const handle = gramlot.subscribe(`${node(border).getAttr('nodeId')}_splitter_resize`, ({region, size}) => {
264
264
  set(region === 'left' ? sidebar : codeSidebar, {width: size});
265
265
  state.setItem(region === 'left' ? 'preferredSidebarWidth' : 'preferredCodeWidth', Number.parseFloat(size));
266
266
  savePreferences();
package/src/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The browser entry point of Gramlot: declarative HTML and SVG interfaces with live data binding.
3
3
  * It exports the page instance (`Gramlot`), the bootstrap that starts it, the builder and the
4
- * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
4
+ * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag`, `BagNode` and `createDecimal` from the Bag and TYTX libraries.
5
5
  *
6
6
  * @module
7
7
  */
@@ -14,15 +14,17 @@ export {UtilitiesHandler} from './handlers/utilities-handler.js';
14
14
  export type {GramlotOptions, GramlotState, Publication, SubscriptionHandle, FormatOptions} from './gramlot.js';
15
15
  export {PageBootstrap} from './bootstrap.js';
16
16
  export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
17
- export {Page} from './server/page.js';
17
+ export {Exposed, Page} from './server/page.js';
18
18
  export {GramlotBuilder} from './builder/gramlot-builder.js';
19
19
  export {GramlotRenderer} from './renderer/gramlot-renderer.js';
20
20
  export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
21
21
  export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
22
22
  export {Bag, BagNode} from '@genrojs/bag';
23
+ export {createDecimal} from '@genrojs/tytx';
23
24
  export {References} from './references.js';
24
25
  export type {SourceReference} from './references.js';
25
26
  export {HttpTransport} from './http-transport.js';
27
+ export {ServerAdapter} from './server-adapter.js';
26
28
  export type {Fetcher} from './http-transport.js';
27
29
  export {RpcError} from './handlers/rpc-handler.js';
28
30
  export type {RpcErrorOutcome, RpcTransport} from './handlers/rpc-handler.js';
package/src/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * The browser entry point of Gramlot: declarative HTML and SVG interfaces with live data binding.
4
4
  * It exports the page instance (`Gramlot`), the bootstrap that starts it, the builder and the
5
- * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
5
+ * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag`, `BagNode` and `createDecimal` from the Bag and TYTX libraries.
6
6
  *
7
7
  * @module
8
8
  */
@@ -14,14 +14,18 @@ export {DomHandler} from './handlers/dom-handler.js';
14
14
  export {UtilitiesHandler} from './handlers/utilities-handler.js';
15
15
  export {PageBootstrap} from './bootstrap.js';
16
16
  // A page module served for its Logic imports @gramlot/gramlot/page; the bootstrap import map points it here.
17
- export {Page} from './server/page.js';
17
+ export {Exposed, Page} from './server/page.js';
18
18
  export {GramlotBuilder} from './builder/gramlot-builder.js';
19
19
  export {GramlotRenderer} from './renderer/gramlot-renderer.js';
20
20
  export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
21
21
  export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
22
22
  export {Bag, BagNode} from '@genrojs/bag';
23
+ // createDecimal and Bag are the typed literals of a page module, as in server/page.js: the import map of the browser
24
+ // resolves @gramlot/gramlot/page to this entry only.
25
+ export {createDecimal} from '@genrojs/tytx';
23
26
  export {References} from './references.js';
24
27
  export {HttpTransport} from './http-transport.js';
28
+ export {ServerAdapter} from './server-adapter.js';
25
29
  export {RpcError} from './handlers/rpc-handler.js';
26
30
  export {InOut} from './inout.js';
27
31
 
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The random id of the browser runtime.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ /**
8
+ * 16 random bytes as 32 lowercase hex characters, the format of the Python `uuid4().hex` ids of the server.
9
+ * `getRandomValues`, unlike `randomUUID`, exists outside secure contexts too.
10
+ */
11
+ export function randomId() {
12
+ return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),
13
+ byte => byte.toString(16).padStart(2, '0')).join('');
14
+ }
@@ -11,7 +11,7 @@ export const SVG_NS = 'http://www.w3.org/2000/svg';
11
11
  const BINDING_ATTRIBUTES = new Set([
12
12
  'default', 'default_value', 'live', 'group', 'visible', 'action', 'fire', 'ask', '_ask', '_ask_if', '_ask_title', '_ask_onCancel',
13
13
  'if', 'else', '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
14
- 'remote', '_cachedRemote', '_onRemote', 'onClose',
14
+ 'remote', '_cachedRemote', '_onRemote', '_onCalling', 'onClose',
15
15
  ]);
16
16
  const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on', 'subscribe_', 'selfsubscribe_', 'formsubscribe_', 'remote_'];
17
17
 
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {HtmlBuilder, HtmlRenderer, SvgBuilder, sourceAttributeItems} from '@genrojs/builders';
7
+ import {HtmlBuilder, HtmlRenderer, SourceBag, SvgBuilder, sourceAttributeItems} from '@genrojs/builders';
8
8
  import {GramlotSvgRenderer} from './gramlot-svg-renderer.js';
9
9
  import {webcomponentCode} from '../webcomponent.js';
10
10
  import {
@@ -31,18 +31,27 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
31
31
  /** HTML nodes (GramlotBuilder, HtmlBuilder) → this renderer; SVG nodes → one GramlotSvgRenderer owned by it. */
32
32
  getRender(builder) {
33
33
  if (!this.renders.has(builder)) {
34
- // HTML/SVG subbuilders share the page's expression hook and compiler.
35
- builder.evaluatePointerExpression = this.builder.evaluatePointerExpression.bind(this.builder);
36
34
  if (builder instanceof HtmlBuilder) this.addRender(builder, this);
37
35
  else if (builder instanceof SvgBuilder) this.addRender(builder, new GramlotSvgRenderer(builder, this));
38
36
  }
39
37
  return super.getRender(builder);
40
38
  }
41
39
 
42
- /** A data-element renders nothing: recognized before runtimeValues (R08, revision 10). */
40
+ /**
41
+ * Builder's walk of one node (RendererBase.render), with its values resolved by the root builder of the
42
+ * Source: the page's GramlotBuilder, whose `evaluatePointerExpression` compiles the `:=` expressions.
43
+ * The library builder of a sub-builder node (SVG, HTML inside SVG) shares the Data but has no page
44
+ * hook: its `runtimeValues` computes no expression. The node's own builder still validates its
45
+ * dialect values and its own renderer writes its attributes. A data-element renders nothing: recognized
46
+ * before runtimeValues (R08, revision 10); Gramlot grammars declare no Builder `@component`.
47
+ */
43
48
  render(node, opts = {}) {
44
49
  if (node._getMeta('data_element')) return null;
45
- return super.render(node, opts);
50
+ const [item, runtimeAttrs] = node.rootBuilder.runtimeValues(node);
51
+ const renderer = this.getRender(node.builder);
52
+ let [tag, attrs] = renderer._handleMeta(node, runtimeAttrs);
53
+ if (!node._getMeta('subbuilder')) attrs = renderer.adaptAttrs(attrs);
54
+ return renderer.renderedItem(node, node.value instanceof SourceBag ? this.renderChildren(node.value, opts) : item, attrs, {tag, ...opts});
46
55
  }
47
56
 
48
57
  /**
@@ -10,6 +10,7 @@ import {ControlAdapter, RadioGroups, SelectControl} from '../view/controls.js';
10
10
  import {ButtonBinding} from '../view/button.js';
11
11
  import {NativeEventBinding} from '../view/events.js';
12
12
  import {References} from '../references.js';
13
+ import {randomId} from '../random-id.js';
13
14
  import {GramlotBuilderBag, GramlotBuilderBagNode} from '../builder/source.js';
14
15
  import {BindingRuntime} from '../binding/runtime.js';
15
16
  import {requireInstallable} from '../binding/installation.js';
@@ -52,8 +53,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
52
53
  this.disposed = false;
53
54
  this.elements = new WeakMap();
54
55
  // The instance id scopes the generated radio names to this page (P11, S11).
55
- this.instanceId = Array.from(crypto.getRandomValues(new Uint8Array(16)),
56
- byte => byte.toString(16).padStart(2, '0')).join('');
56
+ this.instanceId = randomId();
57
57
  this.radioGroups = new RadioGroups(this);
58
58
  this.subscription = `html-source-renderer-${this.instanceId}`;
59
59
  source.subscribe(this.subscription, {any: event => this.receive(event)});
@@ -479,7 +479,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
479
479
  if (!record?.element) return;
480
480
  const renderer = this.getRender(node.builder);
481
481
  const previousDefaults = this.#presentationDefaults.get(node);
482
- const [value, runtimeAttrs] = node.builder.runtimeValues(node);
482
+ const [value, runtimeAttrs] = node.rootBuilder.runtimeValues(node);
483
483
  const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
484
484
  const resolved = this.#resolvedAttributes.get(node);
485
485
  if (record.shape !== ControlAdapter.shape(record.element, resolved)) {
@@ -5,5 +5,7 @@
5
5
  */
6
6
 
7
7
  /** Run the checks of GC-230 §150 against the adapter at `baseUrl` (mount prefix included) with the page
8
- * `pagePath`; reject with an `AssertionError` naming the rule of the first failure. */
9
- export function checkProtocol(baseUrl: string, pagePath: string): Promise<void>;
8
+ * `pagePath`; reject with an `AssertionError` naming the rule of the first failure. `pageTtl` is the `pageTtl`
9
+ * in seconds of the server of the adapter, short for the check to be fast; with it the check also waits for the
10
+ * renewal and the expiry of a page (GC-230 §010), about 2.5 times `pageTtl`, and without it that check is left out. */
11
+ export function checkProtocol(baseUrl: string, pagePath: string, options?: {pageTtl?: number | null}): Promise<void>;
@@ -9,6 +9,7 @@ import {isDeepStrictEqual} from 'node:util';
9
9
  import {fromTytx, toTytx} from '@genrojs/tytx';
10
10
 
11
11
  const OWNER_COOKIE = 'gramlot_owner';
12
+ const BOM = Buffer.from([0xef, 0xbb, 0xbf]);
12
13
  const BOOTSTRAP = /<script type="module" nonce="([^"]+)">import \{PageBootstrap\} from ("[^"]*");await new PageBootstrap\((\{.*?\})\)\.run\(\);<\/script>/;
13
14
 
14
15
  const expect = (rule, condition, message) => {
@@ -17,17 +18,23 @@ const expect = (rule, condition, message) => {
17
18
 
18
19
  const mediaType = headers => (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
19
20
 
21
+ const sleep = seconds => new Promise(done => setTimeout(done, seconds * 1000));
22
+
20
23
  /** Run the checks of GC-230 §150 against the adapter at baseUrl (mount prefix included) with
21
- * the page pagePath; throw an AssertionError naming the rule of the first failure. The Python
22
- * counterpart is src/gramlot/server/conformance.py: both run the same list in the same order. */
23
- export async function checkProtocol(baseUrl, pagePath) {
24
+ * the page pagePath; throw an AssertionError naming the rule of the first failure. pageTtl is the
25
+ * `pageTtl` in seconds of the server of the adapter, short for the check to be fast; with it the check
26
+ * also waits for the renewal and the expiry of a page (GC-230 §010), about 2.5 times pageTtl, and without
27
+ * it that check is left out. The Python counterpart is src/gramlot/server/conformance.py: both run the
28
+ * same list in the same order. */
29
+ export async function checkProtocol(baseUrl, pagePath, {pageTtl = null} = {}) {
24
30
  const base = new URL(baseUrl);
25
31
  const prefix = base.pathname.replace(/\/+$/, '');
26
32
  let owner = null;
27
33
 
28
- const request = async (method, path, {body = null, contentType = 'application/json', withOwner = true} = {}) => {
34
+ const request = async (method, path, {body = null, contentType = 'application/json', withOwner = true,
35
+ ownerValue = null} = {}) => {
29
36
  const headers = body === null ? {} : {'Content-Type': contentType};
30
- if (withOwner && owner !== null) headers.Cookie = `${OWNER_COOKIE}=${owner}`;
37
+ if (withOwner && owner !== null) headers.Cookie = `${OWNER_COOKIE}=${ownerValue ?? owner}`;
31
38
  const response = await fetch(base.origin + path, {method, body, headers, redirect: 'manual'});
32
39
  return {status: response.status, headers: response.headers, body: await response.text()};
33
40
  };
@@ -52,6 +59,9 @@ export async function checkProtocol(baseUrl, pagePath) {
52
59
  expect('GC-230-115', typeof config.rpcUrl === 'string' && typeof config.closeUrl === 'string'
53
60
  && Array.isArray(config.capabilities),
54
61
  `bootstrap config ${JSON.stringify(config)} lacks rpcUrl, closeUrl or a capabilities array`);
62
+ const syntax = config.nameSyntax;
63
+ expect('GC-230-010', syntax?.kind === 'regex' && typeof syntax.pattern === 'string' && Number.isInteger(syntax.flags),
64
+ `bootstrap config nameSyntax ${JSON.stringify(syntax)} is not {kind: 'regex', pattern, flags}`);
55
65
  const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], rpc: [config.rpcUrl, '/gramlot/rpc'],
56
66
  close: [config.closeUrl, '/gramlot/close']};
57
67
  for (const [name, [url, path]] of Object.entries(expected)) {
@@ -91,8 +101,13 @@ export async function checkProtocol(baseUrl, pagePath) {
91
101
 
92
102
  response = await request('GET', `${prefix}/gramlot-conformance-missing-page`);
93
103
  expect('GC-230-115', response.status === 404, `an unknown page answers ${response.status}, not 404`);
94
- response = await request('POST', pageUrl, {body: '{}'});
95
- expect('GC-230-115', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
104
+ for (const method of ['POST', 'HEAD', 'PUT', 'DELETE', 'PATCH']) {
105
+ response = await request(method, pageUrl, {body: method === 'HEAD' ? null : '{}'});
106
+ const allow = response.headers.get('allow');
107
+ const allowed = (allow ?? '').split(',').map(item => item.trim());
108
+ expect('GC-230-115', response.status === 405 && allowed.includes('GET') && !allowed.includes(method),
109
+ `${method} ${pageUrl} answers ${response.status} with Allow ${JSON.stringify(allow)}, not 405 with Allow: GET`);
110
+ }
96
111
  if (pagePath.endsWith('/')) {
97
112
  response = await request('GET', `${pageUrl}index.html`);
98
113
  expect('GC-230-115', response.status === 200 && mediaType(response.headers) === 'text/html',
@@ -142,6 +157,15 @@ export async function checkProtocol(baseUrl, pagePath) {
142
157
  expect('GC-230-125', response.status === 200 && isDeepStrictEqual(parse(response.body, JSON.parse), {ok: true}),
143
158
  `close as ${contentType} answers ${response.status} ${response.body.slice(0, 200)}, not 200 {"ok": true}`);
144
159
  }
160
+ // A leading byte order mark is removed by the decoding of the body (GC-230 §120).
161
+ response = await request('POST', rpc, {body: Buffer.concat([BOM,
162
+ Buffer.from(toTytx(envelope('data', 'check_endpoint', {value: 'bom'})))])});
163
+ expect('GC-230-120', response.status === 200 && parse(response.body, fromTytx)?.value === 'bom',
164
+ `rpc with a leading byte order mark answers ${response.status} ${response.body.slice(0, 200)}, not the endpoint value`);
165
+ response = await request('POST', config.closeUrl, {body: Buffer.concat([BOM,
166
+ Buffer.from(JSON.stringify({pageId: '0'.repeat(32)}))])});
167
+ expect('GC-230-125', response.status === 200 && isDeepStrictEqual(parse(response.body, JSON.parse), {ok: true}),
168
+ `close with a leading byte order mark answers ${response.status} ${response.body.slice(0, 200)}, not 200 {"ok": true}`);
145
169
  response = await request('POST', rpc, {body: '{'});
146
170
  expect('GC-230-120', response.status === 400, `rpc with invalid JSON answers ${response.status}, not 400`);
147
171
  const {pageId: omitted, ...withoutPageId} = envelope('source', 'main');
@@ -159,16 +183,32 @@ export async function checkProtocol(baseUrl, pagePath) {
159
183
  && received?.id === sent.id && received?.contentType === 'source' && typeof received?.value === 'string',
160
184
  `main answers ${response.status} ${response.headers.get('content-type')} ${response.body.slice(0, 200)}, not 200 `
161
185
  + 'application/json with an envelope echoing id and contentType and carrying the fragment document as a string');
186
+ // The page belongs to the browser that opened it: a request without its cookies, or with another owner,
187
+ // reaches it only as page_expired, and its close message leaves the page open.
188
+ await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main without the cookies of the page',
189
+ {withOwner: false});
162
190
  if (owner !== null) {
163
- await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main without the owner cookie',
164
- {withOwner: false});
191
+ await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main with another owner cookie',
192
+ {ownerValue: `${owner}x`});
165
193
  }
194
+ response = await request('POST', config.closeUrl, {body: JSON.stringify({pageId}), withOwner: false});
195
+ expect('GC-230-135', response.status === 200, `close without the cookies of the page answers ${response.status}, not 200`);
196
+ response = await call(envelope('data', 'check_endpoint', {value: 'owned'}));
197
+ expect('GC-230-135', response.status === 200 && response.received?.value === 'owned',
198
+ `after a close without the cookies of the page, check_endpoint answers ${response.status} `
199
+ + `${response.body.slice(0, 200)}: the close of another owner closed the page`);
166
200
 
167
201
  await outcome('GC-230-025', envelope('source', 'main', {}, {pageId: '0'.repeat(32)}), 'page_expired',
168
202
  'main of an unknown page');
169
203
  await outcome('GC-230-025', envelope('source', 'gramlot_conformance_missing'), 'not_found', 'an unknown fragment');
170
204
  await outcome('GC-230-025', envelope('data', 'gramlot_conformance_missing'), 'not_found', 'an unknown endpoint');
171
205
  await outcome('GC-230-025', envelope('data', 'main'), 'not_found', 'data main');
206
+ // A method path never reaches a declared method through an inherited member.
207
+ await outcome('GC-230-025', envelope('data', 'constructor'), 'not_found', 'data constructor');
208
+ await outcome('GC-230-025', envelope('data', 'constructor.prototype.check_endpoint'), 'not_found',
209
+ 'data constructor.prototype.check_endpoint');
210
+ await outcome('GC-230-025', envelope('source', 'constructor.prototype.check_fragment'), 'not_found',
211
+ 'source constructor.prototype.check_fragment');
172
212
 
173
213
  response = await call(envelope('source', 'check_fragment', {text: 'gramlot-conformance'}));
174
214
  const fragment = parse(response.body, JSON.parse)?.value;
@@ -213,4 +253,25 @@ export async function checkProtocol(baseUrl, pagePath) {
213
253
  expect('GC-230-125', response.status === 200 && mediaType(response.headers) === 'application/json' && isDeepStrictEqual(closed, {ok: true}),
214
254
  `close answers ${response.status} ${response.body}, not 200 {"ok": true}`);
215
255
  await outcome('GC-230-125', envelope('source', 'main'), 'page_expired', 'main after close');
256
+
257
+ if (pageTtl !== null) {
258
+ // A page opened now, used at 0.5 pageTtl and again at 1.2 pageTtl after its opening (0.7 after the first use,
259
+ // which only the renewal by the first use lets succeed), then left idle for 1.3 pageTtl (GC-230 §010).
260
+ response = await request('GET', pageUrl);
261
+ const opened = BOOTSTRAP.exec(response.body);
262
+ expect('GC-230-115', response.status === 200 && opened !== null,
263
+ `GET ${pageUrl} answers ${response.status} without a bootstrap`);
264
+ const timed = envelope('data', 'check_endpoint', {value: 'used'}, {pageId: JSON.parse(opened[3]).config.pageId});
265
+ const timedCall = async label => {
266
+ response = await call({...timed, id: crypto.randomUUID()});
267
+ expect('GC-230-010', response.status === 200 && response.received?.value === 'used',
268
+ `${label}, check_endpoint answers ${response.status} ${response.body.slice(0, 200)}, not the endpoint value`);
269
+ };
270
+ await sleep(pageTtl * 0.5);
271
+ await timedCall('a call at 0.5 pageTtl after the opening');
272
+ await sleep(pageTtl * 0.7);
273
+ await timedCall('a call at 1.2 pageTtl after the opening, 0.7 pageTtl after the previous call');
274
+ await sleep(pageTtl * 1.3);
275
+ await outcome('GC-230-010', timed, 'page_expired', 'a call 1.3 pageTtl after the previous call');
276
+ }
216
277
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * File lookup of the Node.js and Bun servers, shared by `GramlotServer` (the core themes) and
3
+ * `GramlotFileServer` (the pages folder). The Python counterpart is src/gramlot/server/files.py.
4
+ * It imports Node.js modules: `GramlotServer` loads it on first use, so the Worker bundle of the
5
+ * neutral server holds no Node.js import.
6
+ *
7
+ * @module
8
+ */
9
+ import {realpath, stat} from 'node:fs/promises';
10
+ import {isAbsolute, join, relative, sep} from 'node:path';
11
+ import {fileURLToPath} from 'node:url';
12
+
13
+ /** The themes folder of the installed core (the `themes` folder of the npm package). */
14
+ export const THEMES = fileURLToPath(new URL('../../themes/', import.meta.url));
15
+
16
+ /** Whether `filename` is `folder` or below it. */
17
+ export const inside = (filename, folder) => {
18
+ const rel = relative(folder, filename);
19
+ return rel === '' || !(rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel));
20
+ };
21
+
22
+ /** Real path of filename, or null when it does not exist. */
23
+ export async function realFile(filename) {
24
+ try {
25
+ const real = await realpath(filename);
26
+ return (await stat(real)).isFile() ? real : null;
27
+ } catch (error) {
28
+ if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ /** The real path of the `/`-separated `path` below `folder` when it is a file whose real path stays inside the
34
+ * real `folder`, else null; a path with a NUL character names no file. */
35
+ export async function fileBelow(folder, path) {
36
+ if (path.includes('\0')) return null;
37
+ const root = await realpath(folder);
38
+ const real = await realFile(join(root, ...path.split('/').filter(Boolean)));
39
+ return real && inside(real, root) ? real : null;
40
+ }
@@ -32,6 +32,8 @@ export class GramlotFileServer extends GramlotServer {
32
32
  resolvePage(path: string): Promise<typeof Page>;
33
33
  /** `Page.css` URLs as written, then the companion CSS and the page logic. */
34
34
  resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
35
+ /** The file of a `.css` or `.js` URL path whose real path is a file below the pages folder, or null. */
36
+ companionFile(path: string): Promise<string | null>;
35
37
  /** Root-relative URL of a file below the pages folder; a file that leaves the folder raises. */
36
38
  url(filename: string): Promise<string>;
37
39
  }
@@ -5,38 +5,27 @@
5
5
  * @module
6
6
  */
7
7
  import {realpath, stat} from 'node:fs/promises';
8
- import {basename, dirname, extname, isAbsolute, join, relative, resolve, sep} from 'node:path';
8
+ import {basename, dirname, extname, join, relative, resolve, sep} from 'node:path';
9
9
  import {pathToFileURL} from 'node:url';
10
10
  import {gramlotDev} from './assets.js';
11
+ import {fileBelow, inside, realFile} from './files.js';
11
12
  import {GramlotServer, PageNotFound} from './gramlot-server.js';
12
13
  import {InvalidResourceName, SEGMENT, parseRequires} from './resources.js';
13
14
 
14
- const inside = (filename, folder) => {
15
- const rel = relative(folder, filename);
16
- return rel === '' || !(rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel));
17
- };
18
-
19
15
  // RFC 3986 unreserved characters stay literal, as with Python urllib.parse.quote(safe='').
20
16
  const encodeSegment = segment => encodeURIComponent(segment)
21
17
  .replace(/[!'()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
22
18
 
23
- /** Real path of filename, or null when it does not exist. */
24
- async function realFile(filename) {
25
- try {
26
- const real = await realpath(filename);
27
- return (await stat(real)).isFile() ? real : null;
28
- } catch (error) {
29
- if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
30
- throw error;
31
- }
32
- }
19
+ // The URL suffixes of the files below the pages folder that reach the browser (GC-230 §145).
20
+ const COMPANION_SUFFIXES = ['.css', '.js'];
33
21
 
34
22
  /** Minimal reference GramlotServer on one pages folder, with APIs shared by Node.js and Bun.
35
23
  * The Python counterpart is src/gramlot/server/gramlot_file_server.py. Page path foo: the
36
24
  * file page foo.js first, then the folder page foo/foo.js; the file wins when both
37
25
  * exist. Beside the page file: foo.css (CSS) and foo.md (README). The page logic
38
26
  * (group null) is the Logic export of the page module itself, else foo_aux.js
39
- * (JS module exporting Logic); both at once raise an Error. The page module then
27
+ * (a JS module whose Logic export, when present, holds the methods); both at once
28
+ * raise an Error. The page module then
40
29
  * reaches the browser, so its imports must resolve there too. The _aux suffix is
41
30
  * reserved. There are
42
31
  * no resource levels: a name in css_requires/js_requires raises
@@ -44,7 +33,9 @@ async function realFile(filename) {
44
33
  * the runtime module cache applies, keyed by the real path
45
34
  * of the page module; with reload the page module is imported again
46
35
  * when its modification time changes. reload null takes the value from GRAMLOT_DEV
47
- * (true for YES and DEBUG, false when unset); an explicit boolean wins.
36
+ * (true for YES and DEBUG, false when unset); an explicit boolean wins. companionFile is the file an
37
+ * adapter serves at the .css and .js URLs of GC-230 §145 (themeFile, the file of the /themes/ URLs, is
38
+ * the one of GramlotServer); the adapter adds the HTTP part (methods, media types, headers).
48
39
  */
49
40
  export class GramlotFileServer extends GramlotServer {
50
41
  constructor(pagesDir, {reload = null, ...options} = {}) {
@@ -107,6 +98,15 @@ export class GramlotFileServer extends GramlotServer {
107
98
  return {css, js};
108
99
  }
109
100
 
101
+ /** The file of the URL path `path` (mount prefix removed, percent-decoded) when it ends in .css or
102
+ * .js and its real path is a file below the pages folder: page modules, companions (foo.css,
103
+ * foo_aux.js) and Page.css files placed there; else null. Any other file of the folder is never
104
+ * served (GC-230 §145). */
105
+ async companionFile(path) {
106
+ if (!COMPANION_SUFFIXES.some(suffix => path.endsWith(suffix))) return null;
107
+ return fileBelow(this.pagesDir, path);
108
+ }
109
+
110
110
  /** Root-relative URL of a file below the pages folder, one encoded segment per
111
111
  * folder; a file whose real path leaves the folder raises an Error. */
112
112
  async url(filename) {
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type {Page} from './page.js';
7
7
  import type {Resources} from './resources.js';
8
+ import type {NameSyntax, NameSyntaxDescriptor} from '../builder/name-syntax.js';
8
9
 
9
10
  export type {Resources};
10
11
 
@@ -54,12 +55,14 @@ export interface GramlotServerOptions {
54
55
  closeUrl?: string;
55
56
  /** Id of the root element of the page. */
56
57
  rootId?: string;
57
- /** Seconds a registered page lives. */
58
+ /** Seconds a page lives after its last use: opening it and each call that names it for its owner renew it. */
58
59
  pageTtl?: number;
59
60
  /** Maximum number of registered pages. */
60
61
  maxPages?: number;
61
62
  /** Application collections: generated Builder grammar and root-relative browser module URL. */
62
63
  collections?: {grammar: Record<string, unknown>; module: string}[];
64
+ /** The base theme of every page, a folder of the core themes, or false for none; default `gramlot-base`. */
65
+ cssTheme?: string | false;
63
66
  }
64
67
 
65
68
  /** The result of `registerPage`. */
@@ -73,6 +76,8 @@ export interface RegisteredPage {
73
76
  title: string;
74
77
  /** The resources of the page, in load order. */
75
78
  resources: Resources;
79
+ /** The name syntax of the server, as the bootstrap carries it. */
80
+ nameSyntax: NameSyntaxDescriptor;
76
81
  }
77
82
 
78
83
  /** The result of `openPage`. */
@@ -98,10 +103,12 @@ export class GramlotServer {
98
103
  closeUrl: string;
99
104
  /** Id of the root element of the page. */
100
105
  rootId: string;
101
- /** Seconds a registered page lives. */
106
+ /** Seconds a page lives after its last use: opening it and each call that names it for its owner renew it. */
102
107
  pageTtl: number;
103
108
  /** Maximum number of registered pages. */
104
109
  maxPages: number;
110
+ /** The base theme of every page, or false for none. */
111
+ cssTheme: string | false;
105
112
  /** The registered pages by id. */
106
113
  pages: Map<string, {PageClass: typeof Page; owner: unknown; expires: number}>;
107
114
  /** Create a server. */
@@ -113,16 +120,28 @@ export class GramlotServer {
113
120
  resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
114
121
  /** The capabilities announced in the bootstrap; none in the base server. */
115
122
  get capabilities(): string[];
116
- /** null when a target with `rule` may run for `owner`; the base server refuses any rule. */
117
- evaluateAuth(rule: string | null, options?: {owner?: unknown}): AuthOutcome;
123
+ /** The syntax of the method names a request may carry, announced in the bootstrap; the core default `NAME_SYNTAX`. */
124
+ get nameSyntax(): NameSyntax;
125
+ /** The URL of the module of the browser ServerAdapter class, or null for the HTTP ServerAdapter of the core. */
126
+ get serverAdapter(): string | null;
127
+ /** null when a target with `rule` may run for `owner` with the `identity` of the call; the base server refuses any rule. */
128
+ evaluateAuth(rule: string | null, options?: {owner?: unknown; identity?: unknown}): AuthOutcome;
118
129
  /** Drop the expired pages. */
119
130
  prune(): void;
120
- /** Register a page independently of its HTTP or Worker transport. */
131
+ /** The CSS URL of the theme of a page class, in an array, or an empty array. */
132
+ themeCss(PageClass: typeof Page): string[];
133
+ /** The file of a `/themes/<path>` URL path whose real path is a file of the core themes, or null. Node.js and Bun only. */
134
+ themeFile(path: string): Promise<string | null>;
135
+ /** Register a page independently of its HTTP or Worker transport; `<path>/index.html` registers `<path>/`. */
121
136
  registerPage(path: string, options?: {owner?: unknown}): Promise<RegisteredPage>;
122
137
  /** Register the page and return its bootstrap; `prefix` is the mount prefix added to root-relative URLs. */
123
138
  openPage(path: string, options?: {owner?: unknown; prefix?: string}): Promise<OpenedPage>;
124
- /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. */
125
- call(text: string, options?: {owner?: unknown}): Promise<string>;
139
+ /** The text of a request body: UTF-8, a leading byte order mark removed; other bytes throw `InvalidRequest`. */
140
+ decodeBody(data: ArrayBuffer | ArrayBufferView): string;
141
+ /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. `identity` is the identity of this call, read only by `evaluateAuth`. */
142
+ call(text: string, options?: {owner?: unknown; identity?: unknown}): Promise<string>;
143
+ /** Close the page named by the close message `text` (`{"pageId": string}` as JSON) when `owner` owns it; throws `InvalidRequest`. */
144
+ close(text: string, options?: {owner?: unknown}): void;
126
145
  /** Forget a registered page when `owner` owns it. */
127
146
  closePage(pageId: string, options?: {owner?: unknown}): void;
128
147
  /** Forget every registered page; adapters call it on shutdown. */