@drupflare/spool 0.0.0-stage → 0.2.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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1749 -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/media/embeds.d.ts +59 -0
  21. package/dist/media/embeds.js +120 -0
  22. package/dist/media/headers.d.ts +13 -0
  23. package/dist/media/headers.js +44 -0
  24. package/dist/media/html.d.ts +27 -0
  25. package/dist/media/html.js +93 -0
  26. package/dist/media/image.d.ts +222 -0
  27. package/dist/media/image.js +413 -0
  28. package/dist/media/index.d.ts +6 -0
  29. package/dist/media/index.js +6 -0
  30. package/dist/media/lazy.d.ts +26 -0
  31. package/dist/media/lazy.js +74 -0
  32. package/dist/media/responsive.d.ts +45 -0
  33. package/dist/media/responsive.js +98 -0
  34. package/dist/media/video.d.ts +30 -0
  35. package/dist/media/video.js +75 -0
  36. package/dist/node/listener.d.ts +19 -0
  37. package/dist/node/listener.js +76 -0
  38. package/dist/protocol/artifact.d.ts +54 -0
  39. package/dist/protocol/artifact.js +79 -0
  40. package/dist/protocol/assembly.d.ts +34 -0
  41. package/dist/protocol/assembly.js +72 -0
  42. package/dist/protocol/beacon.d.ts +59 -0
  43. package/dist/protocol/beacon.js +86 -0
  44. package/dist/protocol/collector.d.ts +41 -0
  45. package/dist/protocol/collector.js +84 -0
  46. package/dist/protocol/config.d.ts +89 -0
  47. package/dist/protocol/config.js +13 -0
  48. package/dist/protocol/envelope.d.ts +47 -0
  49. package/dist/protocol/envelope.js +162 -0
  50. package/dist/protocol/errors.d.ts +7 -0
  51. package/dist/protocol/errors.js +9 -0
  52. package/dist/protocol/graph.d.ts +81 -0
  53. package/dist/protocol/graph.js +201 -0
  54. package/dist/protocol/index.d.ts +19 -0
  55. package/dist/protocol/index.js +19 -0
  56. package/dist/protocol/manifest.d.ts +29 -0
  57. package/dist/protocol/manifest.js +94 -0
  58. package/dist/protocol/normalise.d.ts +20 -0
  59. package/dist/protocol/normalise.js +29 -0
  60. package/dist/protocol/pattern.d.ts +12 -0
  61. package/dist/protocol/pattern.js +82 -0
  62. package/dist/protocol/provision.d.ts +100 -0
  63. package/dist/protocol/provision.js +105 -0
  64. package/dist/protocol/route.d.ts +179 -0
  65. package/dist/protocol/route.js +135 -0
  66. package/dist/protocol/sync.d.ts +31 -0
  67. package/dist/protocol/sync.js +87 -0
  68. package/dist/protocol/tag.d.ts +12 -0
  69. package/dist/protocol/tag.js +26 -0
  70. package/dist/protocol/template/compile.d.ts +35 -0
  71. package/dist/protocol/template/compile.js +82 -0
  72. package/dist/protocol/template/interpret.d.ts +9 -0
  73. package/dist/protocol/template/interpret.js +82 -0
  74. package/dist/protocol/vector.d.ts +32 -0
  75. package/dist/protocol/vector.js +56 -0
  76. package/dist/protocol/view.d.ts +110 -0
  77. package/dist/protocol/view.js +201 -0
  78. package/dist/proxy/dictionary.d.ts +58 -0
  79. package/dist/proxy/dictionary.js +197 -0
  80. package/dist/proxy/eligible.d.ts +45 -0
  81. package/dist/proxy/eligible.js +96 -0
  82. package/dist/proxy/index.d.ts +5 -0
  83. package/dist/proxy/index.js +5 -0
  84. package/dist/proxy/proxy.d.ts +133 -0
  85. package/dist/proxy/proxy.js +507 -0
  86. package/dist/proxy/purge.d.ts +10 -0
  87. package/dist/proxy/purge.js +66 -0
  88. package/dist/proxy/tags.d.ts +8 -0
  89. package/dist/proxy/tags.js +36 -0
  90. package/dist/report/derive.d.ts +223 -0
  91. package/dist/report/derive.js +494 -0
  92. package/dist/report/economics.d.ts +14 -0
  93. package/dist/report/economics.js +24 -0
  94. package/dist/report/index.d.ts +9 -0
  95. package/dist/report/index.js +9 -0
  96. package/dist/report/inputs.d.ts +141 -0
  97. package/dist/report/inputs.js +216 -0
  98. package/dist/report/ledger.d.ts +169 -0
  99. package/dist/report/ledger.js +278 -0
  100. package/dist/report/measurement.d.ts +48 -0
  101. package/dist/report/measurement.js +117 -0
  102. package/dist/report/model.d.ts +42 -0
  103. package/dist/report/model.js +74 -0
  104. package/dist/report/thirdparty.d.ts +62 -0
  105. package/dist/report/thirdparty.js +107 -0
  106. package/dist/report/traffic.d.ts +140 -0
  107. package/dist/report/traffic.js +228 -0
  108. package/dist/report/trim.d.ts +81 -0
  109. package/dist/report/trim.js +105 -0
  110. package/dist/server/beacon.d.ts +20 -0
  111. package/dist/server/beacon.js +47 -0
  112. package/dist/server/embedded.d.ts +6 -0
  113. package/dist/server/embedded.js +6 -0
  114. package/dist/server/ga4.d.ts +70 -0
  115. package/dist/server/ga4.js +165 -0
  116. package/dist/server/identity.d.ts +12 -0
  117. package/dist/server/identity.js +17 -0
  118. package/dist/server/index.d.ts +7 -0
  119. package/dist/server/index.js +7 -0
  120. package/dist/server/sink.d.ts +56 -0
  121. package/dist/server/sink.js +133 -0
  122. package/dist/server/size.d.ts +7 -0
  123. package/dist/server/size.js +18 -0
  124. package/dist/server/spool.d.ts +97 -0
  125. package/dist/server/spool.js +463 -0
  126. package/dist/server/stub.d.ts +9 -0
  127. package/dist/server/stub.js +19 -0
  128. package/dist/server/sync.d.ts +12 -0
  129. package/dist/server/sync.js +48 -0
  130. package/dist/server/work.d.ts +22 -0
  131. package/dist/server/work.js +30 -0
  132. package/dist/stores/durable-object.d.ts +19 -0
  133. package/dist/stores/durable-object.js +53 -0
  134. package/dist/stores/index.d.ts +2 -0
  135. package/dist/stores/index.js +2 -0
  136. package/dist/stores/memory.d.ts +4 -0
  137. package/dist/stores/memory.js +10 -0
  138. package/dist/stores/version-store.d.ts +11 -0
  139. package/dist/stores/version-store.js +1 -0
  140. package/dist/sw/analytics.d.ts +81 -0
  141. package/dist/sw/analytics.js +275 -0
  142. package/dist/sw/collect.d.ts +8 -0
  143. package/dist/sw/collect.js +33 -0
  144. package/dist/sw/core.d.ts +1 -0
  145. package/dist/sw/core.js +3 -0
  146. package/dist/sw/freshness.d.ts +15 -0
  147. package/dist/sw/freshness.js +20 -0
  148. package/dist/sw/graph/index.d.ts +67 -0
  149. package/dist/sw/graph/index.js +170 -0
  150. package/dist/sw/graph/invalidate.d.ts +23 -0
  151. package/dist/sw/graph/invalidate.js +109 -0
  152. package/dist/sw/graph/projections.d.ts +7 -0
  153. package/dist/sw/graph/projections.js +9 -0
  154. package/dist/sw/graph/records.d.ts +7 -0
  155. package/dist/sw/graph/records.js +9 -0
  156. package/dist/sw/graph/store.d.ts +32 -0
  157. package/dist/sw/graph/store.js +52 -0
  158. package/dist/sw/idb.d.ts +8 -0
  159. package/dist/sw/idb.js +117 -0
  160. package/dist/sw/index.d.ts +2 -0
  161. package/dist/sw/index.js +1 -0
  162. package/dist/sw/partition.d.ts +21 -0
  163. package/dist/sw/partition.js +137 -0
  164. package/dist/sw/policy.d.ts +8 -0
  165. package/dist/sw/policy.js +24 -0
  166. package/dist/sw/provision.d.ts +39 -0
  167. package/dist/sw/provision.js +61 -0
  168. package/dist/sw/render.d.ts +21 -0
  169. package/dist/sw/render.js +53 -0
  170. package/dist/sw/replica.d.ts +77 -0
  171. package/dist/sw/replica.js +299 -0
  172. package/dist/sw/router.d.ts +42 -0
  173. package/dist/sw/router.js +48 -0
  174. package/dist/sw/routing.d.ts +23 -0
  175. package/dist/sw/routing.js +48 -0
  176. package/dist/sw/runtime.d.ts +112 -0
  177. package/dist/sw/runtime.js +1070 -0
  178. package/dist/sw/scheduler.d.ts +83 -0
  179. package/dist/sw/scheduler.js +149 -0
  180. package/dist/sw/seal.d.ts +37 -0
  181. package/dist/sw/seal.js +183 -0
  182. package/dist/sw/serve.d.ts +15 -0
  183. package/dist/sw/serve.js +63 -0
  184. package/dist/sw/shadow.d.ts +16 -0
  185. package/dist/sw/shadow.js +27 -0
  186. package/dist/sw/static.d.ts +17 -0
  187. package/dist/sw/static.js +81 -0
  188. package/dist/sw/storage.d.ts +64 -0
  189. package/dist/sw/storage.js +34 -0
  190. package/dist/sw/thirdparty.d.ts +17 -0
  191. package/dist/sw/thirdparty.js +36 -0
  192. package/dist/trim/css.d.ts +38 -0
  193. package/dist/trim/css.js +328 -0
  194. package/dist/trim/index.d.ts +3 -0
  195. package/dist/trim/index.js +3 -0
  196. package/dist/trim/manifest.d.ts +67 -0
  197. package/dist/trim/manifest.js +134 -0
  198. package/dist/trim/tokens.d.ts +47 -0
  199. package/dist/trim/tokens.js +142 -0
  200. package/dist/version.d.ts +2 -0
  201. package/dist/version.js +3 -0
  202. package/package.json +150 -5
@@ -0,0 +1,105 @@
1
+ /** the defaults a config without `provision` gets */
2
+ export const DEFAULT_PRIOR = {
3
+ reuse: 0.5,
4
+ futureViews: 2,
5
+ requestBytes: 2000,
6
+ artifactBytes: 20_000,
7
+ avoidedBytes: 17_054,
8
+ changesPerDay: 1
9
+ };
10
+ /** the prior with whatever the config overrides */
11
+ export function priorFrom(config) {
12
+ const { hot: _hot, ...numbers } = config ?? {};
13
+ return { ...DEFAULT_PRIOR, ...numbers };
14
+ }
15
+ /** a cost as one number: its bytes plus `requestBytes` for each request */
16
+ export function weigh(cost, requestBytes) {
17
+ return cost.bytes + cost.requests * requestBytes;
18
+ }
19
+ const NONE = { bytes: 0, requests: 0 };
20
+ /**
21
+ * `P_reuse x N_future x C_avoided - C_provision - C_maintain`, each cost weighed in bytes. A
22
+ * positive number means fetching it ahead moves fewer bytes and requests than leaving it to the
23
+ * network.
24
+ */
25
+ export function benefit(opportunity, prior = DEFAULT_PRIOR) {
26
+ const reuse = opportunity.reuse ?? prior.reuse;
27
+ const future = opportunity.futureViews ?? prior.futureViews;
28
+ const weigh_ = (cost) => weigh(cost, prior.requestBytes);
29
+ return (reuse * future * weigh_(opportunity.avoided) -
30
+ weigh_(opportunity.provision) -
31
+ weigh_(opportunity.maintain ?? NONE));
32
+ }
33
+ const RANK = {
34
+ layout: 0,
35
+ template: 0,
36
+ asset: 0,
37
+ route: 1,
38
+ expansion: 2
39
+ };
40
+ /**
41
+ * What to fetch, in order: shared layout, templates and immutable assets, then hot routes, then
42
+ * incremental expansion, each group by benefit with the id as tie-break. An opportunity whose
43
+ * benefit is not positive is left out.
44
+ */
45
+ export function plan(opportunities, prior = DEFAULT_PRIOR) {
46
+ return opportunities
47
+ .map((o) => ({ ...o, benefit: benefit(o, prior) }))
48
+ .filter((o) => o.benefit > 0)
49
+ .sort((a, b) => RANK[a.kind] - RANK[b.kind] ||
50
+ b.benefit - a.benefit ||
51
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
52
+ }
53
+ /** joules to move one byte: SWD v4, 0.194 kWh/GB over decimal GB (L2) */
54
+ export const JOULES_PER_BYTE = 6.984e-4;
55
+ /** joules of the origin request a local view avoids (L1, `ORIGIN_J.conventional` in `src/report/inputs.ts`) */
56
+ export const ORIGIN_JOULES = 0.455;
57
+ /** the default cap on one catalogue bundle, in compressed bytes */
58
+ export const DEFAULT_CATALOGUE_BYTES = 32_768;
59
+ /**
60
+ * The share of devices that must open a catalogue entry for it to repay its transfer:
61
+ * `k*E / (k*D + o)`, with `E` the entry's compressed bytes and `D` the document it replaces. At 1
62
+ * or above the entry never pays.
63
+ */
64
+ export function entryBreakEven(entryBytes, documentBytes) {
65
+ return (JOULES_PER_BYTE * entryBytes) / (JOULES_PER_BYTE * documentBytes + ORIGIN_JOULES);
66
+ }
67
+ const sound = (n) => Number.isFinite(n) && n >= 0;
68
+ /** expected joules of shipping an entry: `p * (k*D + o) - k*E` */
69
+ function expectedNet(c) {
70
+ return (c.p * (JOULES_PER_BYTE * c.documentBytes + ORIGIN_JOULES) - JOULES_PER_BYTE * c.entryBytes);
71
+ }
72
+ /**
73
+ * The candidates worth shipping: those whose `p` is at least their break-even, best expected net
74
+ * first, kept while their entry bytes fit under `capBytes`. A candidate that does not fit is
75
+ * skipped and a smaller one may still go. A path is chosen once. A candidate with a `p` outside 0
76
+ * to 1 or a negative or non-finite size is never chosen.
77
+ */
78
+ export function chooseEntries(candidates, options) {
79
+ const paying = candidates
80
+ .filter((c) => sound(c.entryBytes) &&
81
+ sound(c.documentBytes) &&
82
+ c.p >= 0 &&
83
+ c.p <= 1 &&
84
+ c.p >= entryBreakEven(c.entryBytes, c.documentBytes))
85
+ .sort((a, b) => expectedNet(b) - expectedNet(a) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
86
+ const out = [];
87
+ const seen = new Set();
88
+ let bytes = 0;
89
+ for (const c of paying) {
90
+ if (seen.has(c.path) || bytes + c.entryBytes > options.capBytes)
91
+ continue;
92
+ seen.add(c.path);
93
+ bytes += c.entryBytes;
94
+ out.push(c);
95
+ }
96
+ return out;
97
+ }
98
+ /**
99
+ * P_reuse from aggregate telemetry: the share of a route's views that found a stored copy, pulled
100
+ * toward the prior by `weight` pseudo-views so a few views do not decide it. The telemetry
101
+ * has no device identity, so this is a share of views, not of provisioned copies.
102
+ */
103
+ export function smoothReuse(warmViews, coldViews, prior = DEFAULT_PRIOR, weight = 10) {
104
+ return (prior.reuse * weight + warmViews) / (weight + warmViews + coldViews);
105
+ }
@@ -0,0 +1,179 @@
1
+ import type { AssemblyBody, Scope } from './artifact.js';
2
+ import type { Collector } from './graph.js';
3
+ import { type Params } from './pattern.js';
4
+ import { type CompiledTemplate, type TemplateSource } from './template/compile.js';
5
+ import type { Mode } from './view.js';
6
+ /**
7
+ * how a route is answered locally. `projection` renders stored JSON through a function the site
8
+ * bundles into its own worker; `data` answers a GET for JSON, such as an API read, with no request.
9
+ */
10
+ export type Strategy = 'assembly' | 'template' | 'static' | 'projection' | 'data';
11
+ /**
12
+ * how long a principal route's copy may live on the device: `persistent` seals it under a key that
13
+ * stays in IndexedDB, `session` under a key held in the worker's memory, which a worker restart loses
14
+ */
15
+ export type Retention = 'persistent' | 'session';
16
+ /** `hard` blocks on a sync once `maxStale` passes; `soft` shows first and syncs once after */
17
+ export type FreshnessMode = 'hard' | 'soft';
18
+ /** the staleness contract of a route; `maxStale` is in seconds */
19
+ export type Freshness = {
20
+ maxStale: number;
21
+ mode: FreshnessMode;
22
+ };
23
+ /** whether the worker may show a snapshot it cannot validate because the network is down */
24
+ export type OfflineRule = 'serve' | 'refuse';
25
+ /** who is asking, as the app's `identity.resolve` reports it */
26
+ export type Identity = {
27
+ principal: string;
28
+ roles?: readonly string[];
29
+ };
30
+ /** when a soft route past its bound refreshes: right after the view, or at the next network moment */
31
+ export type SyncRule = 'background' | 'deferred';
32
+ /**
33
+ * What `depends` and `load` receive. `record` and `projection` put data into the replica once
34
+ * and return the reference to embed in the page's data; see {@link Collector}.
35
+ */
36
+ export type RouteContext = {
37
+ request: Request;
38
+ url: URL;
39
+ params: Params;
40
+ identity: Identity | null;
41
+ } & Pick<Collector, 'record' | 'projection'>;
42
+ /** public routes default to 15 minutes soft, principal routes to 5 minutes hard */
43
+ export declare const DEFAULT_FRESHNESS: Record<Scope, Freshness>;
44
+ /** a page a route's catalogue suggests, with the share of devices expected to open it next */
45
+ export type CatalogueGuess = {
46
+ path: string;
47
+ p: number;
48
+ };
49
+ /** the declaration fields every strategy shares */
50
+ export type RouteCommon = {
51
+ scope?: Scope;
52
+ freshness?: Partial<Freshness>;
53
+ /** keep the artifact across worker restarts; default true */
54
+ persist?: boolean;
55
+ offline?: OfflineRule;
56
+ /** `shadow` renders locally and compares but never serves; the server's mode when absent */
57
+ mode?: Mode;
58
+ /** how a soft route past its bound refreshes; default `background` */
59
+ sync?: SyncRule;
60
+ /** tags the artifact is built from; records and projections the load registers are added */
61
+ depends?(ctx: RouteContext): readonly string[] | Promise<readonly string[]>;
62
+ /** a principal route's at-rest key; default `session` */
63
+ retention?: Retention;
64
+ /** overrides the provisioning priors for this route when the server decides whether to ship it */
65
+ provision?: {
66
+ reuse?: number;
67
+ futureViews?: number;
68
+ };
69
+ /**
70
+ * Pages a device on this route may open next, each with the share of devices expected to
71
+ * (from the site's own `nextShare` over the sink, link position, or a fixed prior). The server
72
+ * ships the data of those that repay their transfer, never their HTML. Only `template`,
73
+ * `projection` and `data` routes can be entries.
74
+ */
75
+ catalogue?(ctx: RouteContext): readonly CatalogueGuess[] | Promise<readonly CatalogueGuess[]>;
76
+ /** compressed bytes of the document this route renders, which a catalogue entry for it replaces; the server's prior when absent */
77
+ documentBytes?: number;
78
+ };
79
+ /** a route answered by filling placeholders in a stored shell */
80
+ export type AssemblyRoute = RouteCommon & {
81
+ strategy: 'assembly';
82
+ load(ctx: RouteContext): AssemblyBody | Promise<AssemblyBody>;
83
+ };
84
+ /** a route answered by rendering stored JSON through a compiled template */
85
+ export type TemplateRoute = RouteCommon & {
86
+ strategy: 'template';
87
+ template: TemplateSource;
88
+ load(ctx: RouteContext): unknown;
89
+ };
90
+ /**
91
+ * A route for a file the application serves as is, such as a page or an asset with fixed bytes.
92
+ * The worker stores the response it fetched and shows it with no request until a tag in
93
+ * `depends` changes or the freshness bound passes. It has no `load`, is always public, and
94
+ * is answered in `serve` mode only.
95
+ */
96
+ export type StaticRoute = Omit<RouteCommon, 'scope' | 'persist' | 'mode' | 'retention'> & {
97
+ strategy: 'static';
98
+ scope?: undefined;
99
+ persist?: undefined;
100
+ mode?: undefined;
101
+ load?: undefined;
102
+ };
103
+ /**
104
+ * A route whose stored JSON a bundled worker renders into a page: `serve(config, renderers)` from
105
+ * `@drupflare/spool/sw` takes a renderer keyed by this pattern. Without one the worker refuses the
106
+ * local view and the network answers.
107
+ */
108
+ export type ProjectionRoute = RouteCommon & {
109
+ strategy: 'projection';
110
+ load(ctx: RouteContext): unknown;
111
+ };
112
+ /**
113
+ * A route for a JSON read. The worker answers a GET (not a navigation) from the stored value with
114
+ * `JSON.stringify`, so the application's own handler has to return the same JSON `load` does.
115
+ */
116
+ export type DataRoute = RouteCommon & {
117
+ strategy: 'data';
118
+ load(ctx: RouteContext): unknown;
119
+ /** the content type of the local answer; default `application/json` */
120
+ contentType?: string;
121
+ };
122
+ /** what `defineRoute` accepts */
123
+ export type RouteDeclaration = AssemblyRoute | TemplateRoute | StaticRoute | ProjectionRoute | DataRoute;
124
+ /** a validated route with every default applied */
125
+ export type Route = {
126
+ pattern: string;
127
+ strategy: Strategy;
128
+ scope: Scope;
129
+ freshness: Freshness;
130
+ persist: boolean;
131
+ offline: OfflineRule;
132
+ mode?: Mode;
133
+ sync: SyncRule;
134
+ retention?: Retention;
135
+ contentType?: string;
136
+ provision?: {
137
+ reuse?: number;
138
+ futureViews?: number;
139
+ };
140
+ template?: CompiledTemplate;
141
+ catalogue?: RouteCommon['catalogue'];
142
+ documentBytes?: number;
143
+ depends(ctx: RouteContext): readonly string[] | Promise<readonly string[]>;
144
+ load(ctx: RouteContext): unknown;
145
+ };
146
+ /** the part of a route the service worker needs; functions stay on the server */
147
+ export type SerializedRoute = {
148
+ pattern: string;
149
+ strategy: Strategy;
150
+ scope: Scope;
151
+ freshness: Freshness;
152
+ persist: boolean;
153
+ offline: OfflineRule;
154
+ mode?: Mode;
155
+ sync: SyncRule;
156
+ /** a principal route's at-rest key; absent on a public route */
157
+ retention?: Retention;
158
+ /** the content type a `data` route answers with, when it is not JSON */
159
+ type?: string;
160
+ /** what a manifest route's file is at now; the worker compares it with the stored copy */
161
+ version?: string;
162
+ /** the route declares a `catalogue`, so the worker asks for one when a flush goes out on it */
163
+ catalogue?: true;
164
+ };
165
+ /**
166
+ * Declares a route. Validates the pattern and the freshness contract, compiles a template, and
167
+ * fills the defaults: freshness by scope, and `offline` as `serve` for public, `refuse` for
168
+ * principal.
169
+ */
170
+ export declare function defineRoute(pattern: string, declaration: RouteDeclaration): Route;
171
+ /** the first route whose pattern fits `path`, with the params it captured */
172
+ export declare function matchRoute<T extends {
173
+ pattern: string;
174
+ }>(routes: readonly T[], path: string): {
175
+ route: T;
176
+ params: Params;
177
+ } | null;
178
+ /** strips a route to what the service worker config carries */
179
+ export declare function serializeRoute(route: Route): SerializedRoute;
@@ -0,0 +1,135 @@
1
+ import { ProtocolError } from './errors.js';
2
+ import { checkPattern, matchPattern } from './pattern.js';
3
+ import { compileTemplate } from './template/compile.js';
4
+ /** public routes default to 15 minutes soft, principal routes to 5 minutes hard */
5
+ export const DEFAULT_FRESHNESS = {
6
+ public: { maxStale: 900, mode: 'soft' },
7
+ principal: { maxStale: 300, mode: 'hard' }
8
+ };
9
+ function bad(pattern, message) {
10
+ throw new ProtocolError('bad-route', `${pattern}: ${message}`);
11
+ }
12
+ /**
13
+ * Declares a route. Validates the pattern and the freshness contract, compiles a template, and
14
+ * fills the defaults: freshness by scope, and `offline` as `serve` for public, `refuse` for
15
+ * principal.
16
+ */
17
+ export function defineRoute(pattern, declaration) {
18
+ checkPattern(pattern);
19
+ const strategy = declaration.strategy;
20
+ if (!['assembly', 'template', 'static', 'projection', 'data'].includes(strategy)) {
21
+ return bad(pattern, `unknown strategy "${strategy}"`);
22
+ }
23
+ if (declaration.strategy === 'static') {
24
+ if (declaration.scope !== undefined)
25
+ return bad(pattern, 'a static route is always public');
26
+ if (declaration.persist !== undefined)
27
+ return bad(pattern, 'a static route is always kept');
28
+ if (declaration.mode !== undefined)
29
+ return bad(pattern, 'a static route has no mode');
30
+ if (declaration.load !== undefined)
31
+ return bad(pattern, 'a static route has no load');
32
+ }
33
+ const scope = declaration.scope ?? 'public';
34
+ if (scope !== 'public' && scope !== 'principal')
35
+ return bad(pattern, `unknown scope "${scope}"`);
36
+ const freshness = { ...DEFAULT_FRESHNESS[scope], ...declaration.freshness };
37
+ if (!Number.isFinite(freshness.maxStale) || freshness.maxStale <= 0) {
38
+ return bad(pattern, 'freshness.maxStale must be a positive number of seconds');
39
+ }
40
+ if (freshness.mode !== 'hard' && freshness.mode !== 'soft') {
41
+ return bad(pattern, `unknown freshness mode "${String(freshness.mode)}"`);
42
+ }
43
+ const offline = declaration.offline ?? (scope === 'public' ? 'serve' : 'refuse');
44
+ if (offline !== 'serve' && offline !== 'refuse') {
45
+ return bad(pattern, `unknown offline rule "${String(offline)}"`);
46
+ }
47
+ const sync = declaration.sync ?? 'background';
48
+ if (sync !== 'background' && sync !== 'deferred') {
49
+ return bad(pattern, `unknown sync rule "${String(sync)}"`);
50
+ }
51
+ if (declaration.mode !== undefined &&
52
+ declaration.mode !== 'serve' &&
53
+ declaration.mode !== 'shadow') {
54
+ return bad(pattern, `unknown mode "${String(declaration.mode)}"`);
55
+ }
56
+ if (declaration.strategy !== 'static' && typeof declaration.load !== 'function') {
57
+ return bad(pattern, 'load is required');
58
+ }
59
+ const declared = declaration.strategy === 'static' ? undefined : declaration.retention;
60
+ const retention = declared ?? 'session';
61
+ if (retention !== 'persistent' && retention !== 'session') {
62
+ return bad(pattern, `unknown retention "${String(retention)}"`);
63
+ }
64
+ if (declared !== undefined && scope !== 'principal') {
65
+ return bad(pattern, 'retention applies to a principal route');
66
+ }
67
+ const route = {
68
+ pattern,
69
+ strategy: declaration.strategy,
70
+ scope,
71
+ freshness,
72
+ persist: declaration.persist ?? true,
73
+ offline,
74
+ sync,
75
+ depends: declaration.depends ?? (() => []),
76
+ load: declaration.load ?? (() => undefined)
77
+ };
78
+ if (declaration.mode)
79
+ route.mode = declaration.mode;
80
+ if (scope === 'principal')
81
+ route.retention = retention;
82
+ if (declaration.provision)
83
+ route.provision = declaration.provision;
84
+ if (declaration.catalogue !== undefined) {
85
+ if (typeof declaration.catalogue !== 'function')
86
+ return bad(pattern, 'catalogue must be a function');
87
+ route.catalogue = declaration.catalogue;
88
+ }
89
+ if (declaration.documentBytes !== undefined) {
90
+ if (!Number.isFinite(declaration.documentBytes) || declaration.documentBytes < 0) {
91
+ return bad(pattern, 'documentBytes must be a non-negative number');
92
+ }
93
+ route.documentBytes = declaration.documentBytes;
94
+ }
95
+ if (declaration.strategy === 'data' && declaration.contentType) {
96
+ route.contentType = declaration.contentType;
97
+ }
98
+ if (declaration.strategy === 'template') {
99
+ if (!declaration.template)
100
+ return bad(pattern, 'a template route needs a template');
101
+ route.template = compileTemplate(declaration.template);
102
+ }
103
+ return route;
104
+ }
105
+ /** the first route whose pattern fits `path`, with the params it captured */
106
+ export function matchRoute(routes, path) {
107
+ for (const route of routes) {
108
+ const params = matchPattern(route.pattern, path);
109
+ if (params)
110
+ return { route, params };
111
+ }
112
+ return null;
113
+ }
114
+ /** strips a route to what the service worker config carries */
115
+ export function serializeRoute(route) {
116
+ const { pattern, strategy, scope, freshness, persist, offline, sync } = route;
117
+ const out = {
118
+ pattern,
119
+ strategy,
120
+ scope,
121
+ freshness: { ...freshness },
122
+ persist,
123
+ offline,
124
+ sync
125
+ };
126
+ if (route.mode)
127
+ out.mode = route.mode;
128
+ if (route.retention)
129
+ out.retention = route.retention;
130
+ if (route.contentType)
131
+ out.type = route.contentType;
132
+ if (route.catalogue)
133
+ out.catalogue = true;
134
+ return out;
135
+ }
@@ -0,0 +1,31 @@
1
+ import { PROTOCOL_VERSION } from './artifact.js';
2
+ import type { VectorDiff } from './vector.js';
3
+ /** an artifact id rides the vector as this tag, so an explicit drop shares the sync cursor */
4
+ export declare const ARTIFACT_TAG_PREFIX = "spool:artifact:";
5
+ /** the body of `/.spool/sync` */
6
+ export type SyncResponse = {
7
+ protocol: typeof PROTOCOL_VERSION;
8
+ cursor: number;
9
+ /** tag to the vector version of its last change */
10
+ changed: Record<string, number>;
11
+ /** artifact ids the server dropped outright */
12
+ dropped: string[];
13
+ /** the server's vector is behind the asked-for cursor: drop everything held */
14
+ reset: boolean;
15
+ /** answers a `need` request: `changed` covers only the ids asked about and the cursor is not the holder's to take */
16
+ partial?: boolean;
17
+ };
18
+ /** most ids one `need` request may name; a worker needing more falls back to a full sync */
19
+ export declare const MAX_NEED = 64;
20
+ /** most ids one `have` list may carry on an artifact request */
21
+ export declare const MAX_HAVE = 256;
22
+ /** the vector tag that drops artifact `id` */
23
+ export declare function artifactTag(id: string): string;
24
+ /** splits a vector diff into changed tags and dropped artifact ids */
25
+ export declare function toSyncResponse(diff: VectorDiff): SyncResponse;
26
+ /** `id@version` pairs for the `need` and `have` query parameters, ids percent-encoded */
27
+ export declare function encodeHeld(held: Readonly<Record<string, number>>): string;
28
+ /** reads {@link encodeHeld} back; throws `ProtocolError` on a malformed pair or more than `limit` */
29
+ export declare function parseHeld(text: string, limit: number): Record<string, number>;
30
+ /** validates JSON from `/.spool/sync` */
31
+ export declare function parseSyncResponse(value: unknown): SyncResponse;
@@ -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;