@gramlot/gramlot 0.2.12 → 0.2.15

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.
@@ -4,15 +4,42 @@
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';
10
+
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
+ }
9
26
 
10
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
  }
@@ -40,8 +40,8 @@ export class SourceHandler extends Handler {
40
40
  * Replace the children of one Source node with a remote Source, only after the incoming Source
41
41
  * validates. Resolves with true when applied, false when superseded or cancelled.
42
42
  *
43
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
44
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
43
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
44
+ * declarative `remote` grammar attribute is not yet available.
45
45
  */
46
46
  remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
47
47
  }
@@ -67,6 +67,8 @@ export class SourceHandler extends Handler {
67
67
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
68
68
  return wire.bindBuilder(builder).activateCode();
69
69
  }
70
+ // A source envelope decodes its value: anything but a SourceBag or a TYTX text is not a Source.
71
+ if (typeof wire !== 'string') throw new TypeError('Source value did not decode to SourceBag');
70
72
  const source = sourceBagFromTytx(wire, builder);
71
73
  if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
72
74
  return source.activateCode();
@@ -77,12 +79,12 @@ export class SourceHandler extends Handler {
77
79
  * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
78
80
  * or a freeze keeps it, the removal of the target cancels it.
79
81
  *
80
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
81
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
82
+ * `@source` / `registerSource` declare the fragments this method requests (GC-230 §035); the
83
+ * declarative `remote` grammar attribute is not yet available.
82
84
  */
83
85
  async remoteSource(target, method, params = {}) {
84
86
  const rpc = this.gramlot.rpc;
85
- if (!rpc.transport?.source) throw new Error('Remote Source is unavailable without a server transport');
87
+ if (!rpc.transport?.call) throw new Error('Remote Source is unavailable without a server transport');
86
88
  const binding = this.binding.bindingFor(target);
87
89
  if (this.gramlot.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
88
90
  rpc.remoteRequests.get(target)?.controller.abort();
@@ -93,7 +95,7 @@ export class SourceHandler extends Handler {
93
95
  const current = () => this.gramlot.state !== 'disposed' && !request.controller.signal.aborted &&
94
96
  rpc.remoteRequests.get(target) === request && !binding.closed;
95
97
  try {
96
- const wire = await rpc.transport.source(this.gramlot.pageId, method, params, request.controller.signal);
98
+ const wire = await rpc.call('source', method, params, {signal: request.controller.signal});
97
99
  if (!current()) return false;
98
100
  const prepared = this.prepareSource(wire, target.builder);
99
101
  if (!current()) return false;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The HTTP realisation of the Gramlot envelope; application pages do not issue fetch calls.
3
+ *
4
+ * @module
5
+ */
6
+ import type {BeaconNavigator} from './dom.d.ts';
7
+
8
+ /** The fetch function used by the transport. */
9
+ export type Fetcher = (input: string, init?: RequestInit) => Promise<Response>;
10
+
11
+ /** The page-to-server transport over HTTP: sends the envelope to the rpc URL and closes the server page. */
12
+ export class HttpTransport {
13
+ /** The URL of the rpc endpoint. */
14
+ rpcUrl: string;
15
+ /** The function that sends the requests. */
16
+ fetcher: Fetcher;
17
+ /** The URL of the page close endpoint. */
18
+ closeUrl: string;
19
+ /** The navigator whose `sendBeacon` sends the close request on page hide. */
20
+ navigator: BeaconNavigator;
21
+ /** Create a transport on the rpc URL of the page. */
22
+ constructor(rpcUrl: string, options?: {fetcher?: Fetcher; closeUrl?: string; navigator?: BeaconNavigator});
23
+ /** POST the request envelope text; resolves with the response envelope text, rejects on a non-200 status. */
24
+ call(text: string, signal?: AbortSignal): Promise<string>;
25
+ /** Ask the server to close the page, with a beacon or a best-effort fetch; delivery failure is ignored. */
26
+ close(pageId: string, options?: {beacon?: boolean}): void;
27
+ }
@@ -1,32 +1,25 @@
1
- /* @ts-self-types="./transport.d.ts" */
1
+ /* @ts-self-types="./http-transport.d.ts" */
2
2
  /**
3
- * Main and remote Source transport; application pages do not issue fetch calls.
3
+ * The HTTP realisation of the Gramlot envelope; application pages do not issue fetch calls.
4
4
  *
5
5
  * @module
6
6
  */
7
- /** The page-to-server transport: loads `main` and remote Sources and closes the server page. */
8
- export class MainTransport {
9
- constructor(url, fetcher = globalThis.fetch?.bind(globalThis), sourceUrl = '/gramlot/source',
10
- closeUrl = '/gramlot/close', navigator = globalThis.navigator) {
11
- this.url = url;
7
+ /** The page-to-server transport over HTTP: sends the envelope to the rpc URL and closes the server page. */
8
+ export class HttpTransport {
9
+ constructor(rpcUrl, {fetcher = globalThis.fetch?.bind(globalThis), closeUrl = '/gramlot/close',
10
+ navigator = globalThis.navigator} = {}) {
11
+ this.rpcUrl = rpcUrl;
12
12
  this.fetcher = fetcher;
13
- this.sourceUrl = sourceUrl;
14
13
  this.closeUrl = closeUrl;
15
14
  this.navigator = navigator;
16
15
  }
17
- async main(pageId, signal) {
18
- return this.request('main', this.url, {pageId}, signal);
19
- }
20
- async source(pageId, method, params, signal) {
21
- return this.request('source', this.sourceUrl, {pageId, method, params}, signal);
22
- }
23
- async request(operation, url, payload, signal) {
24
- const response = await this.fetcher(url, {
16
+ async call(text, signal) {
17
+ const response = await this.fetcher(this.rpcUrl, {
25
18
  method: 'POST', credentials: 'same-origin', signal,
26
19
  headers: {'Content-Type': 'application/json'},
27
- body: JSON.stringify(payload),
20
+ body: text,
28
21
  });
29
- if (!response.ok) throw new Error(`${operation} failed: HTTP ${response.status}`);
22
+ if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
30
23
  return response.text();
31
24
  }
32
25
  close(pageId, {beacon = false} = {}) {
package/src/index.d.ts CHANGED
@@ -22,7 +22,9 @@ export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
22
22
  export {Bag, BagNode} from '@genrojs/bag';
23
23
  export {References} from './references.js';
24
24
  export type {SourceReference} from './references.js';
25
- export {MainTransport} from './transport.js';
26
- export type {Fetcher} from './transport.js';
25
+ export {HttpTransport} from './http-transport.js';
26
+ export type {Fetcher} from './http-transport.js';
27
+ export {RpcError} from './handlers/rpc-handler.js';
28
+ export type {RpcErrorOutcome, RpcTransport} from './handlers/rpc-handler.js';
27
29
  export {InOut} from './inout.js';
28
30
  export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, DomNode, DomWindow} from './dom.d.ts';
package/src/index.js CHANGED
@@ -21,5 +21,6 @@ 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
23
  export {References} from './references.js';
24
- export {MainTransport} from './transport.js';
24
+ export {HttpTransport} from './http-transport.js';
25
+ export {RpcError} from './handlers/rpc-handler.js';
25
26
  export {InOut} from './inout.js';
@@ -361,7 +361,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
361
361
  insert(node) {
362
362
  if (!this.attached(node) || this.records.has(node)) return;
363
363
  if (node._getMeta('data_element')) {
364
- // A `dataController` inserted in a button may give it a mechanism, or an ambiguous one (S12).
364
+ // A `dataController` or `dataRpc` inserted in a button may give it a mechanism, or an ambiguous one (S12).
365
365
  this.records.get(node.parentBag?.parentNode)?.button?.refresh();
366
366
  this.binding.branchBuilt(node);
367
367
  return;
@@ -1,16 +1,16 @@
1
1
  /* @ts-self-types="./assets.d.ts" */
2
2
  /**
3
- * Development mode and the runtime file to serve; Node.js and Bun only.
3
+ * Development mode and the runtime file to serve. `gramlotDev` imports nothing from Node.js, so the
4
+ * neutral `GramlotServer` can read it in a serverless Worker, where it is null without `process`.
4
5
  *
5
6
  * @module
6
7
  */
7
- import process from 'node:process';
8
8
 
9
9
  const DEV_MODES = ['YES', 'DEBUG'];
10
10
 
11
11
  /** GRAMLOT_DEV: null when unset (deploy), 'YES' or 'DEBUG'; any other value throws a TypeError. */
12
12
  export function gramlotDev() {
13
- const value = process.env.GRAMLOT_DEV;
13
+ const value = globalThis.process?.env?.GRAMLOT_DEV;
14
14
  if (value === undefined) return null;
15
15
  if (!DEV_MODES.includes(value)) {
16
16
  throw new TypeError(`GRAMLOT_DEV must be unset, YES or DEBUG, not ${JSON.stringify(value)}`);
@@ -4,6 +4,6 @@
4
4
  * @module
5
5
  */
6
6
 
7
- /** Run the checks of GC-230 §055 against the adapter at `baseUrl` (mount prefix included) with the page
7
+ /** Run the checks of GC-230 §150 against the adapter at `baseUrl` (mount prefix included) with the page
8
8
  * `pagePath`; reject with an `AssertionError` naming the rule of the first failure. */
9
9
  export function checkProtocol(baseUrl: string, pagePath: string): Promise<void>;
@@ -5,9 +5,10 @@
5
5
  * @module
6
6
  */
7
7
  import {AssertionError} from 'node:assert';
8
+ import {isDeepStrictEqual} from 'node:util';
9
+ import {fromTytx, toTytx} from '@genrojs/tytx';
8
10
 
9
11
  const OWNER_COOKIE = 'gramlot_owner';
10
- const MAX_REQUEST_BYTES = 4096;
11
12
  const BOOTSTRAP = /<script type="module" nonce="([^"]+)">import \{PageBootstrap\} from ("[^"]*");await new PageBootstrap\((\{.*?\})\)\.run\(\);<\/script>/;
12
13
 
13
14
  const expect = (rule, condition, message) => {
@@ -16,7 +17,7 @@ const expect = (rule, condition, message) => {
16
17
 
17
18
  const mediaType = headers => (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
18
19
 
19
- /** Run the checks of GC-230 §055 against the adapter at baseUrl (mount prefix included) with
20
+ /** Run the checks of GC-230 §150 against the adapter at baseUrl (mount prefix included) with
20
21
  * the page pagePath; throw an AssertionError naming the rule of the first failure. The Python
21
22
  * counterpart is src/gramlot/server/conformance.py: both run the same list in the same order. */
22
23
  export async function checkProtocol(baseUrl, pagePath) {
@@ -30,34 +31,36 @@ export async function checkProtocol(baseUrl, pagePath) {
30
31
  const response = await fetch(base.origin + path, {method, body, headers, redirect: 'manual'});
31
32
  return {status: response.status, headers: response.headers, body: await response.text()};
32
33
  };
33
- const post = (url, payload, options = {}) => request('POST', url, {...options, body: JSON.stringify(payload)});
34
34
 
35
35
  if (prefix) {
36
36
  const {status, headers} = await request('GET', prefix);
37
- expect('GC-230-010', status === 301 && (headers.get('location') ?? '').endsWith(`${prefix}/`),
37
+ expect('GC-230-105', status === 301 && (headers.get('location') ?? '').endsWith(`${prefix}/`),
38
38
  `GET ${prefix} answers ${status}, not 301 to ${prefix}/`);
39
39
  }
40
40
 
41
41
  const pageUrl = prefix + pagePath;
42
42
  const page = await request('GET', pageUrl);
43
- expect('GC-230-020', page.status === 200 && mediaType(page.headers) === 'text/html',
43
+ expect('GC-230-115', page.status === 200 && mediaType(page.headers) === 'text/html',
44
44
  `GET ${pageUrl} answers ${page.status} ${page.headers.get('content-type')}, not 200 text/html`);
45
45
  const match = BOOTSTRAP.exec(page.body);
46
- expect('GC-230-020', match !== null, `GET ${pageUrl} has no bootstrap module script`);
46
+ expect('GC-230-115', match !== null, `GET ${pageUrl} has no bootstrap module script`);
47
47
  const [, nonce, runtimeJson, bootstrapJson] = match;
48
48
  const runtimeUrl = JSON.parse(runtimeJson);
49
49
  const {config, resources} = JSON.parse(bootstrapJson);
50
- expect('GC-230-020', page.body.includes(`<script type="importmap" nonce="${nonce}">`),
50
+ expect('GC-230-115', page.body.includes(`<script type="importmap" nonce="${nonce}">`),
51
51
  'the import map does not carry the bootstrap nonce');
52
- const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], main: [config.mainUrl, '/gramlot/main'],
53
- source: [config.sourceUrl, '/gramlot/source'], close: [config.closeUrl, '/gramlot/close']};
52
+ expect('GC-230-115', typeof config.rpcUrl === 'string' && typeof config.closeUrl === 'string'
53
+ && Array.isArray(config.capabilities),
54
+ `bootstrap config ${JSON.stringify(config)} lacks rpcUrl, closeUrl or a capabilities array`);
55
+ const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], rpc: [config.rpcUrl, '/gramlot/rpc'],
56
+ close: [config.closeUrl, '/gramlot/close']};
54
57
  for (const [name, [url, path]] of Object.entries(expected)) {
55
- expect('GC-230-010', url === prefix + path, `bootstrap ${name} URL ${url}, not ${prefix + path}`);
58
+ expect('GC-230-105', url === prefix + path, `bootstrap ${name} URL ${url}, not ${prefix + path}`);
56
59
  }
57
60
 
58
61
  const policy = page.headers.get('content-security-policy');
59
62
  if (policy !== null) {
60
- expect('GC-230-045', policy.includes(`'nonce-${nonce}'`), 'the Content-Security-Policy lacks the bootstrap nonce');
63
+ expect('GC-230-140', policy.includes(`'nonce-${nonce}'`), 'the Content-Security-Policy lacks the bootstrap nonce');
61
64
  }
62
65
 
63
66
  for (const line of page.headers.getSetCookie()) {
@@ -67,72 +70,127 @@ export async function checkProtocol(baseUrl, pagePath) {
67
70
  const [key, value = ''] = attribute.split('=');
68
71
  return [key.toLowerCase(), value];
69
72
  }));
70
- expect('GC-230-040', 'httponly' in named && named.samesite?.toLowerCase() === 'lax' && named.path === (prefix || '/'),
73
+ expect('GC-230-135', 'httponly' in named && named.samesite?.toLowerCase() === 'lax' && named.path === (prefix || '/'),
71
74
  `owner cookie without HttpOnly, SameSite=Lax and Path=${prefix || '/'}`);
72
75
  owner = pair.slice(OWNER_COOKIE.length + 1);
73
76
  }
74
77
 
75
78
  let response = await request('GET', runtimeUrl);
76
- expect('GC-230-015', response.status === 200 && mediaType(response.headers) === 'text/javascript',
79
+ expect('GC-230-110', response.status === 200 && mediaType(response.headers) === 'text/javascript',
77
80
  `GET ${runtimeUrl} answers ${response.status} ${response.headers.get('content-type')}, not 200 text/javascript`);
78
81
  response = await request('POST', runtimeUrl, {body: '{}'});
79
- expect('GC-230-015', response.status === 405, `POST ${runtimeUrl} answers ${response.status}, not 405`);
82
+ expect('GC-230-110', response.status === 405, `POST ${runtimeUrl} answers ${response.status}, not 405`);
80
83
 
81
84
  const files = [...resources.css.map(url => [url, 'text/css']), ...resources.js.map(({url}) => [url, 'text/javascript'])];
82
85
  for (const [url, type] of files) {
83
86
  if (!url.startsWith('/') || url.startsWith('//')) continue;
84
87
  response = await request('GET', url);
85
- expect('GC-230-050', response.status === 200 && mediaType(response.headers) === type,
88
+ expect('GC-230-145', response.status === 200 && mediaType(response.headers) === type,
86
89
  `GET ${url} answers ${response.status} ${response.headers.get('content-type')}, not 200 ${type}`);
87
90
  }
88
91
 
89
92
  response = await request('GET', `${prefix}/gramlot-conformance-missing-page`);
90
- expect('GC-230-020', response.status === 404, `an unknown page answers ${response.status}, not 404`);
93
+ expect('GC-230-115', response.status === 404, `an unknown page answers ${response.status}, not 404`);
91
94
  response = await request('POST', pageUrl, {body: '{}'});
92
- expect('GC-230-020', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
95
+ expect('GC-230-115', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
93
96
  if (pagePath.endsWith('/')) {
94
97
  response = await request('GET', `${pageUrl}index.html`);
95
- expect('GC-230-020', response.status === 200 && mediaType(response.headers) === 'text/html',
98
+ expect('GC-230-115', response.status === 200 && mediaType(response.headers) === 'text/html',
96
99
  `GET ${pageUrl}index.html answers ${response.status}, not the page ${pageUrl}`);
97
100
  }
98
101
 
99
- const {pageId, mainUrl: main} = config;
100
- response = await request('GET', main);
101
- expect('GC-230-025', response.status === 405, `GET ${main} answers ${response.status}, not 405`);
102
- response = await post(main, {pageId}, {contentType: 'text/plain'});
103
- expect('GC-230-025', response.status === 415, `main as text/plain answers ${response.status}, not 415`);
104
- response = await request('POST', main, {body: '{'});
105
- expect('GC-230-025', response.status === 400, `main with invalid JSON answers ${response.status}, not 400`);
106
- response = await post(main, {});
107
- expect('GC-230-025', response.status === 400, `main without pageId answers ${response.status}, not 400`);
108
- response = await post(main, {pageId, padding: 'x'.repeat(MAX_REQUEST_BYTES)});
109
- expect('GC-230-025', response.status === 413,
110
- `main above ${MAX_REQUEST_BYTES} bytes answers ${response.status}, not 413`);
111
-
112
- response = await post(main, {pageId});
113
- expect('GC-230-030', response.status === 200 && mediaType(response.headers) === 'application/json' && response.body,
114
- `main answers ${response.status} ${response.headers.get('content-type')}, not 200 application/json with the Source`);
102
+ const {pageId, rpcUrl: rpc} = config;
103
+ const envelope = (contentType, name, params = {}, fields = {}) =>
104
+ ({id: crypto.randomUUID(), pageId, contentType, name, params, ...fields});
105
+ const parse = (text, decode) => {
106
+ try { return decode(text); } catch { return null; }
107
+ };
108
+ /** POST the envelope sent to rpc; the response with the decoded envelope as `received`. */
109
+ const call = async (sent, options = {}) => {
110
+ const answer = await request('POST', rpc, {...options, body: toTytx(sent)});
111
+ return {...answer, received: parse(answer.body, fromTytx)};
112
+ };
113
+ const outcome = async (rule, sent, code, label, options = {}) => {
114
+ const {status, body, received} = await call(sent, options);
115
+ const error = received?.error;
116
+ expect(rule, status === 200 && error?.code === code,
117
+ `${label} answers ${status} ${body.slice(0, 200)}, not 200 with the outcome ${code}`);
118
+ return error;
119
+ };
120
+
121
+ response = await request('GET', rpc);
122
+ expect('GC-230-120', response.status === 405, `GET ${rpc} answers ${response.status}, not 405`);
123
+ response = await request('POST', rpc, {body: toTytx(envelope('source', 'main')), contentType: 'text/plain'});
124
+ expect('GC-230-120', response.status === 415, `rpc as text/plain answers ${response.status}, not 415`);
125
+ response = await request('POST', rpc, {body: '{'});
126
+ expect('GC-230-120', response.status === 400, `rpc with invalid JSON answers ${response.status}, not 400`);
127
+ const {pageId: omitted, ...withoutPageId} = envelope('source', 'main');
128
+ const invalid = {'without pageId': withoutPageId, 'with params null': envelope('source', 'main', null),
129
+ 'with array params': envelope('source', 'main', []), 'with an unknown contentType': envelope('other', 'main')};
130
+ for (const [label, sent] of Object.entries(invalid)) {
131
+ response = await call(sent);
132
+ expect('GC-230-120', response.status === 400, `rpc ${label} answers ${response.status}, not 400`);
133
+ }
134
+
135
+ const sent = envelope('source', 'main');
136
+ response = await call(sent);
137
+ const received = parse(response.body, JSON.parse);
138
+ expect('GC-230-020', response.status === 200 && mediaType(response.headers) === 'application/json'
139
+ && received?.id === sent.id && received?.contentType === 'source' && typeof received?.value === 'string',
140
+ `main answers ${response.status} ${response.headers.get('content-type')} ${response.body.slice(0, 200)}, not 200 `
141
+ + 'application/json with an envelope echoing id and contentType and carrying the fragment document as a string');
115
142
  if (owner !== null) {
116
- response = await post(main, {pageId}, {withOwner: false});
117
- expect('GC-230-040', response.status === 404, `main without the owner cookie answers ${response.status}, not 404`);
143
+ await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main without the owner cookie',
144
+ {withOwner: false});
145
+ }
146
+
147
+ await outcome('GC-230-025', envelope('source', 'main', {}, {pageId: '0'.repeat(32)}), 'page_expired',
148
+ 'main of an unknown page');
149
+ await outcome('GC-230-025', envelope('source', 'gramlot_conformance_missing'), 'not_found', 'an unknown fragment');
150
+ await outcome('GC-230-025', envelope('data', 'gramlot_conformance_missing'), 'not_found', 'an unknown endpoint');
151
+ await outcome('GC-230-025', envelope('data', 'main'), 'not_found', 'data main');
152
+
153
+ response = await call(envelope('source', 'check_fragment', {text: 'gramlot-conformance'}));
154
+ const fragment = parse(response.body, JSON.parse)?.value;
155
+ expect('GC-230-015', response.status === 200 && typeof fragment === 'string' && fragment.includes('gramlot-conformance'),
156
+ `check_fragment answers ${response.status} ${response.body.slice(0, 200)}, not a fragment document with its params`);
157
+ // The date crosses the wire typed (::D) and comes back as the same typed value.
158
+ for (const value of [3, 'x', new Date(Date.UTC(2020, 0, 1))]) {
159
+ response = await call(envelope('data', 'check_endpoint', {value}));
160
+ expect('GC-230-015', response.status === 200 && isDeepStrictEqual(response.received?.value, value),
161
+ `check_endpoint of ${JSON.stringify(value)} answers ${response.status} ${response.body.slice(0, 200)}, `
162
+ + `not ${JSON.stringify(value)}`);
163
+ }
164
+
165
+ if (config.capabilities.includes('auth')) {
166
+ response = await call(envelope('data', 'check_endpoint_auth'));
167
+ const {received: answer} = response;
168
+ expect('GC-230-030', response.status === 200 && answer !== null && typeof answer === 'object' && (!('error' in answer)
169
+ ? 'value' in answer : ['not_authenticated', 'not_authorized'].includes(answer.error?.code)),
170
+ `check_endpoint_auth answers ${response.status} ${response.body.slice(0, 200)}, not 200 with not_authenticated, `
171
+ + 'not_authorized or a value');
172
+ } else {
173
+ await outcome('GC-230-030', envelope('data', 'check_endpoint_auth'), 'not_authenticated', 'check_endpoint_auth');
174
+ }
175
+
176
+ response = await call(envelope('source', 'check_fragment_auth'));
177
+ const guarded = parse(response.body, JSON.parse)?.value;
178
+ expect('GC-230-030', response.status === 200 && typeof guarded === 'string' && guarded.includes('check-public'),
179
+ `check_fragment_auth answers ${response.status} ${response.body.slice(0, 200)}, not a fragment document`);
180
+ if (!config.capabilities.includes('auth')) {
181
+ expect('GC-230-030', !guarded.includes('check-refused'),
182
+ `check_fragment_auth answers ${guarded.slice(0, 200)}, which contains the element of the refused auth rule`);
118
183
  }
119
- response = await post(main, {pageId: '0'.repeat(32)});
120
- expect('GC-230-035', response.status === 404, `main of an unknown page answers ${response.status}, not 404`);
121
184
 
122
- const source = config.sourceUrl;
123
- response = await post(source, {pageId});
124
- expect('GC-230-025', response.status === 400, `Source without method answers ${response.status}, not 400`);
125
- response = await post(source, {pageId, method: 'details', params: []});
126
- expect('GC-230-025', response.status === 400, `Source with array params answers ${response.status}, not 400`);
127
- response = await post(source, {pageId, method: 'gramlot_conformance_missing'});
128
- expect('GC-230-035', response.status === 404, `an unknown Source method answers ${response.status}, not 404`);
185
+ const error = await outcome('GC-230-025', envelope('data', 'check_endpoint_raise'), 'application_error',
186
+ 'check_endpoint_raise');
187
+ expect('GC-230-025', typeof error.name === 'string' && error.name !== '' && error.message === 'check',
188
+ `check_endpoint_raise answers the error ${JSON.stringify(error)}, not the exception name and the message 'check'`);
129
189
 
130
190
  const close = config.closeUrl;
131
- response = await post(close, {pageId});
132
- let closed = null;
133
- try { closed = JSON.parse(response.body); } catch { /* checked below */ }
134
- expect('GC-230-030', response.status === 200 && mediaType(response.headers) === 'application/json' && closed?.ok === true,
191
+ response = await request('POST', close, {body: JSON.stringify({pageId})});
192
+ const closed = parse(response.body, JSON.parse);
193
+ expect('GC-230-125', response.status === 200 && mediaType(response.headers) === 'application/json' && isDeepStrictEqual(closed, {ok: true}),
135
194
  `close answers ${response.status} ${response.body}, not 200 {"ok": true}`);
136
- response = await post(main, {pageId});
137
- expect('GC-230-030', response.status === 404, `main after close answers ${response.status}, not 404`);
195
+ await outcome('GC-230-125', envelope('source', 'main'), 'page_expired', 'main after close');
138
196
  }
@@ -20,19 +20,36 @@ export class PageNotFound extends Error {
20
20
  export class SourceNotFound extends Error {
21
21
  name: 'SourceNotFound';
22
22
  }
23
+ /** No endpoint of that name, as the Python `EndpointNotFound`. */
24
+ export class EndpointNotFound extends Error {
25
+ name: 'EndpointNotFound';
26
+ }
27
+ /** The `auth` evaluator answered `not_authenticated`. */
28
+ export class NotAuthenticated extends Error {
29
+ name: 'NotAuthenticated';
30
+ }
31
+ /** The `auth` evaluator answered `not_authorized`. */
32
+ export class NotAuthorized extends Error {
33
+ name: 'NotAuthorized';
34
+ }
35
+ /** A request envelope that is not `{id, pageId, contentType, name, params}`, as the Python `InvalidRequest`. */
36
+ export class InvalidRequest extends Error {
37
+ name: 'InvalidRequest';
38
+ }
23
39
  /** The page registry is full. */
24
40
  export class ServerCapacity extends Error {
25
41
  name: 'ServerCapacity';
26
42
  }
27
43
 
44
+ /** The outcome of a refused `auth` rule, or null when the call may proceed. */
45
+ export type AuthOutcome = 'not_authenticated' | 'not_authorized' | null;
46
+
28
47
  /** The options of a `GramlotServer`. */
29
48
  export interface GramlotServerOptions {
30
49
  /** URL of the runtime bundle. */
31
50
  runtimeUrl?: string;
32
- /** URL of the `main` Source endpoint. */
33
- mainUrl?: string;
34
- /** URL of the remote Source endpoint. */
35
- sourceUrl?: string;
51
+ /** URL of the request envelopes. */
52
+ rpcUrl?: string;
36
53
  /** URL of the page close endpoint. */
37
54
  closeUrl?: string;
38
55
  /** Id of the root element of the page. */
@@ -70,10 +87,8 @@ export interface OpenedPage {
70
87
  export class GramlotServer {
71
88
  /** URL of the runtime bundle. */
72
89
  runtimeUrl: string;
73
- /** URL of the `main` Source endpoint. */
74
- mainUrl: string;
75
- /** URL of the remote Source endpoint. */
76
- sourceUrl: string;
90
+ /** URL of the request envelopes. */
91
+ rpcUrl: string;
77
92
  /** URL of the page close endpoint. */
78
93
  closeUrl: string;
79
94
  /** Id of the root element of the page. */
@@ -90,21 +105,18 @@ export class GramlotServer {
90
105
  resolvePage(path: string): Promise<typeof Page>;
91
106
  /** The resources of the page at `path` in load order and without mount prefix, or `PageNotFound`. */
92
107
  resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
108
+ /** The capabilities announced in the bootstrap; none in the base server. */
109
+ get capabilities(): string[];
110
+ /** null when a target with `rule` may run for `owner`; the base server refuses any rule. */
111
+ evaluateAuth(rule: string | null, options?: {owner?: unknown}): AuthOutcome;
93
112
  /** Drop the expired pages. */
94
113
  prune(): void;
95
114
  /** Register a page independently of its HTTP or Worker transport. */
96
115
  registerPage(path: string, options?: {owner?: unknown}): Promise<RegisteredPage>;
97
116
  /** Register the page and return its bootstrap; `prefix` is the mount prefix added to root-relative URLs. */
98
117
  openPage(path: string, options?: {owner?: unknown; prefix?: string}): Promise<OpenedPage>;
99
- /** The `main` Source of a registered page, as TYTX text. */
100
- main(pageId: string, options?: {owner?: unknown}): Promise<string>;
101
- /** A remote Source of a registered page, as TYTX text; `params` null or omitted is `{}`. */
102
- source(pageId: string, method: string, params?: Record<string, unknown> | null,
103
- options?: {owner?: unknown}): Promise<string>;
104
- /** Build the Source of a page by calling its `main` (`method` `'main'`) or a registered Source method;
105
- * the Source builder is named after `method`. */
106
- buildSource(pageId: string, method: string, params: Record<string, unknown>,
107
- owner: unknown): Promise<string>;
118
+ /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. */
119
+ call(text: string, options?: {owner?: unknown}): Promise<string>;
108
120
  /** Forget a registered page when `owner` owns it. */
109
121
  closePage(pageId: string, options?: {owner?: unknown}): void;
110
122
  /** Forget every registered page; adapters call it on shutdown. */