@sigil-dev/grimoire 0.9.20 → 0.9.21

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.
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "module": "index.ts",
12
12
  "type": "module",
13
13
  "private": false,
14
- "version": "0.9.20",
14
+ "version": "0.9.21",
15
15
  "exports": {
16
16
  ".": "./index.ts",
17
17
  "./server": "./server.ts",
@@ -30,8 +30,8 @@
30
30
  "test": "bun test"
31
31
  },
32
32
  "dependencies": {
33
- "@sigil-dev/compiler": "0.9.20",
34
- "@sigil-dev/runtime": "0.9.20",
33
+ "@sigil-dev/compiler": "0.9.21",
34
+ "@sigil-dev/runtime": "0.9.21",
35
35
  "vite": "^8.0.16"
36
36
  },
37
37
  "peerDependencies": {
package/src/headers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { withHeaders } from "./server/with-headers";
1
2
  import type { GrimoirePlugin } from "./types";
2
3
 
3
4
  export interface SecurityHeadersConfig {
@@ -98,17 +99,7 @@ export function securityHeaders(
98
99
  const url = new URL(req.url);
99
100
  const headers = resolveHeaders(config, url.pathname);
100
101
 
101
- // Clone response with security headers
102
- const newHeaders = new Headers(res.headers);
103
- for (const [key, value] of Object.entries(headers)) {
104
- newHeaders.set(key, value);
105
- }
106
-
107
- return new Response(res.body, {
108
- status: res.status,
109
- statusText: res.statusText,
110
- headers: newHeaders,
111
- });
102
+ return withHeaders(res, Object.entries(headers));
112
103
  },
113
104
  };
114
105
  }
@@ -1,7 +1,4 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { preloadLinks } from "./preload.ts";
3
- import { createTimer } from "./timing.ts";
4
- import { optimizeImages } from "./images.ts";
5
2
  import { SafeHtml } from "@sigil-dev/runtime";
6
3
  import { startCollecting, stopCollecting } from "../client/deps";
7
4
  import { filterPublic } from "../env/index";
@@ -9,11 +6,18 @@ import { findClosestError, type MatchedRoute } from "../routing/router";
9
6
  import type { RouteFile } from "../routing/scanner";
10
7
  import { isErrorResult } from "../sentinels/error.ts";
11
8
  import { isRedirectResult } from "../sentinels/redirect.ts";
12
- import { runWithContext } from "../server/context";
13
9
  import { clientAddressOf } from "../server/client-address";
10
+ import { hydrateEntry } from "../server/client-entry";
11
+ import { runWithContext } from "../server/context";
14
12
  import { runHook } from "../server/plugins";
15
13
  import type { GrimoirePlugin, LoadContext, Route } from "../types";
16
14
  import { collectHead, initHead } from "./head";
15
+ import { optimizeImages } from "./images.ts";
16
+ import { preloadLinks } from "./preload.ts";
17
+ import { createTimer } from "./timing.ts";
18
+
19
+ /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
20
+ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
17
21
 
18
22
  export type ModuleLoader = (path: string) => Promise<any>;
19
23
 
@@ -113,7 +117,7 @@ function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
113
117
  <head>
114
118
  <meta charset="UTF-8" />
115
119
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
116
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
120
+ <script type="module" src="/__grimoire__/${hydrateEntry()}"${nonceAttr}></script>
117
121
  ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
118
122
  }
119
123
 
@@ -365,7 +369,7 @@ export async function renderRoute(
365
369
  e,
366
370
  loadModule,
367
371
  { layoutPairs, params: matched.params, nonceAttr, dev },
368
- )) ?? new Response(e.message, { status: e.status })
372
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
369
373
  );
370
374
  throw e;
371
375
  }
@@ -395,7 +399,7 @@ export async function renderRoute(
395
399
  e,
396
400
  loadModule,
397
401
  { layoutPairs, params: matched.params, nonceAttr, dev },
398
- )) ?? new Response(e.message, { status: e.status })
402
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
399
403
  );
400
404
  throw e;
401
405
  }
@@ -459,7 +463,7 @@ export async function renderRoute(
459
463
  e,
460
464
  loadModule,
461
465
  { layoutPairs, params: matched.params, nonceAttr, dev },
462
- )) ?? new Response(e.message, { status: e.status })
466
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
463
467
  );
464
468
  throw e;
465
469
  }
@@ -493,7 +497,7 @@ export async function renderRoute(
493
497
  e,
494
498
  loadModule,
495
499
  { layoutPairs, params: matched.params, nonceAttr, dev },
496
- )) ?? new Response(e.message, { status: e.status })
500
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
497
501
  );
498
502
  throw e;
499
503
  }
@@ -13,6 +13,7 @@
13
13
  import { existsSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { clientDir } from "../server/client-dir";
16
+ import { hydrateEntry } from "../server/client-entry";
16
17
 
17
18
  interface ChunkGraph {
18
19
  /** route pattern → chunk id */
@@ -52,9 +53,14 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
52
53
  return { routes, nodes };
53
54
  }
54
55
 
56
+ let graphOf: string | undefined;
57
+
55
58
  function load(): ChunkGraph | null {
56
- if (graph !== undefined) return graph;
57
- const file = join(clientDir(), "hydrate.js");
59
+ // a new entry name means a new build, whose chunks differ
60
+ const entry = hydrateEntry();
61
+ if (graph !== undefined && graphOf === entry) return graph;
62
+ graphOf = entry;
63
+ const file = join(clientDir(), entry);
58
64
  graph = existsSync(file) ? parseChunkGraph(readFileSync(file, "utf-8")) : null;
59
65
  return graph;
60
66
  }
@@ -49,9 +49,7 @@ let shuttingDown = false;
49
49
  */
50
50
  export function afterResponse(fn: () => unknown): Promise<unknown> {
51
51
  if (shuttingDown) {
52
- return Promise.reject(
53
- new Error("afterResponse() called during shutdown"),
54
- );
52
+ return Promise.reject(new Error("afterResponse() called during shutdown"));
55
53
  }
56
54
 
57
55
  // Wrap so a synchronous throw inside fn becomes a rejection instead of
@@ -113,10 +111,24 @@ export async function withAfterResponse(
113
111
  for (const t of tasks) t();
114
112
  };
115
113
 
116
- if (!(response instanceof Response) || response.body === null) {
114
+ if (!(response instanceof Response)) {
117
115
  fire();
118
116
  return response as Response;
119
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
+ }
120
132
 
121
133
  const { readable, writable } = new TransformStream();
122
134
  // Errors on the original body propagate, and the tasks still run: a
@@ -24,6 +24,8 @@ export function isContentAddressed(pathname: string, search: string): boolean {
24
24
  // chunk: "chunk-" and a hash of the contents. Anchored on the prefix, since
25
25
  // a bare "8+ letters before the extension" would also match hero-background.png.
26
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;
27
29
  // A non-empty version query, e.g. /style.css?v=3. Deliberately does not
28
30
  // treat `?` with an empty value as addressed: /style.css? is the same
29
31
  // URL and would cache forever without ever changing.
@@ -8,6 +8,7 @@ import { transformRoutes } from "../routing/transform-routes";
8
8
  import { generateTypes } from "../typegen";
9
9
  import type { BuildResult, GrimoireConfig, GrimoirePlugin } from "../types";
10
10
  import { clientDir, pruneClientDir, resetClientDir } from "./client-dir";
11
+ import { recordClientEntry } from "./client-entry";
11
12
  import { runHook } from "./plugins";
12
13
  import { projectAliases, resolverPlugin } from "./resolver";
13
14
 
@@ -67,6 +68,7 @@ export async function rebuildClient(
67
68
  Bun.build({
68
69
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
69
70
  outdir: bundleDir,
71
+ naming: { entry: "[name]-[hash].[ext]" },
70
72
  // report failures in result.logs instead of throwing past them
71
73
  throw: false,
72
74
  // lazy route entries in the manifest use dynamic import()
@@ -80,6 +82,7 @@ export async function rebuildClient(
80
82
  Bun.build({
81
83
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
82
84
  outdir: bundleDir,
85
+ naming: { entry: "[name]-[hash].[ext]" },
83
86
  // report failures in result.logs instead of throwing past them
84
87
  throw: false,
85
88
  splitting: true,
@@ -96,7 +99,10 @@ export async function rebuildClient(
96
99
  );
97
100
  const success = hydrateResult.success && domResult.success;
98
101
  // a failed build keeps the last good bundle in place
99
- if (success) await pruneClientDir(outputs);
102
+ if (success) {
103
+ recordClientEntry([...hydrateResult.outputs, ...domResult.outputs]);
104
+ await pruneClientDir(outputs);
105
+ }
100
106
 
101
107
  return {
102
108
  tree,
@@ -174,6 +180,7 @@ export async function buildProject(
174
180
  join(import.meta.dir, "../client/index.ts"),
175
181
  ],
176
182
  outdir: bundleDir,
183
+ naming: { entry: "[name]-[hash].[ext]" },
177
184
  // report failures in result.logs instead of throwing past them
178
185
  throw: false,
179
186
  // lazy route entries in the manifest use dynamic import()
@@ -189,6 +196,8 @@ export async function buildProject(
189
196
 
190
197
  if (!singleResult.success) {
191
198
  for (const log of singleResult.logs) console.error(log);
199
+ } else {
200
+ recordClientEntry(singleResult.outputs);
192
201
  }
193
202
 
194
203
  const result: BuildResult = {
@@ -205,6 +214,7 @@ export async function buildProject(
205
214
  Bun.build({
206
215
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
207
216
  outdir: bundleDir,
217
+ naming: { entry: "[name]-[hash].[ext]" },
208
218
  // report failures in result.logs instead of throwing past them
209
219
  throw: false,
210
220
  // lazy route entries in the manifest use dynamic import()
@@ -218,6 +228,7 @@ export async function buildProject(
218
228
  Bun.build({
219
229
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
220
230
  outdir: bundleDir,
231
+ naming: { entry: "[name]-[hash].[ext]" },
221
232
  // report failures in result.logs instead of throwing past them
222
233
  throw: false,
223
234
  splitting: true,
@@ -231,6 +242,8 @@ export async function buildProject(
231
242
 
232
243
  if (!hydrateResult.success) {
233
244
  for (const log of hydrateResult.logs) console.error(log);
245
+ } else {
246
+ recordClientEntry(hydrateResult.outputs);
234
247
  }
235
248
  if (!domResult.success) {
236
249
  for (const log of domResult.logs) console.error(log);
@@ -0,0 +1,44 @@
1
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+
4
+ /**
5
+ * The client entry is named by its content (`hydrate-a1b2c3d4.js`), like the
6
+ * chunks, so each build has its own URL. A fixed `hydrate.js` let a CDN that
7
+ * caches scripts regardless of Cache-Control (Cloudflare does by default)
8
+ * keep serving the previous build's script against the new build's HTML,
9
+ * for hours after every deploy. The build records the name here.
10
+ */
11
+ const entryFile = (root = process.cwd()) =>
12
+ join(root, ".grimoire", "client-entry.json");
13
+
14
+ let cached: { mtime: number; hydrate: string } | undefined;
15
+
16
+ /** The hydrate entry's file name, relative to /__grimoire__/. */
17
+ export function hydrateEntry(root = process.cwd()): string {
18
+ try {
19
+ const mtime = statSync(entryFile(root)).mtimeMs;
20
+ if (cached?.mtime !== mtime) {
21
+ const { hydrate } = JSON.parse(readFileSync(entryFile(root), "utf8"));
22
+ cached = { mtime, hydrate };
23
+ }
24
+ return cached.hydrate;
25
+ } catch {
26
+ // built by an older version, or not built yet
27
+ return "hydrate.js";
28
+ }
29
+ }
30
+
31
+ /** Records the entry a build produced. */
32
+ export function recordClientEntry(
33
+ outputs: readonly { path: string; kind: string }[],
34
+ root = process.cwd(),
35
+ ): void {
36
+ const entry = outputs.find(
37
+ (o) => o.kind === "entry-point" && basename(o.path).startsWith("hydrate"),
38
+ );
39
+ if (!entry) return;
40
+ writeFileSync(
41
+ entryFile(root),
42
+ JSON.stringify({ hydrate: basename(entry.path) }),
43
+ );
44
+ }
@@ -1,6 +1,4 @@
1
1
  import { existsSync, mkdirSync } from "node:fs";
2
- import { setServerTiming } from "../rendering/timing.ts";
3
- import { preloadModules, startWarming, type Warmer } from "./warm.ts";
4
2
  import { isAbsolute, join } from "node:path";
5
3
  import { plugin as bunPlugin, type ServerWebSocket } from "bun";
6
4
  import { getDevModule } from "../dev/compile-module.ts";
@@ -13,15 +11,16 @@ import { crawlFrom } from "../dev/scan.ts";
13
11
  import { startWatcher } from "../dev/watcher.ts";
14
12
  import { envModuleSource } from "../env/modules";
15
13
  import { log } from "../logger/instance.ts";
16
- import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
17
- import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
18
14
  import { renderErrorPage, renderRoute } from "../rendering";
19
15
  import { registerSSRPlugin } from "../rendering/ssrPlugin";
16
+ import { setServerTiming } from "../rendering/timing.ts";
20
17
  import { matchNotFound, matchRoute } from "../routing/router";
21
18
  import { isErrorResult } from "../sentinels/error.ts";
22
19
  import { isFailResult } from "../sentinels/fail.ts";
23
20
  import { isRedirectResult } from "../sentinels/redirect.ts";
24
21
  import type { GrimoireConfig, WsRouteHandler } from "../types";
22
+ import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
23
+ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
25
24
  import { buildProject, rebuildClient } from "./build";
26
25
  import { clientAddressOf, trackClientAddress } from "./client-address";
27
26
  import { CLIENT_URL, clientDir } from "./client-dir";
@@ -42,6 +41,11 @@ import {
42
41
  runRequestHooks,
43
42
  } from "./plugins";
44
43
  import { projectAliases, resolverPlugin } from "./resolver";
44
+ import { preloadModules, startWarming, type Warmer } from "./warm.ts";
45
+ import { withHeaders } from "./with-headers";
46
+
47
+ /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
48
+ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
45
49
 
46
50
  const logger = log.scope("server");
47
51
 
@@ -758,7 +762,8 @@ export async function createServer(config: GrimoireConfig = {}) {
758
762
  e,
759
763
  loader,
760
764
  { params: matched.params, nonceAttr, dev },
761
- )) ?? new Response(e.message, { status: e.status })
765
+ )) ??
766
+ new Response(e.message, { status: e.status, headers: TEXT })
762
767
  );
763
768
  }
764
769
  throw e;
@@ -898,7 +903,7 @@ export async function createServer(config: GrimoireConfig = {}) {
898
903
  process.env.NODE_ENV === "production"
899
904
  ? "Internal Server Error"
900
905
  : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
901
- return new Response(message, { status: 500 });
906
+ return new Response(message, { status: 500, headers: TEXT });
902
907
  }
903
908
 
904
909
  const setCookieHeaders = cookies.toHeaders();
@@ -909,20 +914,11 @@ export async function createServer(config: GrimoireConfig = {}) {
909
914
  ) {
910
915
  return response;
911
916
  }
912
- const headers = new Headers(response.headers);
913
- for (const [k, v] of Object.entries(setHeadersMap)) {
914
- headers.set(k, v);
915
- }
916
- for (const sc of setCookieHeaders) {
917
- headers.append("Set-Cookie", sc);
918
- }
919
- response = new Response(response.body, {
920
- status: response.status,
921
- statusText: response.statusText,
922
- headers,
923
- });
924
-
925
- return response;
917
+ return withHeaders(
918
+ response,
919
+ Object.entries(setHeadersMap),
920
+ setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
921
+ );
926
922
  });
927
923
  }
928
924
 
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Adds headers to a response. Sets them in place when it can: rebuilding
3
+ * from `response.body` would turn a body Bun types itself (a string, a
4
+ * file) into a stream that is sent with no Content-Type, which browsers
5
+ * treat as a download. A response whose headers are locked (one from
6
+ * fetch) is rebuilt, keeping its type.
7
+ */
8
+ export function withHeaders(
9
+ response: Response,
10
+ set: Iterable<[string, string]>,
11
+ append: Iterable<[string, string]> = [],
12
+ ): Response {
13
+ try {
14
+ for (const [k, v] of set) response.headers.set(k, v);
15
+ for (const [k, v] of append) response.headers.append(k, v);
16
+ return response;
17
+ } catch {
18
+ const headers = new Headers(response.headers);
19
+ for (const [k, v] of set) headers.set(k, v);
20
+ for (const [k, v] of append) headers.append(k, v);
21
+ return new Response(response.body, {
22
+ status: response.status,
23
+ statusText: response.statusText,
24
+ headers,
25
+ });
26
+ }
27
+ }
@@ -27,6 +27,25 @@ describe("afterResponse", () => {
27
27
  expect(ran).toBe(true);
28
28
  });
29
29
 
30
+ test("a body Bun types itself is still typed when served", async () => {
31
+ const server = Bun.serve({
32
+ port: 0,
33
+ fetch: (r) =>
34
+ withAfterResponse(r, async () => {
35
+ afterResponse(() => {});
36
+ return new Response("not found", { status: 404 });
37
+ }),
38
+ });
39
+ try {
40
+ const res = await fetch(`http://localhost:${server.port}/`);
41
+ expect(res.status).toBe(404);
42
+ expect(res.headers.get("content-type")).toStartWith("text/plain");
43
+ expect(await res.text()).toBe("not found");
44
+ } finally {
45
+ server.stop(true);
46
+ }
47
+ });
48
+
30
49
  test("runs for a response with no body", async () => {
31
50
  let ran = false;
32
51
  await withAfterResponse(req(), async () => {
@@ -67,3 +67,35 @@ describe("the client bundle directory", () => {
67
67
  ]);
68
68
  });
69
69
  });
70
+
71
+ describe("the client entry", () => {
72
+ test("is recorded by name and read back, falling back to hydrate.js", async () => {
73
+ const { hydrateEntry, recordClientEntry } = await import(
74
+ "../src/server/client-entry.ts"
75
+ );
76
+ root = mkdtempSync(join(tmpdir(), "client-entry-"));
77
+ expect(hydrateEntry(root)).toBe("hydrate.js");
78
+ mkdirSync(join(root, ".grimoire"), { recursive: true });
79
+ recordClientEntry(
80
+ [
81
+ { path: join(clientDir(root), "chunk-aaaaaaaa.js"), kind: "chunk" },
82
+ {
83
+ path: join(clientDir(root), "hydrate-k3x9q2ab.js"),
84
+ kind: "entry-point",
85
+ },
86
+ ],
87
+ root,
88
+ );
89
+ expect(hydrateEntry(root)).toBe("hydrate-k3x9q2ab.js");
90
+ });
91
+
92
+ test("a hashed entry is cached for good; a fixed name is revalidated", async () => {
93
+ const { cacheControlFor } = await import("../src/server/asset-cache.ts");
94
+ expect(cacheControlFor("/__grimoire__/hydrate-k3x9q2ab.js", "")).toBe(
95
+ "immutable",
96
+ );
97
+ expect(cacheControlFor("/__grimoire__/hydrate.js", "")).toBe("revalidate");
98
+ // a public file shaped like one is not assumed to be hashed
99
+ expect(cacheControlFor("/jquery-plugins.js", "")).toBe("revalidate");
100
+ });
101
+ });