@sigil-dev/grimoire 0.9.21 → 0.9.23

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 +22 -10
  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 +871 -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 -105
  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 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  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 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  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 -44
  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 +211 -80
  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 -27
  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 -132
  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 -101
  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 +1 -1
  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 +799 -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 +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -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 +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Prerendering: turn routes into files by sending requests through the real
3
+ * pipeline.
4
+ *
5
+ * Going through `app.fetch` and not calling the renderer directly is the point.
6
+ * `hooks.server.ts`, plugins, layouts and load functions all run exactly as
7
+ * they will in production, so a prerendered page cannot differ from the live
8
+ * one because a code path was skipped.
9
+ *
10
+ * The pure helpers at the top (path/file mapping, link extraction) are exported
11
+ * for tests. `prerenderSite` is the orchestration.
12
+ */
13
+
14
+ import { cp, mkdir, rm, writeFile } from "node:fs/promises";
15
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
16
+ import type { AdapterContext } from "../adapters/types";
17
+ import { normalizeBase, stripBase, withBase } from "../base";
18
+ import { matchRoute } from "../routing/router";
19
+ import type { RouteFile, RouteTree } from "../routing/scanner";
20
+ import { RESERVED_EXPORTS } from "./reserved";
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // pure helpers
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /** `/blog/:slug` + `{ slug: "a b" }` → `/blog/a%20b`. Null when a required param is missing. */
27
+ export function fillPattern(
28
+ pattern: string,
29
+ params: Record<string, string | undefined>,
30
+ ): string | null {
31
+ const out: string[] = [];
32
+ for (const part of pattern.split("/").filter(Boolean)) {
33
+ if (part.startsWith("*")) {
34
+ const value = params[part.slice(1)];
35
+ if (value) {
36
+ out.push(
37
+ value
38
+ .split("/")
39
+ .map((s) => encodeURIComponent(s))
40
+ .join("/"),
41
+ );
42
+ }
43
+ } else if (part.startsWith(":")) {
44
+ const optional = part.endsWith("?");
45
+ const name = part.slice(1, optional ? -1 : undefined);
46
+ const value = params[name];
47
+ if (value === undefined || value === "") {
48
+ if (optional) continue;
49
+ return null;
50
+ }
51
+ out.push(encodeURIComponent(value));
52
+ } else {
53
+ out.push(part);
54
+ }
55
+ }
56
+ return `/${out.join("/")}`;
57
+ }
58
+
59
+ const HAS_EXTENSION = /\.[A-Za-z0-9]+$/;
60
+
61
+ /** The file a page at `pathname` is written to: `/` → `index.html`, `/a/b` → `a/b/index.html`. */
62
+ export function htmlFileFor(pathname: string): string {
63
+ const clean = pathname.replace(/^\/+|\/+$/g, "");
64
+ if (!clean) return "index.html";
65
+ if (/\.html?$/.test(clean)) return clean;
66
+ return `${clean}/index.html`;
67
+ }
68
+
69
+ /**
70
+ * Where the client router finds the navigation payload for `pathname` on a
71
+ * static host. The router builds the same string, so the two must agree.
72
+ */
73
+ export function dataFileFor(pathname: string): string {
74
+ const clean = pathname.replace(/^\/+|\/+$/g, "");
75
+ return clean ? `${clean}/__data.json` : "__data.json";
76
+ }
77
+
78
+ /**
79
+ * Same-origin page paths linked from `html`, normalised: no query, no hash, no
80
+ * trailing slash, nothing that points at a file with an extension (assets, feeds).
81
+ */
82
+ export function extractLinks(
83
+ html: string,
84
+ origin: string,
85
+ base = "",
86
+ ): string[] {
87
+ const found = new Set<string>();
88
+ for (const m of html.matchAll(/\shref\s*=\s*("([^"]*)"|'([^']*)')/gi)) {
89
+ const href = (m[2] ?? m[3] ?? "").trim();
90
+ let path: string | null = null;
91
+ if (href.startsWith("/") && !href.startsWith("//")) path = href;
92
+ else if (href.startsWith(`${origin}/`)) path = href.slice(origin.length);
93
+ if (path === null) continue;
94
+ path = path.split("#")[0]!.split("?")[0]!;
95
+ // a link outside the base is not one of this site's pages
96
+ if (base) {
97
+ const route = stripBase(path, base);
98
+ if (route === null) continue;
99
+ path = route;
100
+ }
101
+ if (path.length > 1) path = path.replace(/\/+$/, "");
102
+ if (!path) continue;
103
+ if (HAS_EXTENSION.test(path) && !/\.html?$/.test(path)) continue;
104
+ found.add(path);
105
+ }
106
+ return [...found];
107
+ }
108
+
109
+ /**
110
+ * Tell the client router this site has no server to ask for navigation JSON.
111
+ * It then reads `<page>/__data.json`, which prerendering wrote beside the page.
112
+ */
113
+ export function markStatic(html: string): string {
114
+ const tag = "<script>globalThis.__grimoire_static__=1</script>";
115
+ if (/<\/head>/i.test(html)) return html.replace(/<\/head>/i, `${tag}</head>`);
116
+ return tag + html;
117
+ }
118
+
119
+ function redirectPage(location: string): string {
120
+ const safe = location.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
121
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${safe}"><link rel="canonical" href="${safe}"><a href="${safe}">Redirecting</a>`;
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // route options
126
+ // ---------------------------------------------------------------------------
127
+
128
+ interface RouteOptions {
129
+ /** `export const prerender`, from the page, its server file or the nearest layout. */
130
+ prerender: boolean | undefined;
131
+ entries: (() => unknown) | undefined;
132
+ /** Names of exports that are actions: they need a server, so they cannot be prerendered. */
133
+ actions: string[];
134
+ }
135
+
136
+ type Importer = (path: string) => Promise<Record<string, unknown>>;
137
+
138
+ async function readOptions(
139
+ route: RouteFile,
140
+ tree: RouteTree,
141
+ load: Importer,
142
+ ): Promise<RouteOptions> {
143
+ const layoutFor = (l: RouteFile) =>
144
+ l.path === "/" ||
145
+ route.path === l.path ||
146
+ route.path.startsWith(`${l.path}/`);
147
+ const pageServer = tree.routes.find(
148
+ (r) => r.type === "pageServer" && r.path === route.path,
149
+ );
150
+ // most specific first: page server, page, then layouts innermost to root
151
+ const sources = [
152
+ pageServer?.filePath,
153
+ route.filePath,
154
+ ...tree.layouts
155
+ .filter(layoutFor)
156
+ .sort((a, b) => b.path.length - a.path.length)
157
+ .map((l) => l.filePath),
158
+ ].filter((p): p is string => !!p);
159
+
160
+ let prerender: boolean | undefined;
161
+ let entries: RouteOptions["entries"];
162
+ const actions: string[] = [];
163
+ for (const file of sources) {
164
+ const mod = await load(file);
165
+ if (prerender === undefined && typeof mod.prerender === "boolean") {
166
+ prerender = mod.prerender;
167
+ }
168
+ if (!entries && typeof mod.entries === "function") {
169
+ entries = mod.entries as () => unknown;
170
+ }
171
+ if (file === pageServer?.filePath) {
172
+ for (const [name, value] of Object.entries(mod)) {
173
+ if (typeof value === "function" && !RESERVED_EXPORTS.has(name)) {
174
+ actions.push(name);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ return { prerender, entries, actions };
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // orchestration
184
+ // ---------------------------------------------------------------------------
185
+
186
+ export interface PrerenderOptions {
187
+ /** Directory the site is written to, relative to the project root. */
188
+ out: string;
189
+ /** What `url.origin` is while rendering. Default `http://localhost`. */
190
+ origin?: string;
191
+ /** Follow `<a href>` from rendered pages to find more pages. Default true. */
192
+ crawl?: boolean;
193
+ /** Extra paths to render. */
194
+ paths?: string[];
195
+ /** Fail the build when something cannot be a file. When false, warn and skip. Default true. */
196
+ strict?: boolean;
197
+ /** Parallel requests. Default 6. */
198
+ concurrency?: number;
199
+ }
200
+
201
+ export interface PrerenderReport {
202
+ pages: string[];
203
+ problems: string[];
204
+ }
205
+
206
+ export async function prerenderSite(
207
+ ctx: AdapterContext,
208
+ opts: PrerenderOptions,
209
+ load: Importer = (p) => import(p),
210
+ ): Promise<PrerenderReport> {
211
+ const { app, root, log } = ctx;
212
+ const tree = app.tree as RouteTree;
213
+ // `[id=int]` routes only match through their matcher; without it nothing
214
+ // that has one could be reached, linked to, or counted as rendered.
215
+ const matchers = app.matchers;
216
+ const origin = opts.origin ?? "http://localhost";
217
+ // requests carry the base; the files written do not, because the host
218
+ // serves the output directory *as* the base
219
+ const base = normalizeBase(app.config.base);
220
+ const strict = opts.strict ?? true;
221
+ const crawl = opts.crawl ?? true;
222
+ const concurrency = Math.max(1, opts.concurrency ?? 6);
223
+ const problems: string[] = [];
224
+ const outDir = resolve(root, opts.out);
225
+ assertSafeOut(root, outDir);
226
+
227
+ // ---- seeds ----------------------------------------------------------
228
+ const pageRoutes = tree.routes.filter(
229
+ (r) => r.type === "page" || r.type === "simple",
230
+ );
231
+ const queue: { path: string; from: string }[] = [];
232
+ const seen = new Set<string>();
233
+ const enqueue = (path: string, from: string) => {
234
+ if (seen.has(path)) return;
235
+ seen.add(path);
236
+ queue.push({ path, from });
237
+ };
238
+
239
+ const excluded = new Set<string>();
240
+ for (const route of pageRoutes) {
241
+ const o = await readOptions(route, tree, load);
242
+ if (o.prerender === false) {
243
+ excluded.add(route.path);
244
+ problems.push(
245
+ `${route.clientPath} sets prerender = false, so it cannot exist on a static host.`,
246
+ );
247
+ continue;
248
+ }
249
+ if (o.actions.length) {
250
+ excluded.add(route.path);
251
+ problems.push(
252
+ `${route.path} has server actions (${o.actions.join(", ")}) and a static site has no server to run them.`,
253
+ );
254
+ continue;
255
+ }
256
+ const dynamic =
257
+ route.paramNames.length > 0 ||
258
+ route.restParamNames.length > 0 ||
259
+ route.optionalParamNames.length > 0;
260
+ if (!dynamic) {
261
+ enqueue(route.path, route.clientPath);
262
+ } else if (o.entries) {
263
+ const list = await o.entries();
264
+ if (!Array.isArray(list)) {
265
+ problems.push(
266
+ `${route.clientPath}: entries() must return an array of param objects.`,
267
+ );
268
+ continue;
269
+ }
270
+ for (const params of list as Record<string, string>[]) {
271
+ const path = fillPattern(route.path, params ?? {});
272
+ if (path === null) {
273
+ problems.push(
274
+ `${route.clientPath}: entries() returned ${JSON.stringify(params)}, which is missing a param of "${route.path}".`,
275
+ );
276
+ } else enqueue(path, `${route.clientPath} entries()`);
277
+ }
278
+ }
279
+ }
280
+ for (const path of opts.paths ?? []) enqueue(path, "config paths");
281
+
282
+ // +server.ts routes: only an explicit GET with `prerender = true` can be a file.
283
+ const files = new Map<string, string | Uint8Array>();
284
+ for (const server of tree.servers) {
285
+ const mod = await load(server.filePath);
286
+ const methods = Object.keys(mod).filter((k) =>
287
+ ["POST", "PUT", "PATCH", "DELETE"].includes(k),
288
+ );
289
+ const wantsFile = mod.prerender === true && typeof mod.GET === "function";
290
+ if (wantsFile && !methods.length && !mod.websocket) {
291
+ const path = fillPattern(server.path, {});
292
+ if (!path || !HAS_EXTENSION.test(path)) {
293
+ problems.push(
294
+ `${server.clientPath} has prerender = true but "${server.path}" has no file extension or takes params, so there is no file name to write.`,
295
+ );
296
+ } else enqueue(path, server.clientPath);
297
+ } else {
298
+ problems.push(
299
+ `${server.clientPath} is a server endpoint${mod.websocket ? " with a websocket" : ""}; a static site cannot run it. ` +
300
+ "Export `prerender = true` from a GET-only file with an extension in its path (like sitemap.xml) to bake it into a file.",
301
+ );
302
+ }
303
+ }
304
+
305
+ // ---- render ---------------------------------------------------------
306
+ /** Queue a discovered link, unless it is no page or one already ruled out. */
307
+ const follow = (path: string, from: string) => {
308
+ const m = matchRoute(tree, new URL(origin + path), matchers);
309
+ if (m && !excluded.has(m.route.path)) enqueue(path, from);
310
+ };
311
+ const written: string[] = [];
312
+ const render = async (item: { path: string; from: string }) => {
313
+ const url = origin + withBase(item.path, base);
314
+ let res: Response;
315
+ try {
316
+ res = await app.fetch(new Request(url));
317
+ } catch (e) {
318
+ problems.push(
319
+ `${item.path} (from ${item.from}) threw: ${(e as Error).message}`,
320
+ );
321
+ return;
322
+ }
323
+ if (res.status >= 300 && res.status < 400) {
324
+ const location = res.headers.get("location") ?? "/";
325
+ files.set(htmlFileFor(item.path), redirectPage(location));
326
+ written.push(item.path);
327
+ // A redirect to another page of this site is a page to render too.
328
+ if (crawl && location.startsWith("/")) {
329
+ const route = stripBase(location.split(/[?#]/)[0]!, base);
330
+ if (route !== null) follow(route, item.path);
331
+ }
332
+ return;
333
+ }
334
+ if (res.status !== 200) {
335
+ problems.push(`${item.path} (from ${item.from}) returned ${res.status}.`);
336
+ return;
337
+ }
338
+ const type = res.headers.get("content-type") ?? "";
339
+ if (!type.includes("text/html")) {
340
+ // a prerendered endpoint: bytes, exactly as served
341
+ files.set(
342
+ item.path.replace(/^\/+/, ""),
343
+ new Uint8Array(await res.arrayBuffer()),
344
+ );
345
+ written.push(item.path);
346
+ return;
347
+ }
348
+ const html = await res.text();
349
+ files.set(htmlFileFor(item.path), markStatic(html));
350
+ written.push(item.path);
351
+
352
+ // The navigation payload the client router reads in place of a server.
353
+ const nav = await app.fetch(
354
+ new Request(url, { headers: { "x-grimoire-navigate": "1" } }),
355
+ );
356
+ if ((nav.headers.get("content-type") ?? "").includes("application/json")) {
357
+ files.set(dataFileFor(item.path), await nav.text());
358
+ }
359
+ if (crawl) {
360
+ for (const link of extractLinks(html, origin, base)) follow(link, item.path);
361
+ }
362
+ };
363
+
364
+ while (queue.length) {
365
+ const batch = queue.splice(0, concurrency);
366
+ await Promise.all(batch.map(render));
367
+ }
368
+
369
+ // ---- coverage -------------------------------------------------------
370
+ const reached = new Set<string>();
371
+ for (const path of written) {
372
+ const m = matchRoute(tree, new URL(origin + path), matchers);
373
+ if (m) reached.add(m.route.path);
374
+ }
375
+ for (const route of pageRoutes) {
376
+ if (reached.has(route.path) || excluded.has(route.path)) continue;
377
+ problems.push(
378
+ `${route.clientPath} was never rendered: "${route.path}" takes params and nothing produced one. ` +
379
+ "Export `entries()` from the page, or link to it from a page that is prerendered.",
380
+ );
381
+ }
382
+
383
+ // ---- not found ------------------------------------------------------
384
+ try {
385
+ const nf = await app.fetch(new Request(`${origin}${withBase("/__grimoire_not_found__", base)}`));
386
+ if (
387
+ nf.status === 404 &&
388
+ (nf.headers.get("content-type") ?? "").includes("text/html")
389
+ ) {
390
+ files.set("404.html", markStatic(await nf.text()));
391
+ }
392
+ } catch {
393
+ // no error page is fine; the host shows its own
394
+ }
395
+
396
+ if (problems.length && strict) {
397
+ throw new Error(
398
+ `Prerender found ${problems.length} problem${problems.length > 1 ? "s" : ""}:\n${problems
399
+ .map((p) => ` - ${p}`)
400
+ .join(
401
+ "\n",
402
+ )}\n\nFix them, or set { strict: false } on the adapter to skip what cannot be a file.`,
403
+ );
404
+ }
405
+ for (const p of problems) log.warn(p);
406
+
407
+ // ---- write ----------------------------------------------------------
408
+ await rm(outDir, { recursive: true, force: true });
409
+ await mkdir(outDir, { recursive: true });
410
+ await cp(join(root, "public"), outDir, { recursive: true }).catch(
411
+ (e: NodeJS.ErrnoException) => {
412
+ if (e.code !== "ENOENT") throw e;
413
+ },
414
+ );
415
+ for (const [rel, body] of files) {
416
+ const target = join(outDir, rel);
417
+ await mkdir(dirname(target), { recursive: true });
418
+ await writeFile(target, body);
419
+ }
420
+ return { pages: written.sort(), problems };
421
+ }
422
+
423
+ /** `out` is deleted before writing, so refuse anything that could take the project with it. */
424
+ function assertSafeOut(root: string, out: string): void {
425
+ const rel = relative(root, out);
426
+ if (rel === "") {
427
+ throw new Error(
428
+ `adapter-static: out "." is the project root. Use a directory like "build".`,
429
+ );
430
+ }
431
+ const inside = !rel.startsWith("..") && !isAbsolute(rel);
432
+ if (inside) {
433
+ const top = rel.split(sep)[0]!;
434
+ if (["src", "public", ".git", "node_modules", ".grimoire"].includes(top)) {
435
+ throw new Error(
436
+ `adapter-static: out "${rel}" is inside "${top}", which the build must not delete. Use a directory like "build".`,
437
+ );
438
+ }
439
+ } else if (!relative(out, root).startsWith("..")) {
440
+ throw new Error(
441
+ `adapter-static: out "${out}" contains the project. Use a directory inside it, like "build".`,
442
+ );
443
+ }
444
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `+page.server.ts` exports that are never dispatched as named actions.
3
+ *
4
+ * Every other function export is callable by name (`?/create`), so a helper
5
+ * a route module exports for the framework has to be listed here or a form
6
+ * could invoke it.
7
+ */
8
+ export const RESERVED_EXPORTS = new Set([
9
+ "load",
10
+ "canMatch",
11
+ "csrf",
12
+ "loading",
13
+ "default",
14
+ // read by the build, never by a request
15
+ "prerender",
16
+ "entries",
17
+ ]);
@@ -1,98 +1,98 @@
1
- import { isAbsolute, join } from "node:path";
2
- import type { BunPlugin } from "bun";
3
- import { resolveFile } from "../dev/resolve";
4
- import { ENV_MODULE, envModuleSource } from "../env/modules";
5
- import type { GrimoireConfig } from "../types";
6
-
7
- /**
8
- * Import prefixes → absolute directories: `$lib` for `src/lib` unless the
9
- * config says otherwise, plus `GrimoireConfig.alias`.
10
- */
11
- export function projectAliases(
12
- config: GrimoireConfig,
13
- root = process.cwd(),
14
- ): Record<string, string> {
15
- const out: Record<string, string> = { $lib: join(root, "src/lib") };
16
- for (const [prefix, target] of Object.entries(config.alias ?? {})) {
17
- out[prefix] = isAbsolute(target) ? target : join(root, target);
18
- }
19
- return out;
20
- }
21
-
22
- const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
-
24
- /**
25
- * Resolves `$env/*` and aliased imports, for the browser builds (Bun.build)
26
- * and for the server (Bun.plugin). Bun has no alias option of its own.
27
- */
28
- export function resolverPlugin(
29
- config: GrimoireConfig,
30
- target: "server" | "browser",
31
- ): BunPlugin {
32
- const aliases = projectAliases(config);
33
- return {
34
- name: `grimoire-resolve-${target}`,
35
- setup(build) {
36
- if (target === "server") {
37
- // Bun's runtime plugins don't see static imports in onResolve;
38
- // virtual modules have to be registered by name. Aliases on the
39
- // server are rewritten by the SSR plugin (rewriteAliases).
40
- for (const specifier of ENV_SPECIFIERS) {
41
- build.module(specifier, () => ({
42
- contents: envModuleSource(specifier, "server"),
43
- loader: "js",
44
- }));
45
- }
46
- return;
47
- }
48
- build.onResolve({ filter: ENV_MODULE }, (args) => ({
49
- path: args.path,
50
- namespace: "grimoire-env",
51
- }));
52
- build.onLoad({ filter: /.*/, namespace: "grimoire-env" }, (args) => ({
53
- contents: envModuleSource(args.path, target),
54
- loader: "js",
55
- }));
56
- for (const [prefix, dir] of Object.entries(aliases)) {
57
- build.onResolve(
58
- { filter: new RegExp(`^${escapeRegExp(prefix)}(/|$)`) },
59
- (args) => {
60
- const file = resolveFile(join(dir, args.path.slice(prefix.length)));
61
- return file ? { path: file } : undefined;
62
- },
63
- );
64
- }
65
- },
66
- };
67
- }
68
-
69
- const ENV_SPECIFIERS = [
70
- "$env/static/public",
71
- "$env/static/private",
72
- "$env/dynamic/public",
73
- "$env/dynamic/private",
74
- ];
75
-
76
- const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
77
-
78
- /** Point aliased import specifiers in compiled code at their files. */
79
- export function rewriteAliases(
80
- code: string,
81
- aliases: Record<string, string>,
82
- ): string {
83
- const prefixes = Object.keys(aliases);
84
- if (prefixes.length === 0) return code;
85
- return code.replace(
86
- SPEC_RE,
87
- (match, keyword: string, quote: string, specifier: string) => {
88
- const prefix = prefixes.find(
89
- (p) => specifier === p || specifier.startsWith(`${p}/`),
90
- );
91
- if (!prefix) return match;
92
- const file = resolveFile(
93
- join(aliases[prefix]!, specifier.slice(prefix.length)),
94
- );
95
- return file ? `${keyword}${quote}${file}${quote}` : match;
96
- },
97
- );
98
- }
1
+ import { isAbsolute, join } from "node:path";
2
+ import type { BunPlugin } from "bun";
3
+ import { resolveFile } from "../dev/resolve";
4
+ import { ENV_MODULE, envModuleSource } from "../env/modules";
5
+ import type { GrimoireConfig } from "../types";
6
+
7
+ /**
8
+ * Import prefixes → absolute directories: `$lib` for `src/lib` unless the
9
+ * config says otherwise, plus `GrimoireConfig.alias`.
10
+ */
11
+ export function projectAliases(
12
+ config: GrimoireConfig,
13
+ root = process.cwd(),
14
+ ): Record<string, string> {
15
+ const out: Record<string, string> = { $lib: join(root, "src/lib") };
16
+ for (const [prefix, target] of Object.entries(config.alias ?? {})) {
17
+ out[prefix] = isAbsolute(target) ? target : join(root, target);
18
+ }
19
+ return out;
20
+ }
21
+
22
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
+
24
+ /**
25
+ * Resolves `$env/*` and aliased imports, for the browser builds (Bun.build)
26
+ * and for the server (Bun.plugin). Bun has no alias option of its own.
27
+ */
28
+ export function resolverPlugin(
29
+ config: GrimoireConfig,
30
+ target: "server" | "browser",
31
+ ): BunPlugin {
32
+ const aliases = projectAliases(config);
33
+ return {
34
+ name: `grimoire-resolve-${target}`,
35
+ setup(build) {
36
+ if (target === "server") {
37
+ // Bun's runtime plugins don't see static imports in onResolve;
38
+ // virtual modules have to be registered by name. Aliases on the
39
+ // server are rewritten by the SSR plugin (rewriteAliases).
40
+ for (const specifier of ENV_SPECIFIERS) {
41
+ build.module(specifier, () => ({
42
+ contents: envModuleSource(specifier, "server"),
43
+ loader: "js",
44
+ }));
45
+ }
46
+ return;
47
+ }
48
+ build.onResolve({ filter: ENV_MODULE }, (args) => ({
49
+ path: args.path,
50
+ namespace: "grimoire-env",
51
+ }));
52
+ build.onLoad({ filter: /.*/, namespace: "grimoire-env" }, (args) => ({
53
+ contents: envModuleSource(args.path, target),
54
+ loader: "js",
55
+ }));
56
+ for (const [prefix, dir] of Object.entries(aliases)) {
57
+ build.onResolve(
58
+ { filter: new RegExp(`^${escapeRegExp(prefix)}(/|$)`) },
59
+ (args) => {
60
+ const file = resolveFile(join(dir, args.path.slice(prefix.length)));
61
+ return file ? { path: file } : undefined;
62
+ },
63
+ );
64
+ }
65
+ },
66
+ };
67
+ }
68
+
69
+ const ENV_SPECIFIERS = [
70
+ "$env/static/public",
71
+ "$env/static/private",
72
+ "$env/dynamic/public",
73
+ "$env/dynamic/private",
74
+ ];
75
+
76
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
77
+
78
+ /** Point aliased import specifiers in compiled code at their files. */
79
+ export function rewriteAliases(
80
+ code: string,
81
+ aliases: Record<string, string>,
82
+ ): string {
83
+ const prefixes = Object.keys(aliases);
84
+ if (prefixes.length === 0) return code;
85
+ return code.replace(
86
+ SPEC_RE,
87
+ (match, keyword: string, quote: string, specifier: string) => {
88
+ const prefix = prefixes.find(
89
+ (p) => specifier === p || specifier.startsWith(`${p}/`),
90
+ );
91
+ if (!prefix) return match;
92
+ const file = resolveFile(
93
+ join(aliases[prefix]!, specifier.slice(prefix.length)),
94
+ );
95
+ return file ? `${keyword}${quote}${file}${quote}` : match;
96
+ },
97
+ );
98
+ }
@@ -0,0 +1,28 @@
1
+ import type { GrimoirePlugin, RenderContext } from "../types";
2
+
3
+ /**
4
+ * Run every plugin's `rewriteHtml` over a page response without buffering it.
5
+ *
6
+ * Each plugin registers its element handlers on one shared `HTMLRewriter`,
7
+ * which then transforms the response body as a stream: the shell is rewritten
8
+ * and flushed while later chunks (streamed data, deferred patches) are still
9
+ * being produced. That is the whole difference from `onRouteRender`, which
10
+ * needs the finished document as a string and so cannot stream.
11
+ *
12
+ * Only HTML bodies are touched. A redirect, a JSON action result or an empty
13
+ * body is returned as it came.
14
+ */
15
+ export async function applyRewriters(
16
+ response: Response,
17
+ plugins: GrimoirePlugin[],
18
+ context: RenderContext,
19
+ ): Promise<Response> {
20
+ const active = plugins.filter((p) => p.rewriteHtml);
21
+ if (!active.length || response.body === null) return response;
22
+ if (!(response.headers.get("content-type") ?? "").includes("text/html")) {
23
+ return response;
24
+ }
25
+ const rewriter = new HTMLRewriter();
26
+ for (const plugin of active) await plugin.rewriteHtml?.(rewriter, context);
27
+ return rewriter.transform(response);
28
+ }