@sigil-dev/grimoire 0.9.20 → 0.9.22

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -114
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -745
  28. package/src/rendering/preload.ts +101 -95
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -194
  35. package/src/server/asset-cache.ts +57 -55
  36. package/src/server/build.ts +262 -249
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -0
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1022
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -0
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -113
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -69
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,194 +1,206 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import { log } from "../logger/instance.ts";
3
-
4
- const logger = log.scope("server");
5
-
6
- /**
7
- * Tasks collected for the in-flight request.
8
- *
9
- * AsyncLocalStorage is what makes afterResponse() work without threading a
10
- * context argument through every function that might want to defer work.
11
- * A plain module-level array would interleave badly under concurrency: two
12
- * requests running at once could collect each other's tasks, and a task
13
- * would run at the end of the wrong response.
14
- */
15
- interface RequestScope {
16
- tasks: Array<() => unknown>;
17
- /** Resolves when fire() has run every task, so drain can wait for this. */
18
- flushed: Promise<void>;
19
- markFlushed: () => void;
20
- }
21
- const scope = new AsyncLocalStorage<RequestScope>();
22
-
23
- let inflight = new Set<Promise<unknown>>();
24
- /**
25
- * Flush promises for requests whose body has not finished streaming.
26
- *
27
- * Tracked separately from `inflight` because a task is not running yet while
28
- * its response is still streaming — a shutdown that only waits on running
29
- * work would return while queued work was still pending.
30
- */
31
- let unflushed = new Set<Promise<void>>();
32
- let shuttingDown = false;
33
-
34
- /**
35
- * Run work after the response for the current request has been flushed.
36
- *
37
- * Does not block the response, and does not survive a restart — a task that
38
- * has not finished is lost if the process exits. That makes this for work
39
- * that is cheap and re-derivable: analytics, cache warming, a last-seen
40
- * timestamp. Anything a user was promised belongs in a durable queue, and
41
- * this is the call site to change when a job starts to matter.
42
- *
43
- * Errors are logged, never thrown. The response is already sent by the time
44
- * a task runs, so a failure cannot be reported to anyone.
45
- *
46
- * Outside a request (at startup, in `init`) the task runs on the next
47
- * microtask instead. That keeps the call valid anywhere without pretending
48
- * there was a response to wait for.
49
- */
50
- export function afterResponse(fn: () => unknown): Promise<unknown> {
51
- if (shuttingDown) {
52
- return Promise.reject(
53
- new Error("afterResponse() called during shutdown"),
54
- );
55
- }
56
-
57
- // Wrap so a synchronous throw inside fn becomes a rejection instead of
58
- // propagating out of the caller's await.
59
- const run = async () => {
60
- try {
61
- await fn();
62
- } catch (e) {
63
- logger.error("afterResponse task failed:", e);
64
- }
65
- };
66
-
67
- const current = scope.getStore();
68
- if (!current) {
69
- return track(run());
70
- }
71
-
72
- current.tasks.push(() => track(run()));
73
- return Promise.resolve();
74
- }
75
-
76
- function deferred(): { flushed: Promise<void>; markFlushed: () => void } {
77
- let mark!: () => void;
78
- const flushed = new Promise<void>((resolve) => {
79
- mark = resolve;
80
- });
81
- return { flushed, markFlushed: mark };
82
- }
83
-
84
- function track(p: Promise<unknown>): Promise<unknown> {
85
- inflight.add(p);
86
- p.finally(() => inflight.delete(p));
87
- return p;
88
- }
89
-
90
- /**
91
- * Run a handler inside a request scope, then fire the collected tasks once
92
- * the response body has finished streaming.
93
- *
94
- * Wrapping the body is what makes "after the response" true for streaming
95
- * responses: scheduling on the handler's return would run the task while
96
- * the client is still receiving. Firing on the stream's end means a slow
97
- * download does not start the work early.
98
- */
99
- export async function withAfterResponse(
100
- req: Request,
101
- handler: (req: Request) => Response | Promise<Response>,
102
- ): Promise<Response> {
103
- const requestScope: RequestScope = { tasks: [], ...deferred() };
104
- unflushed.add(requestScope.flushed);
105
- requestScope.flushed.finally(() => unflushed.delete(requestScope.flushed));
106
- const response = await scope.run(requestScope, () => handler(req));
107
-
108
- const fire = () => {
109
- requestScope.markFlushed();
110
- if (requestScope.tasks.length === 0) return;
111
- // Copy first: a task may register another task.
112
- const tasks = requestScope.tasks.splice(0);
113
- for (const t of tasks) t();
114
- };
115
-
116
- if (!(response instanceof Response) || response.body === null) {
117
- fire();
118
- return response as Response;
119
- }
120
-
121
- const { readable, writable } = new TransformStream();
122
- // Errors on the original body propagate, and the tasks still run: a
123
- // client disconnecting mid-stream must not silently skip the work.
124
- Promise.resolve(response.body)
125
- .then((body) => body?.pipeTo(writable))
126
- .catch(() => writable.abort())
127
- .finally(fire);
128
-
129
- return new Response(readable, {
130
- status: response.status,
131
- statusText: response.statusText,
132
- headers: response.headers,
133
- });
134
- }
135
-
136
- /**
137
- * Wait for in-flight afterResponse tasks so a graceful shutdown does not
138
- * abandon work already started. Subsequent registrations are rejected.
139
- */
140
- export async function drainAfterResponse(timeoutMs = 5000): Promise<void> {
141
- shuttingDown = true;
142
-
143
- const deadline = Date.now() + timeoutMs;
144
- const timedOut = Symbol("timeout");
145
-
146
- const waitFor = async <T>(work: Promise<T>): Promise<T | typeof timedOut> => {
147
- const left = deadline - Date.now();
148
- if (left <= 0) return timedOut;
149
- let timer: ReturnType<typeof setTimeout> | undefined;
150
- const result = await Promise.race([
151
- work,
152
- new Promise<typeof timedOut>((resolve) => {
153
- timer = setTimeout(() => resolve(timedOut), left);
154
- }),
155
- ]);
156
- if (timer) clearTimeout(timer);
157
- return result;
158
- };
159
-
160
- // Two waits, not one. A task registered during a request is not in
161
- // `inflight` until the response body has flushed and it actually
162
- // starts, so draining only that set would return while a response was
163
- // still streaming and its work was still queued.
164
- const flushed = await waitFor(Promise.allSettled([...unflushed]));
165
- if (flushed === timedOut) {
166
- logger.warn(
167
- `responses were still streaming after ${timeoutMs}ms; ` +
168
- `afterResponse tasks for them will be lost`,
169
- );
170
- return;
171
- }
172
-
173
- if (inflight.size === 0) {
174
- unflushed.clear();
175
- return;
176
- }
177
-
178
- logger.info(`waiting for ${inflight.size} afterResponse task(s)...`);
179
- const result = await waitFor(Promise.allSettled([...inflight]));
180
- if (result === timedOut) {
181
- logger.warn(
182
- `afterResponse tasks did not finish within ${timeoutMs}ms, abandoning them`,
183
- );
184
- }
185
- inflight.clear();
186
- unflushed.clear();
187
- }
188
-
189
- /** Test-only: reset module state between cases. */
190
- export function _resetAfterResponseForTest(): void {
191
- inflight = new Set();
192
- unflushed = new Set();
193
- shuttingDown = false;
194
- }
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { log } from "../logger/instance.ts";
3
+
4
+ const logger = log.scope("server");
5
+
6
+ /**
7
+ * Tasks collected for the in-flight request.
8
+ *
9
+ * AsyncLocalStorage is what makes afterResponse() work without threading a
10
+ * context argument through every function that might want to defer work.
11
+ * A plain module-level array would interleave badly under concurrency: two
12
+ * requests running at once could collect each other's tasks, and a task
13
+ * would run at the end of the wrong response.
14
+ */
15
+ interface RequestScope {
16
+ tasks: Array<() => unknown>;
17
+ /** Resolves when fire() has run every task, so drain can wait for this. */
18
+ flushed: Promise<void>;
19
+ markFlushed: () => void;
20
+ }
21
+ const scope = new AsyncLocalStorage<RequestScope>();
22
+
23
+ let inflight = new Set<Promise<unknown>>();
24
+ /**
25
+ * Flush promises for requests whose body has not finished streaming.
26
+ *
27
+ * Tracked separately from `inflight` because a task is not running yet while
28
+ * its response is still streaming — a shutdown that only waits on running
29
+ * work would return while queued work was still pending.
30
+ */
31
+ let unflushed = new Set<Promise<void>>();
32
+ let shuttingDown = false;
33
+
34
+ /**
35
+ * Run work after the response for the current request has been flushed.
36
+ *
37
+ * Does not block the response, and does not survive a restart — a task that
38
+ * has not finished is lost if the process exits. That makes this for work
39
+ * that is cheap and re-derivable: analytics, cache warming, a last-seen
40
+ * timestamp. Anything a user was promised belongs in a durable queue, and
41
+ * this is the call site to change when a job starts to matter.
42
+ *
43
+ * Errors are logged, never thrown. The response is already sent by the time
44
+ * a task runs, so a failure cannot be reported to anyone.
45
+ *
46
+ * Outside a request (at startup, in `init`) the task runs on the next
47
+ * microtask instead. That keeps the call valid anywhere without pretending
48
+ * there was a response to wait for.
49
+ */
50
+ export function afterResponse(fn: () => unknown): Promise<unknown> {
51
+ if (shuttingDown) {
52
+ return Promise.reject(new Error("afterResponse() called during shutdown"));
53
+ }
54
+
55
+ // Wrap so a synchronous throw inside fn becomes a rejection instead of
56
+ // propagating out of the caller's await.
57
+ const run = async () => {
58
+ try {
59
+ await fn();
60
+ } catch (e) {
61
+ logger.error("afterResponse task failed:", e);
62
+ }
63
+ };
64
+
65
+ const current = scope.getStore();
66
+ if (!current) {
67
+ return track(run());
68
+ }
69
+
70
+ current.tasks.push(() => track(run()));
71
+ return Promise.resolve();
72
+ }
73
+
74
+ function deferred(): { flushed: Promise<void>; markFlushed: () => void } {
75
+ let mark!: () => void;
76
+ const flushed = new Promise<void>((resolve) => {
77
+ mark = resolve;
78
+ });
79
+ return { flushed, markFlushed: mark };
80
+ }
81
+
82
+ function track(p: Promise<unknown>): Promise<unknown> {
83
+ inflight.add(p);
84
+ p.finally(() => inflight.delete(p));
85
+ return p;
86
+ }
87
+
88
+ /**
89
+ * Run a handler inside a request scope, then fire the collected tasks once
90
+ * the response body has finished streaming.
91
+ *
92
+ * Wrapping the body is what makes "after the response" true for streaming
93
+ * responses: scheduling on the handler's return would run the task while
94
+ * the client is still receiving. Firing on the stream's end means a slow
95
+ * download does not start the work early.
96
+ */
97
+ export async function withAfterResponse(
98
+ req: Request,
99
+ handler: (req: Request) => Response | Promise<Response>,
100
+ ): Promise<Response> {
101
+ const requestScope: RequestScope = { tasks: [], ...deferred() };
102
+ unflushed.add(requestScope.flushed);
103
+ requestScope.flushed.finally(() => unflushed.delete(requestScope.flushed));
104
+ const response = await scope.run(requestScope, () => handler(req));
105
+
106
+ const fire = () => {
107
+ requestScope.markFlushed();
108
+ if (requestScope.tasks.length === 0) return;
109
+ // Copy first: a task may register another task.
110
+ const tasks = requestScope.tasks.splice(0);
111
+ for (const t of tasks) t();
112
+ };
113
+
114
+ if (!(response instanceof Response)) {
115
+ fire();
116
+ return response as Response;
117
+ }
118
+ // A body Bun types itself (a string, a file, a blob) has no Content-Type
119
+ // in response.headers: Bun adds it when sending. Merely reading
120
+ // response.body turns it into a stream that Bun then sends untyped,
121
+ // which browsers treat as a download, so check the headers first and
122
+ // leave such a response alone. Its body is complete already: run the
123
+ // tasks on the next turn, once it has gone out.
124
+ if (!response.headers.has("content-type")) {
125
+ setTimeout(fire, 0);
126
+ return response;
127
+ }
128
+ if (response.body === null) {
129
+ fire();
130
+ return response;
131
+ }
132
+
133
+ const { readable, writable } = new TransformStream();
134
+ // Errors on the original body propagate, and the tasks still run: a
135
+ // client disconnecting mid-stream must not silently skip the work.
136
+ Promise.resolve(response.body)
137
+ .then((body) => body?.pipeTo(writable))
138
+ .catch(() => writable.abort())
139
+ .finally(fire);
140
+
141
+ return new Response(readable, {
142
+ status: response.status,
143
+ statusText: response.statusText,
144
+ headers: response.headers,
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Wait for in-flight afterResponse tasks so a graceful shutdown does not
150
+ * abandon work already started. Subsequent registrations are rejected.
151
+ */
152
+ export async function drainAfterResponse(timeoutMs = 5000): Promise<void> {
153
+ shuttingDown = true;
154
+
155
+ const deadline = Date.now() + timeoutMs;
156
+ const timedOut = Symbol("timeout");
157
+
158
+ const waitFor = async <T>(work: Promise<T>): Promise<T | typeof timedOut> => {
159
+ const left = deadline - Date.now();
160
+ if (left <= 0) return timedOut;
161
+ let timer: ReturnType<typeof setTimeout> | undefined;
162
+ const result = await Promise.race([
163
+ work,
164
+ new Promise<typeof timedOut>((resolve) => {
165
+ timer = setTimeout(() => resolve(timedOut), left);
166
+ }),
167
+ ]);
168
+ if (timer) clearTimeout(timer);
169
+ return result;
170
+ };
171
+
172
+ // Two waits, not one. A task registered during a request is not in
173
+ // `inflight` until the response body has flushed and it actually
174
+ // starts, so draining only that set would return while a response was
175
+ // still streaming and its work was still queued.
176
+ const flushed = await waitFor(Promise.allSettled([...unflushed]));
177
+ if (flushed === timedOut) {
178
+ logger.warn(
179
+ `responses were still streaming after ${timeoutMs}ms; ` +
180
+ `afterResponse tasks for them will be lost`,
181
+ );
182
+ return;
183
+ }
184
+
185
+ if (inflight.size === 0) {
186
+ unflushed.clear();
187
+ return;
188
+ }
189
+
190
+ logger.info(`waiting for ${inflight.size} afterResponse task(s)...`);
191
+ const result = await waitFor(Promise.allSettled([...inflight]));
192
+ if (result === timedOut) {
193
+ logger.warn(
194
+ `afterResponse tasks did not finish within ${timeoutMs}ms, abandoning them`,
195
+ );
196
+ }
197
+ inflight.clear();
198
+ unflushed.clear();
199
+ }
200
+
201
+ /** Test-only: reset module state between cases. */
202
+ export function _resetAfterResponseForTest(): void {
203
+ inflight = new Set();
204
+ unflushed = new Set();
205
+ shuttingDown = false;
206
+ }
@@ -1,55 +1,57 @@
1
- /**
2
- * The cache policy for files served out of public/.
3
- *
4
- * Extracted from the server so the decision can be tested without booting
5
- * one, and so there is exactly one copy of it. A policy test that keeps its
6
- * own duplicate of the logic passes forever regardless of what the server
7
- * does, which is worse than having no test.
8
- */
9
-
10
- /**
11
- * A URL that changes whenever its content changes: a build-stamped hash, or
12
- * a version query the app bumps per deploy.
13
- *
14
- * `?v=` deliberately counts. A file that a caller knows to re-request under
15
- * a new query is content-addressed by that query, and that is the same
16
- * guarantee a hash gives — the URL is the key. Requiring a literal hash in
17
- * the path would send every project that uses the query form back to
18
- * revalidation for no reason.
19
- */
20
- export function isContentAddressed(pathname: string, search: string): boolean {
21
- // /style.a1b2c3d4.css — a hash inserted before the extension.
22
- if (/\.[0-9a-f]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
23
- // /__grimoire__/chunk-jp4kgm87.js — the name the bundler gives a shared
24
- // chunk: "chunk-" and a hash of the contents. Anchored on the prefix, since
25
- // a bare "8+ letters before the extension" would also match hero-background.png.
26
- if (/(^|\/)chunk-[a-z0-9]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
27
- // A non-empty version query, e.g. /style.css?v=3. Deliberately does not
28
- // treat `?` with an empty value as addressed: /style.css? is the same
29
- // URL and would cache forever without ever changing.
30
- return /[?&]v=[^&#]+/.test(search);
31
- }
32
-
33
- /** The `Cache-Control` for a public asset, by its URL. */
34
- export function cacheControlFor(
35
- pathname: string,
36
- search: string,
37
- ): "no-cache" | "immutable" | "revalidate" {
38
- // The document is what references the assets. Caching it hard means
39
- // serving stale references to assets that are long gone.
40
- if (pathname === "/" || pathname.endsWith(".html")) return "no-cache";
41
- if (isContentAddressed(pathname, search)) return "immutable";
42
- // Cached, but revalidated every time. Costs a conditional request and
43
- // guarantees a deploy is visible on the next load — the right trade for a
44
- // file whose URL is not content-addressed.
45
- return "revalidate";
46
- }
47
-
48
- export const CACHE_CONTROL: Record<
49
- ReturnType<typeof cacheControlFor>,
50
- string
51
- > = {
52
- "no-cache": "no-cache",
53
- immutable: "public, max-age=31536000, immutable",
54
- revalidate: "public, max-age=0, must-revalidate",
55
- };
1
+ /**
2
+ * The cache policy for files served out of public/.
3
+ *
4
+ * Extracted from the server so the decision can be tested without booting
5
+ * one, and so there is exactly one copy of it. A policy test that keeps its
6
+ * own duplicate of the logic passes forever regardless of what the server
7
+ * does, which is worse than having no test.
8
+ */
9
+
10
+ /**
11
+ * A URL that changes whenever its content changes: a build-stamped hash, or
12
+ * a version query the app bumps per deploy.
13
+ *
14
+ * `?v=` deliberately counts. A file that a caller knows to re-request under
15
+ * a new query is content-addressed by that query, and that is the same
16
+ * guarantee a hash gives — the URL is the key. Requiring a literal hash in
17
+ * the path would send every project that uses the query form back to
18
+ * revalidation for no reason.
19
+ */
20
+ export function isContentAddressed(pathname: string, search: string): boolean {
21
+ // /style.a1b2c3d4.css — a hash inserted before the extension.
22
+ if (/\.[0-9a-f]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
23
+ // /__grimoire__/chunk-jp4kgm87.js — the name the bundler gives a shared
24
+ // chunk: "chunk-" and a hash of the contents. Anchored on the prefix, since
25
+ // a bare "8+ letters before the extension" would also match hero-background.png.
26
+ if (/(^|\/)chunk-[a-z0-9]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
27
+ // /__grimoire__/hydrate-a1b2c3d4.js — an entry named by its contents
28
+ if (/^\/__grimoire__\/[a-z]+-[a-z0-9]{8,}\.js$/i.test(pathname)) return true;
29
+ // A non-empty version query, e.g. /style.css?v=3. Deliberately does not
30
+ // treat `?` with an empty value as addressed: /style.css? is the same
31
+ // URL and would cache forever without ever changing.
32
+ return /[?&]v=[^&#]+/.test(search);
33
+ }
34
+
35
+ /** The `Cache-Control` for a public asset, by its URL. */
36
+ export function cacheControlFor(
37
+ pathname: string,
38
+ search: string,
39
+ ): "no-cache" | "immutable" | "revalidate" {
40
+ // The document is what references the assets. Caching it hard means
41
+ // serving stale references to assets that are long gone.
42
+ if (pathname === "/" || pathname.endsWith(".html")) return "no-cache";
43
+ if (isContentAddressed(pathname, search)) return "immutable";
44
+ // Cached, but revalidated every time. Costs a conditional request and
45
+ // guarantees a deploy is visible on the next load — the right trade for a
46
+ // file whose URL is not content-addressed.
47
+ return "revalidate";
48
+ }
49
+
50
+ export const CACHE_CONTROL: Record<
51
+ ReturnType<typeof cacheControlFor>,
52
+ string
53
+ > = {
54
+ "no-cache": "no-cache",
55
+ immutable: "public, max-age=31536000, immutable",
56
+ revalidate: "public, max-age=0, must-revalidate",
57
+ };