@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,299 @@
1
+ import { CLEAR_ALL } from '../protocol/envelope.js';
2
+ import { ARTIFACT_TAG_PREFIX, artifactTag, MAX_HAVE, MAX_NEED } from '../protocol/sync.js';
3
+ import { isCurrent, validatedAt } from './freshness.js';
4
+ import { Graph, usesGraph } from './graph/index.js';
5
+ import { MAX_POLICY_PATHS } from './policy.js';
6
+ /**
7
+ * The device-side copy: artifacts, the tag versions learned from syncs, and the cursor they are
8
+ * current to. An artifact is valid while no dependency tag has a version above the cursor the
9
+ * artifact was built at; every sync and piggybacked diff only ever raises tag versions, so
10
+ * a stale copy is never revived.
11
+ */
12
+ export class Replica {
13
+ #storage;
14
+ #version;
15
+ #now;
16
+ #memory = new Map();
17
+ // ponytail: tag versions are never pruned (one entry per distinct changed tag)
18
+ #tags = new Map();
19
+ #cursor = null;
20
+ #syncedAt = 0;
21
+ #site;
22
+ #policies = new Map();
23
+ /** records and projections; untouched until a page that references them is stored or shown */
24
+ graph;
25
+ constructor(storage, version, now = Date.now) {
26
+ this.#storage = storage;
27
+ this.#version = version;
28
+ this.#now = now;
29
+ this.graph = new Graph({
30
+ storage,
31
+ tagVersion: (tag) => this.#tags.get(tag) ?? 0,
32
+ artifacts: () => this.#all()
33
+ });
34
+ }
35
+ /** reads the persisted meta; a different runtime version wipes what the old one stored */
36
+ async load() {
37
+ const meta = await this.#storage.getMeta();
38
+ if (meta && meta.version === this.#version) {
39
+ this.#cursor = meta.cursor;
40
+ this.#syncedAt = meta.syncedAt;
41
+ this.#tags = new Map(meta.tags);
42
+ this.#site = meta.policy?.site;
43
+ this.#policies = new Map(meta.policy?.paths);
44
+ return;
45
+ }
46
+ await this.#storage.clearArtifacts();
47
+ await this.graph.clear();
48
+ await this.#save();
49
+ }
50
+ /** the vector cursor the replica is current to, or null before the first artifact */
51
+ get cursor() {
52
+ return this.#cursor;
53
+ }
54
+ /** when the replica last completed a sync or a piggybacked diff */
55
+ get syncedAt() {
56
+ return this.#syncedAt;
57
+ }
58
+ /** the security headers of the latest network navigation, or undefined before one was seen */
59
+ get sitePolicy() {
60
+ return this.#site;
61
+ }
62
+ /** the security headers `path` itself was last answered with, or undefined */
63
+ policyOf(path) {
64
+ return this.#policies.get(path);
65
+ }
66
+ /** keeps the headers of a network view: for `path`, or for the whole site when `path` is null */
67
+ async keepPolicy(path, headers) {
68
+ const same = (a) => JSON.stringify(a) === JSON.stringify(headers);
69
+ if (path === null) {
70
+ if (same(this.#site))
71
+ return;
72
+ this.#site = headers;
73
+ }
74
+ else {
75
+ if (same(this.#policies.get(path)))
76
+ return;
77
+ this.#policies.delete(path);
78
+ this.#policies.set(path, headers);
79
+ if (this.#policies.size > MAX_POLICY_PATHS) {
80
+ this.#policies.delete(this.#policies.keys().next().value);
81
+ }
82
+ }
83
+ await this.#save();
84
+ }
85
+ /** the stored artifact for `id`, memory-only routes included */
86
+ async get(id) {
87
+ return this.#memory.get(id) ?? (await this.#storage.getArtifact(id));
88
+ }
89
+ /** every stored artifact id */
90
+ async ids() {
91
+ return (await this.#all()).map((s) => s.artifact.id);
92
+ }
93
+ /** whether no dependency of `artifact` has changed since it was built */
94
+ isCurrent(artifact) {
95
+ return isCurrent(artifact, (tag) => this.#tags.get(tag) ?? 0);
96
+ }
97
+ /** when `stored` was last known good */
98
+ validatedAt(stored) {
99
+ return Math.max(validatedAt(stored.fetchedAt, this.#syncedAt), stored.validatedAt ?? 0);
100
+ }
101
+ /** records that a sync just confirmed `id`, if it is still stored */
102
+ async validate(id) {
103
+ const stored = await this.get(id);
104
+ if (!stored || !this.isCurrent(stored.artifact))
105
+ return;
106
+ const next = { ...stored, validatedAt: this.#now() };
107
+ if (this.#memory.has(id))
108
+ this.#memory.set(id, next);
109
+ else
110
+ await this.#storage.putArtifact(next);
111
+ }
112
+ /**
113
+ * What to ask `/.spool/sync?need=` about before showing `artifact`: each tag it depends on at
114
+ * the version it was built, plus its own drop tag. Null for an artifact with no references,
115
+ * which a full sync validates unless `always` is set, and for one that depends on more than the
116
+ * server accepts.
117
+ */
118
+ needFor(artifact, always = false) {
119
+ if (!always && !usesGraph(artifact))
120
+ return null;
121
+ const tags = [...new Set([...artifact.deps, artifactTag(artifact.id)])];
122
+ if (tags.length > MAX_NEED)
123
+ return null;
124
+ return Object.fromEntries(tags.map((tag) => [tag, artifact.vector]));
125
+ }
126
+ /** the records and projections held, for an artifact request's `have`; loads the graph */
127
+ async held() {
128
+ await this.#wake();
129
+ return this.graph.held(MAX_HAVE);
130
+ }
131
+ /** the artifact with its references resolved from the graph; loads the graph when it has any */
132
+ async materialize(artifact) {
133
+ if (usesGraph(artifact))
134
+ await this.#wake();
135
+ return this.graph.materialize(artifact);
136
+ }
137
+ async #wake() {
138
+ const gone = await this.graph.ensure();
139
+ if (gone.length > 0)
140
+ await this.drop(gone);
141
+ }
142
+ /**
143
+ * Stores an artifact unless a change it missed is already known. The first one sets the cursor
144
+ * to its vector, since nothing earlier can affect it. Returns whether it was kept.
145
+ */
146
+ async put(artifact, persist, catalogue = false) {
147
+ if (!this.isCurrent(artifact))
148
+ return false;
149
+ if (usesGraph(artifact)) {
150
+ await this.#wake();
151
+ await this.graph.put(artifact, persist);
152
+ }
153
+ const { records: _records, projections: _projections, ...rest } = artifact;
154
+ const stored = {
155
+ artifact: rest,
156
+ fetchedAt: this.#now(),
157
+ ...(catalogue ? { catalogue: true } : {})
158
+ };
159
+ if (persist) {
160
+ this.#memory.delete(artifact.id);
161
+ await this.#storage.putArtifact(stored);
162
+ }
163
+ else {
164
+ await this.#storage.deleteArtifacts([artifact.id]);
165
+ this.#memory.set(artifact.id, stored);
166
+ }
167
+ if (this.#cursor === null) {
168
+ this.#cursor = artifact.vector;
169
+ await this.#save();
170
+ }
171
+ return true;
172
+ }
173
+ /** marks the catalogue entry `id` as opened, so it is an ordinary artifact from now on */
174
+ async open(id) {
175
+ const stored = await this.get(id);
176
+ if (!stored?.catalogue)
177
+ return;
178
+ const { catalogue: _catalogue, ...opened } = stored;
179
+ if (this.#memory.has(id))
180
+ this.#memory.set(id, opened);
181
+ else
182
+ await this.#storage.putArtifact(opened);
183
+ }
184
+ /**
185
+ * `need` with the dependency tags and drop tag of every unopened catalogue entry added, each at
186
+ * the vector its entry was built at. A revoked entry that no page opens is named by no page's
187
+ * sync, so a required sync of a principal page carries this. Null when the union is over
188
+ * `MAX_NEED`, which the caller answers with a full sync.
189
+ */
190
+ async sweep(need) {
191
+ const out = { ...need };
192
+ for (const { artifact, catalogue } of await this.#all()) {
193
+ if (!catalogue)
194
+ continue;
195
+ for (const tag of [...artifact.deps, artifactTag(artifact.id)]) {
196
+ out[tag] = Math.min(out[tag] ?? Infinity, artifact.vector);
197
+ }
198
+ }
199
+ return Object.keys(out).length > MAX_NEED ? null : out;
200
+ }
201
+ /** removes artifacts by id */
202
+ async drop(ids) {
203
+ for (const id of ids)
204
+ this.#memory.delete(id);
205
+ await this.#storage.deleteArtifacts(ids);
206
+ if (this.graph.loaded)
207
+ this.graph.forgetArtifacts(ids);
208
+ }
209
+ /** empties the replica; `cursor` is where it restarts */
210
+ async wipe(cursor = null) {
211
+ this.#memory.clear();
212
+ await this.#storage.clearArtifacts();
213
+ await this.graph.clear();
214
+ this.#tags = new Map();
215
+ this.#site = undefined;
216
+ this.#policies = new Map();
217
+ this.#cursor = cursor;
218
+ await this.#save();
219
+ }
220
+ /** applies a `/.spool/sync` answer and returns the ids of the artifacts it invalidated */
221
+ async applySync(response) {
222
+ if (response.reset) {
223
+ const held = await this.ids();
224
+ await this.wipe(response.cursor);
225
+ this.#syncedAt = this.#now();
226
+ await this.#save();
227
+ return held;
228
+ }
229
+ const gone = await this.#merge(response.changed);
230
+ await this.drop(response.dropped);
231
+ if (!response.partial) {
232
+ this.#cursor = Math.max(this.#cursor ?? 0, response.cursor);
233
+ this.#syncedAt = this.#now();
234
+ }
235
+ await this.#save();
236
+ return [...new Set([...gone, ...response.dropped])];
237
+ }
238
+ /**
239
+ * Applies the spool headers of a network response. Invalidations always apply. The cursor and
240
+ * the sync clock move only when the response answers the cursor this worker sent and carries
241
+ * no `Age`, so a copy replayed from a shared cache cannot extend freshness.
242
+ */
243
+ async applyEnvelope(envelope, sent, aged) {
244
+ let gone = [];
245
+ if (envelope.clear?.includes(CLEAR_ALL)) {
246
+ gone = await this.ids();
247
+ await this.wipe(envelope.vector ?? this.#cursor);
248
+ }
249
+ else if (envelope.invalidate) {
250
+ gone = await this.#merge(envelope.invalidate);
251
+ }
252
+ const answered = sent !== null && envelope.seen === sent && envelope.vector !== undefined;
253
+ if (answered && !aged) {
254
+ this.#cursor = Math.max(this.#cursor ?? 0, envelope.vector);
255
+ this.#syncedAt = this.#now();
256
+ }
257
+ await this.#save();
258
+ return gone;
259
+ }
260
+ async #all() {
261
+ return [...this.#memory.values(), ...(await this.#storage.allArtifacts())];
262
+ }
263
+ async #merge(changed) {
264
+ const dropAt = new Map();
265
+ for (const [tag, version] of Object.entries(changed)) {
266
+ if (tag.startsWith(ARTIFACT_TAG_PREFIX)) {
267
+ dropAt.set(tag.slice(ARTIFACT_TAG_PREFIX.length), version);
268
+ }
269
+ else if (version > (this.#tags.get(tag) ?? 0))
270
+ this.#tags.set(tag, version);
271
+ }
272
+ const reached = this.graph.loaded
273
+ ? (await this.graph.invalidate(Object.fromEntries(this.#changedTags(changed))))
274
+ .artifacts
275
+ : [];
276
+ const gone = (await this.#all())
277
+ .filter(({ artifact }) => {
278
+ const at = dropAt.get(artifact.id);
279
+ return ((at !== undefined && artifact.vector < at) ||
280
+ !this.isCurrent(artifact) ||
281
+ reached.includes(artifact.id));
282
+ })
283
+ .map(({ artifact }) => artifact.id);
284
+ await this.drop(gone);
285
+ return gone;
286
+ }
287
+ #changedTags(changed) {
288
+ return Object.entries(changed).filter(([tag]) => !tag.startsWith(ARTIFACT_TAG_PREFIX));
289
+ }
290
+ async #save() {
291
+ await this.#storage.setMeta({
292
+ version: this.#version,
293
+ cursor: this.#cursor,
294
+ tags: [...this.#tags],
295
+ syncedAt: this.#syncedAt,
296
+ policy: { ...(this.#site ? { site: this.#site } : {}), paths: [...this.#policies] }
297
+ });
298
+ }
299
+ }
@@ -0,0 +1,42 @@
1
+ import { type CollectorConfig } from '../protocol/collector.js';
2
+ import type { SwConfig } from '../protocol/config.js';
3
+ import { type Params } from '../protocol/pattern.js';
4
+ import { type SerializedRoute } from '../protocol/route.js';
5
+ /** how the worker treats a request; a `static` hit keys its file by pathname plus query string */
6
+ export type Classified = {
7
+ kind: 'ignore';
8
+ } | {
9
+ kind: 'beacon';
10
+ } | {
11
+ kind: 'collector';
12
+ collector: CollectorConfig;
13
+ } | {
14
+ kind: 'thirdparty';
15
+ } | {
16
+ kind: 'logout';
17
+ } | {
18
+ kind: 'navigation';
19
+ route: SerializedRoute;
20
+ params: Params;
21
+ path: string;
22
+ } | {
23
+ kind: 'static';
24
+ route: SerializedRoute;
25
+ path: string;
26
+ } | {
27
+ kind: 'data';
28
+ route: SerializedRoute;
29
+ path: string;
30
+ } | {
31
+ kind: 'asset';
32
+ } | {
33
+ kind: 'pass';
34
+ };
35
+ /**
36
+ * Sorts a request without touching it. A request to another origin is a held collector hit, a
37
+ * file of an allowed third-party origin, or ignored so the browser handles it natively. A
38
+ * same-origin one is a logout request, a queued beacon, a navigation on a declared route, a GET for
39
+ * a JSON route, a GET for a subresource (cache-first when immutable), a GET of a file a static
40
+ * route keeps, or a pass-through that the worker still observes for spool headers.
41
+ */
42
+ export declare function classify(config: SwConfig, request: Request, origin: string): Classified;
@@ -0,0 +1,48 @@
1
+ import { matchCollector } from '../protocol/collector.js';
2
+ import { matchPattern } from '../protocol/pattern.js';
3
+ import { matchRoute } from '../protocol/route.js';
4
+ /** whether `url` falls under an origin the worker may cache files from */
5
+ function thirdPartyOrigin(config, url) {
6
+ return config.thirdParty?.allow.includes(url.origin) === true;
7
+ }
8
+ /**
9
+ * Sorts a request without touching it. A request to another origin is a held collector hit, a
10
+ * file of an allowed third-party origin, or ignored so the browser handles it natively. A
11
+ * same-origin one is a logout request, a queued beacon, a navigation on a declared route, a GET for
12
+ * a JSON route, a GET for a subresource (cache-first when immutable), a GET of a file a static
13
+ * route keeps, or a pass-through that the worker still observes for spool headers.
14
+ */
15
+ export function classify(config, request, origin) {
16
+ const url = new URL(request.url);
17
+ if (url.origin !== origin) {
18
+ const collector = matchCollector(config.collectors, request.url);
19
+ if (collector && (request.method === 'POST' || request.method === 'GET')) {
20
+ return { kind: 'collector', collector };
21
+ }
22
+ if (request.method === 'GET' && thirdPartyOrigin(config, url))
23
+ return { kind: 'thirdparty' };
24
+ return { kind: 'ignore' };
25
+ }
26
+ if (config.logout?.some((pattern) => matchPattern(pattern, url.pathname))) {
27
+ return { kind: 'logout' };
28
+ }
29
+ if (request.method === 'POST' && config.beacons.includes(url.pathname))
30
+ return { kind: 'beacon' };
31
+ if (request.method !== 'GET')
32
+ return { kind: 'pass' };
33
+ const hit = matchRoute(config.routes, url.pathname);
34
+ // an artifact is keyed by path alone, so a query string can never be answered from one
35
+ const queried = url.search !== '';
36
+ if (request.mode !== 'navigate') {
37
+ if (hit?.route.strategy === 'static' && !request.headers.has('range')) {
38
+ return { kind: 'static', route: hit.route, path: url.pathname + url.search };
39
+ }
40
+ if (hit?.route.strategy === 'data' && !request.headers.has('range') && !queried) {
41
+ return { kind: 'data', route: hit.route, path: url.pathname };
42
+ }
43
+ return { kind: 'asset' };
44
+ }
45
+ if (!hit || hit.route.strategy === 'data' || queried)
46
+ return { kind: 'pass' };
47
+ return { kind: 'navigation', route: hit.route, params: hit.params, path: url.pathname };
48
+ }
@@ -0,0 +1,23 @@
1
+ import type { SwConfig } from '../protocol/config.js';
2
+ /** one rule of `InstallEvent.addRoutes`, the parts spool writes */
3
+ export type RouterRule = {
4
+ condition: Record<string, unknown>;
5
+ source: 'fetch-event' | 'network';
6
+ };
7
+ /** the `InstallEvent` of a browser with Static Routing; `addRoutes` is absent elsewhere */
8
+ export type RoutableInstall = {
9
+ addRoutes?(rules: RouterRule[]): Promise<void>;
10
+ };
11
+ /**
12
+ * The rules that send only what the worker handles to its `fetch` event and every other
13
+ * same-origin request to the network: navigations, the beacon, logout and routed paths first, and
14
+ * cross-origin requests too when collectors or a third-party cache are configured. Rules apply in
15
+ * order, so the last one catches the rest of the origin. Spool path patterns (`/n/:id`) are valid
16
+ * URLPattern syntax, so they pass through as written.
17
+ */
18
+ export declare function staticRoutingRules(config: SwConfig, origin: string): RouterRule[];
19
+ /**
20
+ * Registers the rules when the browser has the API. Returns whether they took effect; a browser
21
+ * without `addRoutes`, or one that refuses a rule, leaves the worker to act as `passthrough`.
22
+ */
23
+ export declare function installRoutes(event: RoutableInstall, config: SwConfig, origin: string): Promise<boolean>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The rules that send only what the worker handles to its `fetch` event and every other
3
+ * same-origin request to the network: navigations, the beacon, logout and routed paths first, and
4
+ * cross-origin requests too when collectors or a third-party cache are configured. Rules apply in
5
+ * order, so the last one catches the rest of the origin. Spool path patterns (`/n/:id`) are valid
6
+ * URLPattern syntax, so they pass through as written.
7
+ */
8
+ export function staticRoutingRules(config, origin) {
9
+ const at = (path) => `${origin}${path}`;
10
+ const rules = [{ condition: { requestMode: 'navigate' }, source: 'fetch-event' }];
11
+ for (const path of config.beacons) {
12
+ rules.push({
13
+ condition: { urlPattern: at(path), requestMethod: 'POST' },
14
+ source: 'fetch-event'
15
+ });
16
+ }
17
+ for (const path of config.logout ?? []) {
18
+ rules.push({ condition: { urlPattern: at(path) }, source: 'fetch-event' });
19
+ }
20
+ for (const route of config.routes) {
21
+ if (route.strategy === 'static' || route.strategy === 'data') {
22
+ rules.push({ condition: { urlPattern: at(route.pattern) }, source: 'fetch-event' });
23
+ }
24
+ }
25
+ if ((config.collectors?.length ?? 0) > 0 || config.thirdParty) {
26
+ rules.push({
27
+ condition: { not: { urlPattern: at('/*') } },
28
+ source: 'fetch-event'
29
+ });
30
+ }
31
+ rules.push({ condition: { urlPattern: at('/*') }, source: 'network' });
32
+ return rules;
33
+ }
34
+ /**
35
+ * Registers the rules when the browser has the API. Returns whether they took effect; a browser
36
+ * without `addRoutes`, or one that refuses a rule, leaves the worker to act as `passthrough`.
37
+ */
38
+ export async function installRoutes(event, config, origin) {
39
+ if (typeof event.addRoutes !== 'function')
40
+ return false;
41
+ try {
42
+ await event.addRoutes(staticRoutingRules(config, origin));
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
@@ -0,0 +1,112 @@
1
+ import { type AssetMode, type SwConfig } from '../protocol/config.js';
2
+ import type { PartitionHost } from './partition.js';
3
+ import { Ledger, type LedgerEntry, type LedgerTotals } from './provision.js';
4
+ import { type Renderers } from './render.js';
5
+ import { Replica } from './replica.js';
6
+ import { type RoutableInstall } from './routing.js';
7
+ import type { ReplicaStorage } from './storage.js';
8
+ /** the slice of a `Cache` the runtime uses */
9
+ export type CacheLike = {
10
+ match(request: Request): Promise<Response | undefined>;
11
+ put(request: Request, response: Response): Promise<void>;
12
+ keys(): Promise<readonly Request[]>;
13
+ delete(request: Request): Promise<boolean>;
14
+ };
15
+ /** the slice of `CacheStorage` the runtime uses */
16
+ export type CachesLike = {
17
+ open(name: string): Promise<CacheLike>;
18
+ keys(): Promise<string[]>;
19
+ delete(name: string): Promise<boolean>;
20
+ };
21
+ /** everything the runtime touches outside itself, injected so a test can drive it */
22
+ export type RuntimeDeps = {
23
+ config: SwConfig;
24
+ storage: ReplicaStorage;
25
+ fetch(input: Request | string, init?: RequestInit): Promise<Response>;
26
+ caches: CachesLike;
27
+ /** the worker's own origin */
28
+ origin: string;
29
+ now?: () => number;
30
+ renderers?: Renderers;
31
+ /** a number in [0, 1) for the shadow sample; default `Math.random` */
32
+ random?: () => number;
33
+ /** the browser's user agent, which names the engine in view events; default `navigator.userAgent` */
34
+ userAgent?: string;
35
+ /**
36
+ * where principal routes keep their sealed stores; without it the worker sends every principal
37
+ * route to the network and keeps nothing for them
38
+ */
39
+ partitions?: PartitionHost;
40
+ /** tells every page of the origin something, such as that a wipe happened */
41
+ broadcast?(message: unknown): void;
42
+ };
43
+ /** the worker's answer to a page's `spool:hello` */
44
+ export type Hello = {
45
+ type: 'spool:hello';
46
+ protocol: number;
47
+ version: string;
48
+ compatible: boolean;
49
+ };
50
+ /** the worker's answer to `spool:status` */
51
+ export type Status = {
52
+ type: 'spool:status';
53
+ cursor: number | null;
54
+ syncedAt: number;
55
+ artifacts: string[];
56
+ /** beacons held for the next flush */
57
+ beacons: number;
58
+ };
59
+ /** the worker's answer to `spool:view`: the id of the latest view of a path, for the page's report */
60
+ export type ViewId = {
61
+ type: 'spool:view';
62
+ id: string | null;
63
+ };
64
+ /** the worker's answer to `spool:graph`: what it holds in records and projections */
65
+ export type GraphStatus = {
66
+ type: 'spool:graph';
67
+ records: string[];
68
+ projections: string[];
69
+ };
70
+ /** the worker's answer to `spool:ledger`: bytes and requests spent provisioning, against views served */
71
+ export type LedgerStatus = {
72
+ type: 'spool:ledger';
73
+ entries: LedgerEntry[];
74
+ totals: LedgerTotals;
75
+ };
76
+ /** the worker's answer to `spool:partition`: the principal store in use and what it holds */
77
+ export type PartitionStatus = {
78
+ type: 'spool:partition';
79
+ partition: string | null;
80
+ artifacts: string[];
81
+ records: string[];
82
+ projections: string[];
83
+ };
84
+ /** the worker's answer to `spool:assets`: the mode asked for and whether Static Routing took effect */
85
+ export type AssetsStatus = {
86
+ type: 'spool:assets';
87
+ mode: AssetMode;
88
+ routed: boolean;
89
+ };
90
+ /** the worker's answer to `spool:held`: events dropped past a vendor's cap, and the third-party files held */
91
+ export type HeldStatus = {
92
+ type: 'spool:held';
93
+ dropped: Record<string, number>;
94
+ third: string[];
95
+ };
96
+ /** every reply the worker gives a page */
97
+ export type Reply = Hello | Status | ViewId | GraphStatus | LedgerStatus | PartitionStatus | AssetsStatus | HeldStatus;
98
+ /** the object `serve` wires to service worker events */
99
+ export type Runtime = {
100
+ /** a response promise for a request the worker handles, `undefined` for one it leaves alone */
101
+ handle(request: Request, wait: (promise: Promise<unknown>) => void): Promise<Response> | undefined;
102
+ /** run on install: asks for Static Routing when the config does and the browser has it */
103
+ install(event: RoutableInstall): Promise<void>;
104
+ /** run on activation: loads the replica and drops asset caches from older versions */
105
+ activate(): Promise<void>;
106
+ /** answers a page message, or `undefined` for one that is not spool's */
107
+ message(data: unknown): Promise<Reply | undefined>;
108
+ readonly replica: Replica;
109
+ readonly ledger: Ledger;
110
+ };
111
+ /** builds the request pipeline: local render, sync, provisioning, asset cache and beacon queue */
112
+ export declare function createRuntime(deps: RuntimeDeps): Runtime;