@drupflare/spool 0.0.0-stage → 0.1.0

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1557 -2
  3. package/dist/cdn/client.js +1 -0
  4. package/dist/cdn/location.d.ts +11 -0
  5. package/dist/cdn/location.js +15 -0
  6. package/dist/cdn/manifest.json +16 -0
  7. package/dist/cdn/spool-sw.js +1 -0
  8. package/dist/client/entry.d.ts +1 -0
  9. package/dist/client/entry.js +25 -0
  10. package/dist/client/index.d.ts +3 -0
  11. package/dist/client/index.js +2 -0
  12. package/dist/client/lifecycle.d.ts +10 -0
  13. package/dist/client/lifecycle.js +10 -0
  14. package/dist/client/loads.d.ts +16 -0
  15. package/dist/client/loads.js +41 -0
  16. package/dist/client/register.d.ts +34 -0
  17. package/dist/client/register.js +58 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +2 -0
  20. package/dist/node/listener.d.ts +19 -0
  21. package/dist/node/listener.js +76 -0
  22. package/dist/protocol/artifact.d.ts +54 -0
  23. package/dist/protocol/artifact.js +79 -0
  24. package/dist/protocol/assembly.d.ts +34 -0
  25. package/dist/protocol/assembly.js +72 -0
  26. package/dist/protocol/beacon.d.ts +59 -0
  27. package/dist/protocol/beacon.js +86 -0
  28. package/dist/protocol/collector.d.ts +41 -0
  29. package/dist/protocol/collector.js +84 -0
  30. package/dist/protocol/config.d.ts +89 -0
  31. package/dist/protocol/config.js +13 -0
  32. package/dist/protocol/envelope.d.ts +47 -0
  33. package/dist/protocol/envelope.js +162 -0
  34. package/dist/protocol/errors.d.ts +7 -0
  35. package/dist/protocol/errors.js +9 -0
  36. package/dist/protocol/graph.d.ts +81 -0
  37. package/dist/protocol/graph.js +201 -0
  38. package/dist/protocol/index.d.ts +19 -0
  39. package/dist/protocol/index.js +19 -0
  40. package/dist/protocol/manifest.d.ts +29 -0
  41. package/dist/protocol/manifest.js +94 -0
  42. package/dist/protocol/normalise.d.ts +20 -0
  43. package/dist/protocol/normalise.js +29 -0
  44. package/dist/protocol/pattern.d.ts +12 -0
  45. package/dist/protocol/pattern.js +82 -0
  46. package/dist/protocol/provision.d.ts +100 -0
  47. package/dist/protocol/provision.js +105 -0
  48. package/dist/protocol/route.d.ts +179 -0
  49. package/dist/protocol/route.js +135 -0
  50. package/dist/protocol/sync.d.ts +31 -0
  51. package/dist/protocol/sync.js +87 -0
  52. package/dist/protocol/tag.d.ts +12 -0
  53. package/dist/protocol/tag.js +26 -0
  54. package/dist/protocol/template/compile.d.ts +35 -0
  55. package/dist/protocol/template/compile.js +82 -0
  56. package/dist/protocol/template/interpret.d.ts +9 -0
  57. package/dist/protocol/template/interpret.js +82 -0
  58. package/dist/protocol/vector.d.ts +32 -0
  59. package/dist/protocol/vector.js +56 -0
  60. package/dist/protocol/view.d.ts +110 -0
  61. package/dist/protocol/view.js +201 -0
  62. package/dist/proxy/eligible.d.ts +45 -0
  63. package/dist/proxy/eligible.js +96 -0
  64. package/dist/proxy/index.d.ts +4 -0
  65. package/dist/proxy/index.js +4 -0
  66. package/dist/proxy/proxy.d.ts +86 -0
  67. package/dist/proxy/proxy.js +388 -0
  68. package/dist/proxy/purge.d.ts +10 -0
  69. package/dist/proxy/purge.js +66 -0
  70. package/dist/proxy/tags.d.ts +8 -0
  71. package/dist/proxy/tags.js +36 -0
  72. package/dist/report/derive.d.ts +221 -0
  73. package/dist/report/derive.js +490 -0
  74. package/dist/report/economics.d.ts +14 -0
  75. package/dist/report/economics.js +24 -0
  76. package/dist/report/index.d.ts +8 -0
  77. package/dist/report/index.js +8 -0
  78. package/dist/report/inputs.d.ts +141 -0
  79. package/dist/report/inputs.js +216 -0
  80. package/dist/report/measurement.d.ts +48 -0
  81. package/dist/report/measurement.js +114 -0
  82. package/dist/report/model.d.ts +42 -0
  83. package/dist/report/model.js +74 -0
  84. package/dist/report/thirdparty.d.ts +62 -0
  85. package/dist/report/thirdparty.js +107 -0
  86. package/dist/report/traffic.d.ts +140 -0
  87. package/dist/report/traffic.js +228 -0
  88. package/dist/report/trim.d.ts +81 -0
  89. package/dist/report/trim.js +105 -0
  90. package/dist/server/beacon.d.ts +20 -0
  91. package/dist/server/beacon.js +47 -0
  92. package/dist/server/embedded.d.ts +6 -0
  93. package/dist/server/embedded.js +6 -0
  94. package/dist/server/ga4.d.ts +70 -0
  95. package/dist/server/ga4.js +165 -0
  96. package/dist/server/identity.d.ts +12 -0
  97. package/dist/server/identity.js +17 -0
  98. package/dist/server/index.d.ts +7 -0
  99. package/dist/server/index.js +7 -0
  100. package/dist/server/sink.d.ts +56 -0
  101. package/dist/server/sink.js +133 -0
  102. package/dist/server/size.d.ts +7 -0
  103. package/dist/server/size.js +18 -0
  104. package/dist/server/spool.d.ts +97 -0
  105. package/dist/server/spool.js +463 -0
  106. package/dist/server/stub.d.ts +9 -0
  107. package/dist/server/stub.js +19 -0
  108. package/dist/server/sync.d.ts +12 -0
  109. package/dist/server/sync.js +48 -0
  110. package/dist/server/work.d.ts +22 -0
  111. package/dist/server/work.js +30 -0
  112. package/dist/stores/durable-object.d.ts +19 -0
  113. package/dist/stores/durable-object.js +53 -0
  114. package/dist/stores/index.d.ts +2 -0
  115. package/dist/stores/index.js +2 -0
  116. package/dist/stores/memory.d.ts +4 -0
  117. package/dist/stores/memory.js +10 -0
  118. package/dist/stores/version-store.d.ts +11 -0
  119. package/dist/stores/version-store.js +1 -0
  120. package/dist/sw/analytics.d.ts +81 -0
  121. package/dist/sw/analytics.js +275 -0
  122. package/dist/sw/collect.d.ts +8 -0
  123. package/dist/sw/collect.js +33 -0
  124. package/dist/sw/core.d.ts +1 -0
  125. package/dist/sw/core.js +3 -0
  126. package/dist/sw/freshness.d.ts +15 -0
  127. package/dist/sw/freshness.js +20 -0
  128. package/dist/sw/graph/index.d.ts +67 -0
  129. package/dist/sw/graph/index.js +170 -0
  130. package/dist/sw/graph/invalidate.d.ts +23 -0
  131. package/dist/sw/graph/invalidate.js +109 -0
  132. package/dist/sw/graph/projections.d.ts +7 -0
  133. package/dist/sw/graph/projections.js +9 -0
  134. package/dist/sw/graph/records.d.ts +7 -0
  135. package/dist/sw/graph/records.js +9 -0
  136. package/dist/sw/graph/store.d.ts +32 -0
  137. package/dist/sw/graph/store.js +52 -0
  138. package/dist/sw/idb.d.ts +8 -0
  139. package/dist/sw/idb.js +117 -0
  140. package/dist/sw/index.d.ts +2 -0
  141. package/dist/sw/index.js +1 -0
  142. package/dist/sw/partition.d.ts +21 -0
  143. package/dist/sw/partition.js +137 -0
  144. package/dist/sw/policy.d.ts +8 -0
  145. package/dist/sw/policy.js +24 -0
  146. package/dist/sw/provision.d.ts +39 -0
  147. package/dist/sw/provision.js +61 -0
  148. package/dist/sw/render.d.ts +21 -0
  149. package/dist/sw/render.js +53 -0
  150. package/dist/sw/replica.d.ts +77 -0
  151. package/dist/sw/replica.js +299 -0
  152. package/dist/sw/router.d.ts +42 -0
  153. package/dist/sw/router.js +48 -0
  154. package/dist/sw/routing.d.ts +23 -0
  155. package/dist/sw/routing.js +48 -0
  156. package/dist/sw/runtime.d.ts +112 -0
  157. package/dist/sw/runtime.js +1070 -0
  158. package/dist/sw/scheduler.d.ts +83 -0
  159. package/dist/sw/scheduler.js +149 -0
  160. package/dist/sw/seal.d.ts +37 -0
  161. package/dist/sw/seal.js +183 -0
  162. package/dist/sw/serve.d.ts +15 -0
  163. package/dist/sw/serve.js +63 -0
  164. package/dist/sw/shadow.d.ts +16 -0
  165. package/dist/sw/shadow.js +27 -0
  166. package/dist/sw/static.d.ts +17 -0
  167. package/dist/sw/static.js +81 -0
  168. package/dist/sw/storage.d.ts +64 -0
  169. package/dist/sw/storage.js +34 -0
  170. package/dist/sw/thirdparty.d.ts +17 -0
  171. package/dist/sw/thirdparty.js +36 -0
  172. package/dist/trim/css.d.ts +38 -0
  173. package/dist/trim/css.js +328 -0
  174. package/dist/trim/index.d.ts +3 -0
  175. package/dist/trim/index.js +3 -0
  176. package/dist/trim/manifest.d.ts +67 -0
  177. package/dist/trim/manifest.js +134 -0
  178. package/dist/trim/tokens.d.ts +43 -0
  179. package/dist/trim/tokens.js +142 -0
  180. package/dist/version.d.ts +2 -0
  181. package/dist/version.js +3 -0
  182. package/package.json +146 -5
@@ -0,0 +1,87 @@
1
+ import { PROTOCOL_VERSION } from './artifact.js';
2
+ import { ProtocolError } from './errors.js';
3
+ /** an artifact id rides the vector as this tag, so an explicit drop shares the sync cursor */
4
+ export const ARTIFACT_TAG_PREFIX = 'spool:artifact:';
5
+ /** most ids one `need` request may name; a worker needing more falls back to a full sync */
6
+ export const MAX_NEED = 64;
7
+ /** most ids one `have` list may carry on an artifact request */
8
+ export const MAX_HAVE = 256;
9
+ /** the vector tag that drops artifact `id` */
10
+ export function artifactTag(id) {
11
+ return `${ARTIFACT_TAG_PREFIX}${id}`;
12
+ }
13
+ /** splits a vector diff into changed tags and dropped artifact ids */
14
+ export function toSyncResponse(diff) {
15
+ const entries = Object.entries(diff.changed);
16
+ const dropped = entries
17
+ .filter(([tag]) => tag.startsWith(ARTIFACT_TAG_PREFIX))
18
+ .map(([tag]) => tag.slice(ARTIFACT_TAG_PREFIX.length));
19
+ const changed = Object.fromEntries(entries.filter(([tag]) => !tag.startsWith(ARTIFACT_TAG_PREFIX)));
20
+ return { protocol: PROTOCOL_VERSION, cursor: diff.cursor, changed, dropped, reset: diff.reset };
21
+ }
22
+ function bad(message) {
23
+ throw new ProtocolError('bad-sync', message);
24
+ }
25
+ /** `id@version` pairs for the `need` and `have` query parameters, ids percent-encoded */
26
+ export function encodeHeld(held) {
27
+ return Object.entries(held)
28
+ .map(([id, version]) => `${encodeURIComponent(id)}@${version}`)
29
+ .join(',');
30
+ }
31
+ /** reads {@link encodeHeld} back; throws `ProtocolError` on a malformed pair or more than `limit` */
32
+ export function parseHeld(text, limit) {
33
+ const out = {};
34
+ const parts = text.split(',').filter((part) => part !== '');
35
+ if (parts.length > limit)
36
+ return bad(`more than ${limit} ids`);
37
+ for (const part of parts) {
38
+ const at = part.lastIndexOf('@');
39
+ const version = part.slice(at + 1);
40
+ if (at < 1 || !/^\d{1,15}$/.test(version))
41
+ return bad('entries are id@version');
42
+ try {
43
+ out[decodeURIComponent(part.slice(0, at))] = Number(version);
44
+ }
45
+ catch {
46
+ return bad('an id has a bad escape');
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+ /** validates JSON from `/.spool/sync` */
52
+ export function parseSyncResponse(value) {
53
+ if (typeof value !== 'object' || value === null)
54
+ return bad('sync response must be an object');
55
+ const v = value;
56
+ if (v['protocol'] !== PROTOCOL_VERSION)
57
+ return bad('unsupported protocol version');
58
+ const { cursor, changed, dropped, reset, partial } = v;
59
+ if (typeof cursor !== 'number' || !Number.isSafeInteger(cursor) || cursor < 0) {
60
+ return bad('cursor must be a non-negative integer');
61
+ }
62
+ if (typeof changed !== 'object' || changed === null || Array.isArray(changed)) {
63
+ return bad('changed must be an object');
64
+ }
65
+ for (const version of Object.values(changed)) {
66
+ if (typeof version !== 'number' || !Number.isSafeInteger(version)) {
67
+ return bad('changed versions must be integers');
68
+ }
69
+ }
70
+ if (!Array.isArray(dropped) || dropped.some((d) => typeof d !== 'string')) {
71
+ return bad('dropped must be a list of strings');
72
+ }
73
+ if (typeof reset !== 'boolean')
74
+ return bad('reset must be a boolean');
75
+ if (partial !== undefined && typeof partial !== 'boolean')
76
+ return bad('partial must be a boolean');
77
+ const out = {
78
+ protocol: PROTOCOL_VERSION,
79
+ cursor,
80
+ changed: changed,
81
+ dropped,
82
+ reset
83
+ };
84
+ if (partial)
85
+ out.partial = true;
86
+ return out;
87
+ }
@@ -0,0 +1,12 @@
1
+ /** the attribute that marks the page runtime script, so it is never injected twice */
2
+ export declare const CLIENT_TAG_ATTR = "data-spool-client";
3
+ /** the script tag for the page runtime; `integrity` makes it a cross-origin, SRI-checked load */
4
+ export declare function clientTag(options: {
5
+ src: string;
6
+ integrity?: string;
7
+ }): string;
8
+ /**
9
+ * Puts `tag` before `</head>`, else before `</body>`, else at the end. A page that already has
10
+ * the runtime tag is returned unchanged, so the server and the worker can both call this.
11
+ */
12
+ export declare function injectClientTag(html: string, tag: string): string;
@@ -0,0 +1,26 @@
1
+ /** the attribute that marks the page runtime script, so it is never injected twice */
2
+ export const CLIENT_TAG_ATTR = 'data-spool-client';
3
+ function escapeAttr(value) {
4
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
5
+ }
6
+ /** the script tag for the page runtime; `integrity` makes it a cross-origin, SRI-checked load */
7
+ export function clientTag(options) {
8
+ const sri = options.integrity
9
+ ? ` integrity="${escapeAttr(options.integrity)}" crossorigin="anonymous"`
10
+ : '';
11
+ return `<script src="${escapeAttr(options.src)}"${sri} defer ${CLIENT_TAG_ATTR}></script>`;
12
+ }
13
+ /**
14
+ * Puts `tag` before `</head>`, else before `</body>`, else at the end. A page that already has
15
+ * the runtime tag is returned unchanged, so the server and the worker can both call this.
16
+ */
17
+ export function injectClientTag(html, tag) {
18
+ if (html.includes(CLIENT_TAG_ATTR))
19
+ return html;
20
+ for (const close of [/<\/head\s*>/i, /<\/body\s*>/i]) {
21
+ const at = html.search(close);
22
+ if (at >= 0)
23
+ return html.slice(0, at) + tag + html.slice(at);
24
+ }
25
+ return html + tag;
26
+ }
@@ -0,0 +1,35 @@
1
+ /** one node of a compiled template; `p` is a dotted path split into segments, `[]` is `this` */
2
+ export type TemplateNode = {
3
+ t: 'text';
4
+ v: string;
5
+ } | {
6
+ t: 'var';
7
+ p: string[];
8
+ raw: boolean;
9
+ } | {
10
+ t: 'each';
11
+ p: string[];
12
+ body: TemplateNode[];
13
+ } | {
14
+ t: 'if';
15
+ p: string[];
16
+ then: TemplateNode[];
17
+ else: TemplateNode[];
18
+ };
19
+ /** the JSON a service worker interprets; `trusted` lists the paths allowed to print unescaped */
20
+ export type CompiledTemplate = {
21
+ v: 1;
22
+ trusted: string[];
23
+ nodes: TemplateNode[];
24
+ };
25
+ /** what a route declares: the source and the fields the server vouches for as markup */
26
+ export type TemplateSource = {
27
+ source: string;
28
+ trusted?: readonly string[];
29
+ };
30
+ /**
31
+ * Compiles Mustache-shaped source to a JSON tree: `{{field}}` escaped, `{{{field}}}` raw (only for
32
+ * paths in `trusted`), `{{#each list}}`, `{{#if field}}` with an optional `{{else}}`, `{{this}}`
33
+ * and `{{@index}}`. There is no expression syntax, so the interpreter needs no `eval`.
34
+ */
35
+ export declare function compileTemplate(input: TemplateSource): CompiledTemplate;
@@ -0,0 +1,82 @@
1
+ import { ProtocolError } from '../errors.js';
2
+ const TAG = /\{\{\{([^}]*)\}\}\}|\{\{([^}]*)\}\}/g;
3
+ const PATH = /^(?:this|@index|[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*)$/;
4
+ function parsePath(text, tag) {
5
+ const path = text.trim();
6
+ if (!PATH.test(path))
7
+ throw new ProtocolError('bad-template', `bad field "${path}" in ${tag}`);
8
+ return path === 'this' ? [] : path.split('.');
9
+ }
10
+ /**
11
+ * Compiles Mustache-shaped source to a JSON tree: `{{field}}` escaped, `{{{field}}}` raw (only for
12
+ * paths in `trusted`), `{{#each list}}`, `{{#if field}}` with an optional `{{else}}`, `{{this}}`
13
+ * and `{{@index}}`. There is no expression syntax, so the interpreter needs no `eval`.
14
+ */
15
+ export function compileTemplate(input) {
16
+ const trusted = [...(input.trusted ?? [])];
17
+ const root = [];
18
+ const stack = [{ kind: 'root', path: [], target: root }];
19
+ const top = () => stack[stack.length - 1];
20
+ let last = 0;
21
+ for (const match of input.source.matchAll(TAG)) {
22
+ const at = match.index;
23
+ if (at > last)
24
+ top().target.push({ t: 'text', v: input.source.slice(last, at) });
25
+ last = at + match[0].length;
26
+ if (match[1] !== undefined) {
27
+ const p = parsePath(match[1], match[0]);
28
+ const name = match[1].trim();
29
+ if (!trusted.includes(name)) {
30
+ throw new ProtocolError('bad-template', `{{{${name}}}} is not a trusted field`);
31
+ }
32
+ top().target.push({ t: 'var', p, raw: true });
33
+ continue;
34
+ }
35
+ const body = match[2].trim();
36
+ if (body.startsWith('!'))
37
+ continue;
38
+ if (body === 'else') {
39
+ const frame = top();
40
+ if (frame.kind !== 'if' || !frame.owner) {
41
+ throw new ProtocolError('bad-template', '{{else}} outside {{#if}}');
42
+ }
43
+ frame.target = frame.owner.else;
44
+ continue;
45
+ }
46
+ if (body.startsWith('#')) {
47
+ const [kind = '', ...rest] = body.slice(1).trim().split(/\s+/);
48
+ if (rest.length !== 1)
49
+ throw new ProtocolError('bad-template', `bad block ${match[0]}`);
50
+ const p = parsePath(rest[0], match[0]);
51
+ if (kind === 'each') {
52
+ const node = { t: 'each', p, body: [] };
53
+ top().target.push(node);
54
+ stack.push({ kind: 'each', path: p, target: node.body });
55
+ }
56
+ else if (kind === 'if') {
57
+ const node = { t: 'if', p, then: [], else: [] };
58
+ top().target.push(node);
59
+ stack.push({ kind: 'if', path: p, target: node.then, owner: node });
60
+ }
61
+ else
62
+ throw new ProtocolError('bad-template', `unknown block "${kind}"`);
63
+ continue;
64
+ }
65
+ if (body.startsWith('/')) {
66
+ const kind = body.slice(1).trim();
67
+ const frame = top();
68
+ if (frame.kind === 'root' || frame.kind !== kind) {
69
+ throw new ProtocolError('bad-template', `unexpected {{/${kind}}}`);
70
+ }
71
+ stack.pop();
72
+ continue;
73
+ }
74
+ top().target.push({ t: 'var', p: parsePath(body, match[0]), raw: false });
75
+ }
76
+ if (last < input.source.length)
77
+ top().target.push({ t: 'text', v: input.source.slice(last) });
78
+ if (stack.length > 1) {
79
+ throw new ProtocolError('bad-template', `unclosed {{#${top().kind}}} block`);
80
+ }
81
+ return { v: 1, trusted, nodes: root };
82
+ }
@@ -0,0 +1,9 @@
1
+ import type { CompiledTemplate } from './compile.js';
2
+ /** escapes the five characters that matter in HTML text and quoted attributes */
3
+ export declare function escapeHtml(value: string): string;
4
+ /**
5
+ * Renders a compiled template against JSON data. A name resolves only to an own property of the
6
+ * data, so `constructor` and `__proto__` print nothing, and a raw field must be in the template's
7
+ * trusted list even if the tree was edited after compilation.
8
+ */
9
+ export declare function interpretTemplate(template: CompiledTemplate, data: unknown): string;
@@ -0,0 +1,82 @@
1
+ import { ProtocolError } from '../errors.js';
2
+ const ESCAPES = {
3
+ '&': '&amp;',
4
+ '<': '&lt;',
5
+ '>': '&gt;',
6
+ '"': '&quot;',
7
+ "'": '&#39;'
8
+ };
9
+ /** escapes the five characters that matter in HTML text and quoted attributes */
10
+ export function escapeHtml(value) {
11
+ return value.replace(/[&<>"']/g, (c) => ESCAPES[c]);
12
+ }
13
+ function own(value, key) {
14
+ if (value === null || typeof value !== 'object')
15
+ return undefined;
16
+ return Object.hasOwn(value, key) ? value[key] : undefined;
17
+ }
18
+ function lookup(path, frames) {
19
+ const innermost = frames[frames.length - 1];
20
+ if (path.length === 0)
21
+ return innermost.value;
22
+ if (path[0] === '@index')
23
+ return innermost.index;
24
+ for (let i = frames.length - 1; i >= 0; i--) {
25
+ const frame = frames[i];
26
+ if (own(frame.value, path[0]) === undefined)
27
+ continue;
28
+ return path.reduce((value, key) => own(value, key), frame.value);
29
+ }
30
+ return undefined;
31
+ }
32
+ function truthy(value) {
33
+ if (Array.isArray(value))
34
+ return value.length > 0;
35
+ return !(value === undefined ||
36
+ value === null ||
37
+ value === false ||
38
+ value === '' ||
39
+ value === 0);
40
+ }
41
+ function text(value) {
42
+ return typeof value === 'string' || typeof value === 'number' ? String(value) : '';
43
+ }
44
+ function run(nodes, frames, trusted) {
45
+ let out = '';
46
+ for (const node of nodes) {
47
+ if (node.t === 'text')
48
+ out += node.v;
49
+ else if (node.t === 'var') {
50
+ const value = text(lookup(node.p, frames));
51
+ if (!node.raw)
52
+ out += escapeHtml(value);
53
+ else if (trusted.has(node.p.join('.')))
54
+ out += value;
55
+ else
56
+ throw new ProtocolError('bad-template', `{{{${node.p.join('.')}}}} is not trusted`);
57
+ }
58
+ else if (node.t === 'if') {
59
+ out += run(truthy(lookup(node.p, frames)) ? node.then : node.else, frames, trusted);
60
+ }
61
+ else {
62
+ const list = lookup(node.p, frames);
63
+ if (!Array.isArray(list))
64
+ continue;
65
+ list.forEach((value, index) => {
66
+ out += run(node.body, [...frames, { value, index }], trusted);
67
+ });
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ /**
73
+ * Renders a compiled template against JSON data. A name resolves only to an own property of the
74
+ * data, so `constructor` and `__proto__` print nothing, and a raw field must be in the template's
75
+ * trusted list even if the tree was edited after compilation.
76
+ */
77
+ export function interpretTemplate(template, data) {
78
+ if (template.v !== 1) {
79
+ throw new ProtocolError('bad-template', `unknown template version ${String(template.v)}`);
80
+ }
81
+ return run(template.nodes, [{ value: data, index: 0 }], new Set(template.trusted));
82
+ }
@@ -0,0 +1,32 @@
1
+ /** the tags that changed after a cursor, each with the cursor value of its last change */
2
+ export type VectorDiff = {
3
+ cursor: number;
4
+ changed: Record<string, number>;
5
+ /** the asked-for cursor is ahead of this vector, so the holder lost state and must start over */
6
+ reset: boolean;
7
+ };
8
+ /** a vector as JSON: the cursor and every tag's version */
9
+ export type VectorSnapshot = {
10
+ cursor: number;
11
+ versions: Record<string, number>;
12
+ };
13
+ /**
14
+ * Tag to counter, with one cursor that only moves forward. A bump moves the cursor once and stamps
15
+ * every tag in it with the new value, so a tag's version is the cursor at its last change and
16
+ * `diff(from)` is every tag stamped after `from`.
17
+ */
18
+ export declare class VersionVector {
19
+ #private;
20
+ /** rebuilds a vector from {@link VersionVector.snapshot} */
21
+ static from(snapshot: VectorSnapshot): VersionVector;
22
+ /** the version of the most recent bump */
23
+ get cursor(): number;
24
+ /** the cursor at which `tag` last changed, or 0 when it never has */
25
+ version(tag: string): number;
26
+ /** records a change to `tags` and returns the new cursor; no tags is no change */
27
+ bump(tags: readonly string[]): number;
28
+ /** every tag changed after `from` */
29
+ diff(from: number): VectorDiff;
30
+ /** the vector as JSON */
31
+ snapshot(): VectorSnapshot;
32
+ }
@@ -0,0 +1,56 @@
1
+ import { ProtocolError } from './errors.js';
2
+ /**
3
+ * Tag to counter, with one cursor that only moves forward. A bump moves the cursor once and stamps
4
+ * every tag in it with the new value, so a tag's version is the cursor at its last change and
5
+ * `diff(from)` is every tag stamped after `from`.
6
+ */
7
+ export class VersionVector {
8
+ #cursor = 0;
9
+ #versions = new Map();
10
+ /** rebuilds a vector from {@link VersionVector.snapshot} */
11
+ static from(snapshot) {
12
+ const vector = new VersionVector();
13
+ if (!Number.isSafeInteger(snapshot.cursor) || snapshot.cursor < 0) {
14
+ throw new ProtocolError('bad-sync', 'snapshot cursor must be a non-negative integer');
15
+ }
16
+ vector.#cursor = snapshot.cursor;
17
+ for (const [tag, version] of Object.entries(snapshot.versions)) {
18
+ if (!Number.isSafeInteger(version) || version < 1 || version > snapshot.cursor) {
19
+ throw new ProtocolError('bad-sync', `snapshot version for "${tag}" is out of range`);
20
+ }
21
+ vector.#versions.set(tag, version);
22
+ }
23
+ return vector;
24
+ }
25
+ /** the version of the most recent bump */
26
+ get cursor() {
27
+ return this.#cursor;
28
+ }
29
+ /** the cursor at which `tag` last changed, or 0 when it never has */
30
+ version(tag) {
31
+ return this.#versions.get(tag) ?? 0;
32
+ }
33
+ /** records a change to `tags` and returns the new cursor; no tags is no change */
34
+ bump(tags) {
35
+ if (tags.length === 0)
36
+ return this.#cursor;
37
+ this.#cursor += 1;
38
+ for (const tag of tags)
39
+ this.#versions.set(tag, this.#cursor);
40
+ return this.#cursor;
41
+ }
42
+ /** every tag changed after `from` */
43
+ diff(from) {
44
+ if (from > this.#cursor)
45
+ return { cursor: this.#cursor, changed: this.#all(), reset: true };
46
+ const changed = Object.fromEntries([...this.#versions].filter(([, version]) => version > from));
47
+ return { cursor: this.#cursor, changed, reset: false };
48
+ }
49
+ /** the vector as JSON */
50
+ snapshot() {
51
+ return { cursor: this.#cursor, versions: this.#all() };
52
+ }
53
+ #all() {
54
+ return Object.fromEntries(this.#versions);
55
+ }
56
+ }
@@ -0,0 +1,110 @@
1
+ import type { Scope } from './artifact.js';
2
+ import type { BeaconEvent } from './beacon.js';
3
+ import type { Strategy } from './route.js';
4
+ /** `serve` answers views locally; `shadow` decides and compares but lets the network answer */
5
+ export type Mode = 'serve' | 'shadow';
6
+ /** how a view was answered; `shadow` means the network answered and the reason is what local would have done */
7
+ export type ViewTier = 'local' | 'local-revalidate' | 'network' | 'fallback' | 'shadow';
8
+ /**
9
+ * Why a view went the way it did, from the worker's first check to its last: nothing stored
10
+ * (`cold`), a route the worker never serves (`principal`), within the bound (`fresh`), past a
11
+ * soft bound with the sync left for a network moment (`soft-deferred`) or sent now (`soft-sync`),
12
+ * past a hard bound and synced first (`hard-sync`), past it offline and shown anyway
13
+ * (`offline-stale`), a stored copy a change outdated (`invalidated`, `stale-after-sync`), a hard
14
+ * route offline that refuses (`hard-refused`), or a render the worker declined (`refused`). A
15
+ * page the visitor had not opened, shown with no request from a catalogue entry that came with an
16
+ * earlier flush, is `catalogue`.
17
+ */
18
+ export type ViewReason = 'cold' | 'principal' | 'fresh' | 'catalogue' | 'soft-deferred' | 'soft-sync' | 'hard-sync' | 'offline-stale' | 'invalidated' | 'stale-after-sync' | 'hard-refused' | 'refused';
19
+ /** the tier a reason has when the worker serves; a shadow view keeps the reason and drops the tier */
20
+ export declare const REASON_TIER: Record<ViewReason, Exclude<ViewTier, 'shadow'>>;
21
+ /** the layout engine, which decides what the browser does with a worker: not the vendor */
22
+ export type Engine = 'chromium' | 'firefox' | 'webkit' | 'other';
23
+ /** one page view on a declared route, as the worker reports it in `spool.view` */
24
+ export type ViewEvent = {
25
+ /** names this view, so the page's later report of its cross-origin loads can be joined to it */
26
+ id: string;
27
+ tier: ViewTier;
28
+ reason: ViewReason;
29
+ /** seconds since the stored copy was last known good, or null when none was stored */
30
+ staleSec: number | null;
31
+ engine: Engine;
32
+ scope: Scope;
33
+ strategy: Strategy;
34
+ /** the matched route pattern */
35
+ route: string;
36
+ /** whether the local render differed from the network one; null when no local render was made */
37
+ mismatch: boolean | null;
38
+ /** milliseconds since this worker instance started */
39
+ swAgeMs: number;
40
+ /** milliseconds since this worker's previous view, or null for its first */
41
+ gapMs: number | null;
42
+ /**
43
+ * Where the visitor came from: the referring page's route pattern when it is same-origin and
44
+ * matches a declared route, `external` for a cross-origin referrer, omitted otherwise. Never a path.
45
+ */
46
+ from?: string;
47
+ /**
48
+ * Cross-origin resources the page loaded during the view, as the page runtime counted them from
49
+ * `PerformanceResourceTiming` when it was hidden. Without `Timing-Allow-Origin` such an entry has a
50
+ * transfer size of 0 whether it came from cache or network, so a cache hit counts: this is an upper
51
+ * bound on cross-origin network requests. Null until the page reports, and when it never does.
52
+ */
53
+ crossOriginLoads: number | null;
54
+ };
55
+ /** a view with the device time it was recorded at, epoch milliseconds */
56
+ export type TimedView = ViewEvent & {
57
+ at: number;
58
+ /** cross-origin loads by origin, when the page's report named them */
59
+ crossOriginOrigins?: Record<string, number>;
60
+ };
61
+ /** longest route pattern a view may name; a longer one is not read as a view */
62
+ export declare const MAX_ROUTE_CHARS = 256;
63
+ /** the `from` of a view whose referrer is another origin */
64
+ export declare const FROM_EXTERNAL = "external";
65
+ /** the `path` a view carries inside a beacon batch */
66
+ export declare const VIEW_PATH = "/.spool/view";
67
+ /** the `path` of the page's later report of a view's cross-origin loads */
68
+ export declare const LOADS_PATH = "/.spool/loads";
69
+ /** most origins a loads report names; the page keeps the busiest */
70
+ export declare const MAX_LOAD_ORIGINS = 32;
71
+ /**
72
+ * a page's count of the cross-origin loads of view `view`, and how many came from each origin
73
+ * (origins only, never paths or query strings)
74
+ */
75
+ export type LoadsReport = {
76
+ view: string;
77
+ count: number;
78
+ at: number;
79
+ origins?: Record<string, number>;
80
+ };
81
+ /** a loads report as a queued beacon */
82
+ export declare function loadsToBeacon(view: string, count: number, at: number, origins?: Record<string, number>): BeaconEvent;
83
+ /** the report inside a beacon, or null when it is another request or does not validate */
84
+ export declare function loadsFromBeacon(event: BeaconEvent): LoadsReport | null;
85
+ /**
86
+ * The views in `events` with their cross-origin counts filled in from the loads reports among
87
+ * them. A report that arrives in a later batch than its view needs the whole stream, so pass every
88
+ * event; the last report for a view wins. A view with no report keeps null.
89
+ */
90
+ export declare function viewsWithLoads(events: readonly BeaconEvent[]): TimedView[];
91
+ /** the view as a queued beacon, so it rides the same flush as every other held request */
92
+ export declare function viewToBeacon(view: ViewEvent, at: number): BeaconEvent;
93
+ /** the view inside a beacon, or null when it is another request or does not validate */
94
+ export declare function viewFromBeacon(event: BeaconEvent): TimedView | null;
95
+ /**
96
+ * The engine behind a user agent. Every browser on iOS runs WebKit, whatever its name says, so
97
+ * the iOS tokens are checked first.
98
+ */
99
+ export declare function engineOf(userAgent: string): Engine;
100
+ /** where a view stopped on the way to a zero-network render */
101
+ export type Funnel = 'ineligible' | 'cold' | 'unusable' | 'local';
102
+ /**
103
+ * Where a view stopped: on a route the worker never serves (`ineligible`), with nothing stored
104
+ * (`cold`), with a copy it could not show without the network (`unusable`), or shown with no
105
+ * request (`local`). A view is local only when no cross-origin resource loaded during it, which the
106
+ * page must have reported as 0: a count above 0 or no report makes it `unusable`, whatever the worker
107
+ * did. A shadow view that would have been local but rendered differently from the network is
108
+ * `unusable` too.
109
+ */
110
+ export declare function funnelOf(view: Pick<ViewEvent, 'reason' | 'mismatch' | 'crossOriginLoads'>): Funnel;