@sigil-dev/grimoire 0.9.29 → 0.9.30

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 (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +476 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +8 -0
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +140 -19
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +640 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,114 +1,114 @@
1
- /**
2
- * In-memory stale-while-revalidate cache for expensive server-side values.
3
- *
4
- * The common hand-rolled version is "if the entry is older than an hour,
5
- * rebuild it inline", which makes one unlucky visitor per hour (per worker)
6
- * wait for the rebuild. Here, once a value exists it is always returned at
7
- * once; an expired one is refreshed in the background, by a single shared
8
- * call, while callers keep getting the old value.
9
- *
10
- * const costumeIndex = cached(() => buildIndex(), { ttl: 3600_000 });
11
- * const index = await costumeIndex();
12
- *
13
- * const player = cachedBy((id: string) => fetchPlayer(id), { ttl: 60_000 });
14
- * await player("123");
15
- */
16
-
17
- export interface CachedOptions {
18
- /** How long (ms) a value is fresh. */
19
- ttl: number;
20
- /**
21
- * How long (ms) past `ttl` a stale value may still be served while the
22
- * refresh runs. Past it, the next caller waits. Default: forever.
23
- */
24
- staleFor?: number;
25
- /** cachedBy only: the most keys held; the least recently used goes first. */
26
- max?: number;
27
- /** Called when a background refresh fails; the stale value stays. */
28
- onError?: (error: unknown) => void;
29
- }
30
-
31
- interface Entry<T> {
32
- value: T;
33
- at: number;
34
- }
35
-
36
- export interface CachedFn<A extends unknown[], T> {
37
- (...args: A): Promise<T>;
38
- /** Drop one entry (or all with no argument); the next call refetches. */
39
- invalidate(...args: A | []): void;
40
- }
41
-
42
- function build<A extends unknown[], T>(
43
- fn: (...args: A) => Promise<T>,
44
- keyOf: (args: A) => string,
45
- opts: CachedOptions,
46
- ): CachedFn<A, T> {
47
- const { ttl, staleFor = Number.POSITIVE_INFINITY, max = 500, onError } = opts;
48
- const entries = new Map<string, Entry<T>>();
49
- const running = new Map<string, Promise<T>>();
50
-
51
- function refresh(key: string, args: A): Promise<T> {
52
- const existing = running.get(key);
53
- if (existing) return existing;
54
- const p = fn(...args).then(
55
- (value) => {
56
- running.delete(key);
57
- entries.delete(key); // re-insert so insertion order = recency
58
- entries.set(key, { value, at: Date.now() });
59
- while (entries.size > max) {
60
- const oldest = entries.keys().next().value as string;
61
- entries.delete(oldest);
62
- }
63
- return value;
64
- },
65
- (e) => {
66
- running.delete(key);
67
- throw e;
68
- },
69
- );
70
- running.set(key, p);
71
- return p;
72
- }
73
-
74
- const call = ((...args: A): Promise<T> => {
75
- const key = keyOf(args);
76
- const hit = entries.get(key);
77
- if (hit) {
78
- const age = Date.now() - hit.at;
79
- entries.delete(key); // a read counts as use
80
- entries.set(key, hit);
81
- if (age < ttl) return Promise.resolve(hit.value);
82
- if (age < ttl + staleFor) {
83
- refresh(key, args).catch((e) => onError?.(e));
84
- return Promise.resolve(hit.value);
85
- }
86
- }
87
- return refresh(key, args);
88
- }) as CachedFn<A, T>;
89
-
90
- call.invalidate = (...args: A | []) => {
91
- if (args.length === 0) {
92
- entries.clear();
93
- return;
94
- }
95
- entries.delete(keyOf(args as A));
96
- };
97
- return call;
98
- }
99
-
100
- /** A value with no arguments, cached process-wide. */
101
- export function cached<T>(
102
- fn: () => Promise<T>,
103
- opts: CachedOptions,
104
- ): CachedFn<[], T> {
105
- return build(fn, () => "", opts);
106
- }
107
-
108
- /** A value per argument list (compared as JSON), with an LRU cap. */
109
- export function cachedBy<A extends unknown[], T>(
110
- fn: (...args: A) => Promise<T>,
111
- opts: CachedOptions,
112
- ): CachedFn<A, T> {
113
- return build(fn, (args) => JSON.stringify(args), opts);
114
- }
1
+ /**
2
+ * In-memory stale-while-revalidate cache for expensive server-side values.
3
+ *
4
+ * The common hand-rolled version is "if the entry is older than an hour,
5
+ * rebuild it inline", which makes one unlucky visitor per hour (per worker)
6
+ * wait for the rebuild. Here, once a value exists it is always returned at
7
+ * once; an expired one is refreshed in the background, by a single shared
8
+ * call, while callers keep getting the old value.
9
+ *
10
+ * const costumeIndex = cached(() => buildIndex(), { ttl: 3600_000 });
11
+ * const index = await costumeIndex();
12
+ *
13
+ * const player = cachedBy((id: string) => fetchPlayer(id), { ttl: 60_000 });
14
+ * await player("123");
15
+ */
16
+
17
+ export interface CachedOptions {
18
+ /** How long (ms) a value is fresh. */
19
+ ttl: number;
20
+ /**
21
+ * How long (ms) past `ttl` a stale value may still be served while the
22
+ * refresh runs. Past it, the next caller waits. Default: forever.
23
+ */
24
+ staleFor?: number;
25
+ /** cachedBy only: the most keys held; the least recently used goes first. */
26
+ max?: number;
27
+ /** Called when a background refresh fails; the stale value stays. */
28
+ onError?: (error: unknown) => void;
29
+ }
30
+
31
+ interface Entry<T> {
32
+ value: T;
33
+ at: number;
34
+ }
35
+
36
+ export interface CachedFn<A extends unknown[], T> {
37
+ (...args: A): Promise<T>;
38
+ /** Drop one entry (or all with no argument); the next call refetches. */
39
+ invalidate(...args: A | []): void;
40
+ }
41
+
42
+ function build<A extends unknown[], T>(
43
+ fn: (...args: A) => Promise<T>,
44
+ keyOf: (args: A) => string,
45
+ opts: CachedOptions,
46
+ ): CachedFn<A, T> {
47
+ const { ttl, staleFor = Number.POSITIVE_INFINITY, max = 500, onError } = opts;
48
+ const entries = new Map<string, Entry<T>>();
49
+ const running = new Map<string, Promise<T>>();
50
+
51
+ function refresh(key: string, args: A): Promise<T> {
52
+ const existing = running.get(key);
53
+ if (existing) return existing;
54
+ const p = fn(...args).then(
55
+ (value) => {
56
+ running.delete(key);
57
+ entries.delete(key); // re-insert so insertion order = recency
58
+ entries.set(key, { value, at: Date.now() });
59
+ while (entries.size > max) {
60
+ const oldest = entries.keys().next().value as string;
61
+ entries.delete(oldest);
62
+ }
63
+ return value;
64
+ },
65
+ (e) => {
66
+ running.delete(key);
67
+ throw e;
68
+ },
69
+ );
70
+ running.set(key, p);
71
+ return p;
72
+ }
73
+
74
+ const call = ((...args: A): Promise<T> => {
75
+ const key = keyOf(args);
76
+ const hit = entries.get(key);
77
+ if (hit) {
78
+ const age = Date.now() - hit.at;
79
+ entries.delete(key); // a read counts as use
80
+ entries.set(key, hit);
81
+ if (age < ttl) return Promise.resolve(hit.value);
82
+ if (age < ttl + staleFor) {
83
+ refresh(key, args).catch((e) => onError?.(e));
84
+ return Promise.resolve(hit.value);
85
+ }
86
+ }
87
+ return refresh(key, args);
88
+ }) as CachedFn<A, T>;
89
+
90
+ call.invalidate = (...args: A | []) => {
91
+ if (args.length === 0) {
92
+ entries.clear();
93
+ return;
94
+ }
95
+ entries.delete(keyOf(args as A));
96
+ };
97
+ return call;
98
+ }
99
+
100
+ /** A value with no arguments, cached process-wide. */
101
+ export function cached<T>(
102
+ fn: () => Promise<T>,
103
+ opts: CachedOptions,
104
+ ): CachedFn<[], T> {
105
+ return build(fn, () => "", opts);
106
+ }
107
+
108
+ /** A value per argument list (compared as JSON), with an LRU cap. */
109
+ export function cachedBy<A extends unknown[], T>(
110
+ fn: (...args: A) => Promise<T>,
111
+ opts: CachedOptions,
112
+ ): CachedFn<A, T> {
113
+ return build(fn, (args) => JSON.stringify(args), opts);
114
+ }
@@ -1,82 +1,82 @@
1
- import type { Server } from "bun";
2
-
3
- /**
4
- * The visitor's address, as the coordinator saw it, on a request it forwards
5
- * to a worker. A client's own copy of the header is dropped by the
6
- * coordinator, and a worker only accepts requests that carry its secret, so
7
- * inside a worker the value can be trusted.
8
- */
9
- export const CLIENT_ADDRESS_HEADER = "x-grimoire-client-address";
10
-
11
- const isWorker = () => Boolean(process.env.GRIMOIRE_INTERNAL_SECRET);
12
-
13
- /** Loopback and private ranges: where a reverse proxy on the same machine or network connects from. */
14
- function isPrivate(ip: string): boolean {
15
- const v4 = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
16
- if (/^(127\.|10\.|192\.168\.|169\.254\.)/.test(v4)) return true;
17
- const m = /^172\.(\d+)\./.exec(v4);
18
- if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
19
- const v6 = ip.toLowerCase();
20
- return (
21
- v6 === "::1" ||
22
- v6.startsWith("fc") ||
23
- v6.startsWith("fd") ||
24
- v6.startsWith("fe80:")
25
- );
26
- }
27
-
28
- /**
29
- * Who sent the request, given the address of the connection it came over.
30
- *
31
- * A connection from a private address is a reverse proxy (Caddy, nginx, a
32
- * load balancer, Docker's network), and the visitor is the last entry it
33
- * appended to X-Forwarded-For. Earlier entries came from the client and can
34
- * say anything. A connection from a public address is the visitor itself, so
35
- * any X-Forwarded-For it sends is ignored rather than believed.
36
- */
37
- export function resolveClientAddress(
38
- req: Request,
39
- peer: string | undefined,
40
- ): string {
41
- if (!peer) return "unknown";
42
- if (!isPrivate(peer)) return peer;
43
- const forwarded = req.headers
44
- .get("x-forwarded-for")
45
- ?.split(",")
46
- .map((s) => s.trim())
47
- .filter(Boolean);
48
- return forwarded?.at(-1) ?? req.headers.get("x-real-ip")?.trim() ?? peer;
49
- }
50
-
51
- /**
52
- * The visitor's IP address. Under `sigil start` it is what the coordinator
53
- * worked out; otherwise it is read from the connection the same way.
54
- */
55
- export function clientAddress(
56
- req: Request,
57
- server: Server<unknown> | null,
58
- ): string {
59
- if (isWorker()) {
60
- return req.headers.get(CLIENT_ADDRESS_HEADER) ?? "unknown";
61
- }
62
- return resolveClientAddress(req, server?.requestIP(req)?.address);
63
- }
64
-
65
- const lookups = new WeakMap<Request, () => string>();
66
-
67
- /** Remembers how to find the address of a request, so every context built for it can offer one. */
68
- export function trackClientAddress(
69
- req: Request,
70
- server: Server<unknown> | null,
71
- ): void {
72
- let address: string | undefined;
73
- lookups.set(req, () => {
74
- address ??= clientAddress(req, server);
75
- return address;
76
- });
77
- }
78
-
79
- /** The address of a request the server is handling. */
80
- export function clientAddressOf(req: Request): string {
81
- return lookups.get(req)?.() ?? "unknown";
82
- }
1
+ import type { Server } from "bun";
2
+
3
+ /**
4
+ * The visitor's address, as the coordinator saw it, on a request it forwards
5
+ * to a worker. A client's own copy of the header is dropped by the
6
+ * coordinator, and a worker only accepts requests that carry its secret, so
7
+ * inside a worker the value can be trusted.
8
+ */
9
+ export const CLIENT_ADDRESS_HEADER = "x-grimoire-client-address";
10
+
11
+ const isWorker = () => Boolean(process.env.GRIMOIRE_INTERNAL_SECRET);
12
+
13
+ /** Loopback and private ranges: where a reverse proxy on the same machine or network connects from. */
14
+ function isPrivate(ip: string): boolean {
15
+ const v4 = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
16
+ if (/^(127\.|10\.|192\.168\.|169\.254\.)/.test(v4)) return true;
17
+ const m = /^172\.(\d+)\./.exec(v4);
18
+ if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
19
+ const v6 = ip.toLowerCase();
20
+ return (
21
+ v6 === "::1" ||
22
+ v6.startsWith("fc") ||
23
+ v6.startsWith("fd") ||
24
+ v6.startsWith("fe80:")
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Who sent the request, given the address of the connection it came over.
30
+ *
31
+ * A connection from a private address is a reverse proxy (Caddy, nginx, a
32
+ * load balancer, Docker's network), and the visitor is the last entry it
33
+ * appended to X-Forwarded-For. Earlier entries came from the client and can
34
+ * say anything. A connection from a public address is the visitor itself, so
35
+ * any X-Forwarded-For it sends is ignored rather than believed.
36
+ */
37
+ export function resolveClientAddress(
38
+ req: Request,
39
+ peer: string | undefined,
40
+ ): string {
41
+ if (!peer) return "unknown";
42
+ if (!isPrivate(peer)) return peer;
43
+ const forwarded = req.headers
44
+ .get("x-forwarded-for")
45
+ ?.split(",")
46
+ .map((s) => s.trim())
47
+ .filter(Boolean);
48
+ return forwarded?.at(-1) ?? req.headers.get("x-real-ip")?.trim() ?? peer;
49
+ }
50
+
51
+ /**
52
+ * The visitor's IP address. Under `sigil start` it is what the coordinator
53
+ * worked out; otherwise it is read from the connection the same way.
54
+ */
55
+ export function clientAddress(
56
+ req: Request,
57
+ server: Server<unknown> | null,
58
+ ): string {
59
+ if (isWorker()) {
60
+ return req.headers.get(CLIENT_ADDRESS_HEADER) ?? "unknown";
61
+ }
62
+ return resolveClientAddress(req, server?.requestIP(req)?.address);
63
+ }
64
+
65
+ const lookups = new WeakMap<Request, () => string>();
66
+
67
+ /** Remembers how to find the address of a request, so every context built for it can offer one. */
68
+ export function trackClientAddress(
69
+ req: Request,
70
+ server: Server<unknown> | null,
71
+ ): void {
72
+ let address: string | undefined;
73
+ lookups.set(req, () => {
74
+ address ??= clientAddress(req, server);
75
+ return address;
76
+ });
77
+ }
78
+
79
+ /** The address of a request the server is handling. */
80
+ export function clientAddressOf(req: Request): string {
81
+ return lookups.get(req)?.() ?? "unknown";
82
+ }
@@ -1,63 +1,63 @@
1
- import { existsSync } from "node:fs";
2
- import { readdir, rm } from "node:fs/promises";
3
- import { join, relative } from "node:path";
4
- import { log } from "../logger/instance";
5
-
6
- const logger = log.scope("build");
7
-
8
- /** The URL the browser bundle is served under. */
9
- export const CLIENT_URL = "/__grimoire__/";
10
-
11
- /**
12
- * In dev, the one copy of @sigil-dev/runtime every browser module shares: the
13
- * client bundles and HMR-swapped modules alike. See sharedDevRuntime.
14
- */
15
- export const RUNTIME_URL = `${CLIENT_URL}runtime.js`;
16
-
17
- /**
18
- * Where the browser bundle is written: hydrate.js, the client router, their
19
- * chunks, and in dev the runtime. Generated output, so it lives in .grimoire/
20
- * with the rest of the build rather than in public/, which is the app's own.
21
- */
22
- export const clientDir = (root = process.cwd()) =>
23
- join(root, ".grimoire", "client");
24
-
25
- /** Files dev writes beside the bundle, which a dev rebuild must keep. */
26
- export const DEV_FILES = new Set(["runtime.js", "grimoire-client.js"]);
27
-
28
- /**
29
- * Empties the bundle directory before a build, so the chunks of the last one
30
- * are not left behind and served forever. Also removes public/__grimoire__,
31
- * where older versions wrote the bundle.
32
- */
33
- export async function resetClientDir(root = process.cwd()): Promise<void> {
34
- await rm(clientDir(root), { recursive: true, force: true });
35
- const legacy = join(root, "public", "__grimoire__");
36
- if (existsSync(legacy)) {
37
- await rm(legacy, { recursive: true, force: true });
38
- logger.info(
39
- "removed public/__grimoire__: the client bundle is now built into .grimoire/client. " +
40
- "Its line in .gitignore can go.",
41
- );
42
- }
43
- }
44
-
45
- /**
46
- * After a dev rebuild, deletes what that rebuild did not produce: the chunks
47
- * an edit replaced. The dev runtime files stay.
48
- */
49
- export async function pruneClientDir(
50
- outputs: readonly string[],
51
- root = process.cwd(),
52
- ): Promise<void> {
53
- const dir = clientDir(root);
54
- const keep = new Set(outputs.map((p) => relative(dir, p)));
55
- const entries = await readdir(dir, { recursive: true, withFileTypes: true });
56
- await Promise.all(
57
- entries
58
- .filter((e) => e.isFile())
59
- .map((e) => relative(dir, join(e.parentPath, e.name)))
60
- .filter((file) => !keep.has(file) && !DEV_FILES.has(file))
61
- .map((file) => rm(join(dir, file), { force: true })),
62
- );
63
- }
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, rm } from "node:fs/promises";
3
+ import { join, relative } from "node:path";
4
+ import { log } from "../logger/instance";
5
+
6
+ const logger = log.scope("build");
7
+
8
+ /** The URL the browser bundle is served under. */
9
+ export const CLIENT_URL = "/__grimoire__/";
10
+
11
+ /**
12
+ * In dev, the one copy of @sigil-dev/runtime every browser module shares: the
13
+ * client bundles and HMR-swapped modules alike. See sharedDevRuntime.
14
+ */
15
+ export const RUNTIME_URL = `${CLIENT_URL}runtime.js`;
16
+
17
+ /**
18
+ * Where the browser bundle is written: hydrate.js, the client router, their
19
+ * chunks, and in dev the runtime. Generated output, so it lives in .grimoire/
20
+ * with the rest of the build rather than in public/, which is the app's own.
21
+ */
22
+ export const clientDir = (root = process.cwd()) =>
23
+ join(root, ".grimoire", "client");
24
+
25
+ /** Files dev writes beside the bundle, which a dev rebuild must keep. */
26
+ export const DEV_FILES = new Set(["runtime.js", "grimoire-client.js"]);
27
+
28
+ /**
29
+ * Empties the bundle directory before a build, so the chunks of the last one
30
+ * are not left behind and served forever. Also removes public/__grimoire__,
31
+ * where older versions wrote the bundle.
32
+ */
33
+ export async function resetClientDir(root = process.cwd()): Promise<void> {
34
+ await rm(clientDir(root), { recursive: true, force: true });
35
+ const legacy = join(root, "public", "__grimoire__");
36
+ if (existsSync(legacy)) {
37
+ await rm(legacy, { recursive: true, force: true });
38
+ logger.info(
39
+ "removed public/__grimoire__: the client bundle is now built into .grimoire/client. " +
40
+ "Its line in .gitignore can go.",
41
+ );
42
+ }
43
+ }
44
+
45
+ /**
46
+ * After a dev rebuild, deletes what that rebuild did not produce: the chunks
47
+ * an edit replaced. The dev runtime files stay.
48
+ */
49
+ export async function pruneClientDir(
50
+ outputs: readonly string[],
51
+ root = process.cwd(),
52
+ ): Promise<void> {
53
+ const dir = clientDir(root);
54
+ const keep = new Set(outputs.map((p) => relative(dir, p)));
55
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
56
+ await Promise.all(
57
+ entries
58
+ .filter((e) => e.isFile())
59
+ .map((e) => relative(dir, join(e.parentPath, e.name)))
60
+ .filter((file) => !keep.has(file) && !DEV_FILES.has(file))
61
+ .map((file) => rm(join(dir, file), { force: true })),
62
+ );
63
+ }
@@ -1,44 +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
+ 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,10 +1,18 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import { __setStoreProvider } from "@sigil-dev/runtime";
3
-
4
- const storage = new AsyncLocalStorage<Map<symbol, unknown>>();
5
-
6
- __setStoreProvider(() => storage.getStore() ?? new Map());
7
-
8
- export function runWithContext<T>(fn: () => Promise<T>): Promise<T> {
9
- return storage.run(new Map(), fn);
10
- }
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { __setStoreProvider } from "@sigil-dev/runtime";
3
+
4
+ const storage = new AsyncLocalStorage<Map<symbol, unknown>>();
5
+
6
+ /**
7
+ * Context set outside any request (module scope, hooks `init`). It used to
8
+ * be a fresh Map per call, so such a setContext was dropped on the spot and
9
+ * the next getContext read undefined. Each request starts from a copy, so
10
+ * it sees the root and its own writes stay its own.
11
+ */
12
+ const root = new Map<symbol, unknown>();
13
+
14
+ __setStoreProvider(() => storage.getStore() ?? root);
15
+
16
+ export function runWithContext<T>(fn: () => Promise<T>): Promise<T> {
17
+ return storage.run(new Map(root), fn);
18
+ }