@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
package/src/dev/loader.ts CHANGED
@@ -1,144 +1,144 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
- import { transformSync } from "@babel/core";
6
- import sigilPlugin from "@sigil-dev/compiler/babel";
7
- import {
8
- computeHash,
9
- extractStyles,
10
- serverStyleSnippet,
11
- } from "@sigil-dev/compiler/css";
12
- import { disposeModuleEffects } from "./effect-registry";
13
- import type { DevGraph } from "./graph";
14
- import { normalizePath } from "./paths";
15
- import { absoluteAliases, isSourceFile, resolveProjectImport } from "./resolve";
16
- import { pinRuntime } from "../server/resolver";
17
-
18
- export interface DevLoaderOptions {
19
- /** GrimoireConfig.alias — prefix → project-relative directory. */
20
- aliases?: Record<string, string>;
21
- }
22
-
23
- /**
24
- * Module loader for dev SSR.
25
- *
26
- * Bun caches every module it imports for the process lifetime, so a changed
27
- * file can only be re-executed under a fresh path. Each edited module (and
28
- * each importer of one, since the graph bumps them together) is recompiled
29
- * into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
30
- * rewritten to the versioned files of its dependencies — otherwise a
31
- * recompiled page would keep importing the cached copy of the component that
32
- * was just edited.
33
- */
34
- export function makeDevLoader(
35
- graph: DevGraph,
36
- projectRoot: string,
37
- options: DevLoaderOptions = {},
38
- ) {
39
- const cacheDir = join(projectRoot, ".grimoire/dev-cache");
40
- const aliases = options.aliases ?? {};
41
- // a previous session's cache cannot be trusted: same path, same version
42
- // number, different source
43
- rmSync(cacheDir, { recursive: true, force: true });
44
- mkdirSync(cacheDir, { recursive: true });
45
-
46
- /** Cache files this process has already written, by path. */
47
- const written = new Set<string>();
48
-
49
- const materialize = async (filePath: string): Promise<string> => {
50
- const version = graph.get(filePath)?.version ?? 0;
51
- // untouched since startup: the SSR plugin handles the source directly
52
- if (version === 0) return pathToFileURL(filePath).href;
53
-
54
- const key = createHash("md5")
55
- .update(normalizePath(filePath))
56
- .digest("hex")
57
- .slice(0, 8);
58
- const cachePath = join(cacheDir, `${key}_v${version}.js`);
59
- const href = pathToFileURL(cachePath).href;
60
- // (file, version) is immutable within a session; import cycles reach
61
- // the same deterministic path, and the outer call writes it
62
- if (written.has(cachePath)) return href;
63
- written.add(cachePath);
64
-
65
- try {
66
- const source = await Bun.file(filePath).text();
67
- // scoped <style> blocks come out before parsing (CSS braces would
68
- // read as JSX expressions); their CSS is registered for the
69
- // renderer, which puts it in <head>
70
- const styles = extractStyles(source, computeHash(filePath), filePath);
71
- const babelResult = transformSync(styles.code, {
72
- configFile: false,
73
- babelrc: false,
74
- parserOpts: { plugins: ["typescript", "jsx"] },
75
- plugins: [
76
- [
77
- sigilPlugin,
78
- {
79
- mode: "ssr",
80
- hash: styles.css ? computeHash(filePath) : undefined,
81
- aliases: absoluteAliases(projectRoot, aliases),
82
- },
83
- ],
84
- ],
85
- filename: filePath,
86
- });
87
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
88
- let compiled = transpiler.transformSync(babelResult?.code ?? "");
89
- if (styles.css) {
90
- compiled =
91
- serverStyleSnippet(computeHash(filePath), styles.css) + compiled;
92
- }
93
- compiled = pinRuntime(compiled);
94
- compiled = await rewriteSpecifiers(compiled, async (specifier) => {
95
- const resolved = resolveProjectImport(
96
- specifier,
97
- filePath,
98
- projectRoot,
99
- aliases,
100
- );
101
- // externals keep their specifier: node_modules resolution walks
102
- // up from the cache dir to the project root all the same
103
- if (!resolved || !isSourceFile(resolved)) return null;
104
- return await materialize(resolved);
105
- });
106
- mkdirSync(cacheDir, { recursive: true });
107
- writeFileSync(cachePath, compiled);
108
- } catch (e) {
109
- // let the next request retry instead of importing a half-written file
110
- written.delete(cachePath);
111
- throw e;
112
- }
113
- return href;
114
- };
115
-
116
- return async function devLoadModule(filePath: string): Promise<unknown> {
117
- disposeModuleEffects(normalizePath(filePath));
118
- return import(await materialize(filePath));
119
- };
120
- }
121
-
122
- const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
123
-
124
- /** Replace every import specifier for which `resolve` returns a new one. */
125
- async function rewriteSpecifiers(
126
- code: string,
127
- resolve: (specifier: string) => Promise<string | null>,
128
- ): Promise<string> {
129
- const replacements = new Map<string, string>();
130
- for (const match of code.matchAll(SPEC_RE)) {
131
- const specifier = match[3]!;
132
- if (replacements.has(specifier)) continue;
133
- const next = await resolve(specifier);
134
- if (next) replacements.set(specifier, next);
135
- }
136
- if (replacements.size === 0) return code;
137
- return code.replace(
138
- SPEC_RE,
139
- (match, keyword: string, quote: string, specifier: string) => {
140
- const next = replacements.get(specifier);
141
- return next ? `${keyword}${quote}${next}${quote}` : match;
142
- },
143
- );
144
- }
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { transformSync } from "@babel/core";
6
+ import sigilPlugin from "@sigil-dev/compiler/babel";
7
+ import {
8
+ computeHash,
9
+ extractStyles,
10
+ serverStyleSnippet,
11
+ } from "@sigil-dev/compiler/css";
12
+ import { pinRuntime } from "../server/resolver";
13
+ import { disposeModuleEffects } from "./effect-registry";
14
+ import type { DevGraph } from "./graph";
15
+ import { normalizePath } from "./paths";
16
+ import { absoluteAliases, isSourceFile, resolveProjectImport } from "./resolve";
17
+
18
+ export interface DevLoaderOptions {
19
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
20
+ aliases?: Record<string, string>;
21
+ }
22
+
23
+ /**
24
+ * Module loader for dev SSR.
25
+ *
26
+ * Bun caches every module it imports for the process lifetime, so a changed
27
+ * file can only be re-executed under a fresh path. Each edited module (and
28
+ * each importer of one, since the graph bumps them together) is recompiled
29
+ * into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
30
+ * rewritten to the versioned files of its dependencies — otherwise a
31
+ * recompiled page would keep importing the cached copy of the component that
32
+ * was just edited.
33
+ */
34
+ export function makeDevLoader(
35
+ graph: DevGraph,
36
+ projectRoot: string,
37
+ options: DevLoaderOptions = {},
38
+ ) {
39
+ const cacheDir = join(projectRoot, ".grimoire/dev-cache");
40
+ const aliases = options.aliases ?? {};
41
+ // a previous session's cache cannot be trusted: same path, same version
42
+ // number, different source
43
+ rmSync(cacheDir, { recursive: true, force: true });
44
+ mkdirSync(cacheDir, { recursive: true });
45
+
46
+ /** Cache files this process has already written, by path. */
47
+ const written = new Set<string>();
48
+
49
+ const materialize = async (filePath: string): Promise<string> => {
50
+ const version = graph.get(filePath)?.version ?? 0;
51
+ // untouched since startup: the SSR plugin handles the source directly
52
+ if (version === 0) return pathToFileURL(filePath).href;
53
+
54
+ const key = createHash("md5")
55
+ .update(normalizePath(filePath))
56
+ .digest("hex")
57
+ .slice(0, 8);
58
+ const cachePath = join(cacheDir, `${key}_v${version}.js`);
59
+ const href = pathToFileURL(cachePath).href;
60
+ // (file, version) is immutable within a session; import cycles reach
61
+ // the same deterministic path, and the outer call writes it
62
+ if (written.has(cachePath)) return href;
63
+ written.add(cachePath);
64
+
65
+ try {
66
+ const source = await Bun.file(filePath).text();
67
+ // scoped <style> blocks come out before parsing (CSS braces would
68
+ // read as JSX expressions); their CSS is registered for the
69
+ // renderer, which puts it in <head>
70
+ const styles = extractStyles(source, computeHash(filePath), filePath);
71
+ const babelResult = transformSync(styles.code, {
72
+ configFile: false,
73
+ babelrc: false,
74
+ parserOpts: { plugins: ["typescript", "jsx"] },
75
+ plugins: [
76
+ [
77
+ sigilPlugin,
78
+ {
79
+ mode: "ssr",
80
+ hash: styles.css ? computeHash(filePath) : undefined,
81
+ aliases: absoluteAliases(projectRoot, aliases),
82
+ },
83
+ ],
84
+ ],
85
+ filename: filePath,
86
+ });
87
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
88
+ let compiled = transpiler.transformSync(babelResult?.code ?? "");
89
+ if (styles.css) {
90
+ compiled =
91
+ serverStyleSnippet(computeHash(filePath), styles.css) + compiled;
92
+ }
93
+ compiled = pinRuntime(compiled);
94
+ compiled = await rewriteSpecifiers(compiled, async (specifier) => {
95
+ const resolved = resolveProjectImport(
96
+ specifier,
97
+ filePath,
98
+ projectRoot,
99
+ aliases,
100
+ );
101
+ // externals keep their specifier: node_modules resolution walks
102
+ // up from the cache dir to the project root all the same
103
+ if (!resolved || !isSourceFile(resolved)) return null;
104
+ return await materialize(resolved);
105
+ });
106
+ mkdirSync(cacheDir, { recursive: true });
107
+ writeFileSync(cachePath, compiled);
108
+ } catch (e) {
109
+ // let the next request retry instead of importing a half-written file
110
+ written.delete(cachePath);
111
+ throw e;
112
+ }
113
+ return href;
114
+ };
115
+
116
+ return async function devLoadModule(filePath: string): Promise<unknown> {
117
+ disposeModuleEffects(normalizePath(filePath));
118
+ return import(await materialize(filePath));
119
+ };
120
+ }
121
+
122
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
123
+
124
+ /** Replace every import specifier for which `resolve` returns a new one. */
125
+ async function rewriteSpecifiers(
126
+ code: string,
127
+ resolve: (specifier: string) => Promise<string | null>,
128
+ ): Promise<string> {
129
+ const replacements = new Map<string, string>();
130
+ for (const match of code.matchAll(SPEC_RE)) {
131
+ const specifier = match[3]!;
132
+ if (replacements.has(specifier)) continue;
133
+ const next = await resolve(specifier);
134
+ if (next) replacements.set(specifier, next);
135
+ }
136
+ if (replacements.size === 0) return code;
137
+ return code.replace(
138
+ SPEC_RE,
139
+ (match, keyword: string, quote: string, specifier: string) => {
140
+ const next = replacements.get(specifier);
141
+ return next ? `${keyword}${quote}${next}${quote}` : match;
142
+ },
143
+ );
144
+ }
@@ -13,9 +13,11 @@ export async function ensureRuntimeBundle(projectRoot: string): Promise<void> {
13
13
  // about whether @sigil-dev/runtime changed under it. It takes a few ms.
14
14
  logger.debug("bundling runtime...");
15
15
  const result = await Bun.build({
16
- entrypoints: [
17
- join(projectRoot, "node_modules/@sigil-dev/runtime/index.ts"),
18
- ],
16
+ // grimoire's own runtime, the copy the server pins compiled code to.
17
+ // Reading it from the project's node_modules required every app to
18
+ // install the runtime itself, and a different version there meant the
19
+ // browser and the server ran two runtimes.
20
+ entrypoints: [Bun.resolveSync("@sigil-dev/runtime", import.meta.dir)],
19
21
  outdir: outDir,
20
22
  naming: "runtime.js",
21
23
  target: "browser",
@@ -0,0 +1,46 @@
1
+ /** A time unit in a duration string. */
2
+ type Unit = "ms" | "s" | "m" | "h" | "d";
3
+ type Part = `${number}${Unit}`;
4
+
5
+ /**
6
+ * Milliseconds, or a string of up to three parts: `"30s"`, `"5m"`,
7
+ * `"1h 30m"`, `"1d 2h 30m"`. A typo is a compile error.
8
+ */
9
+ export type Duration =
10
+ | number
11
+ | Part
12
+ | `${Part} ${Part}`
13
+ | `${Part} ${Part} ${Part}`;
14
+
15
+ const UNIT_MS: Record<Unit, number> = {
16
+ ms: 1,
17
+ s: 1_000,
18
+ m: 60_000,
19
+ h: 3_600_000,
20
+ d: 86_400_000,
21
+ };
22
+
23
+ /**
24
+ * A duration in milliseconds. Throws, naming the input, on anything it
25
+ * cannot read; `who` starts the message ("plugin-jobs: ...").
26
+ */
27
+ export function ms(duration: Duration, who = "sigil"): number {
28
+ if (typeof duration === "number") {
29
+ if (!Number.isFinite(duration) || duration < 0) {
30
+ throw new Error(`${who}: ${duration} is not a duration`);
31
+ }
32
+ return duration;
33
+ }
34
+ const parts = duration.trim().split(/\s+/);
35
+ let total = 0;
36
+ for (const part of parts) {
37
+ const m = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(part);
38
+ if (!m) {
39
+ throw new Error(
40
+ `${who}: cannot read "${duration}" as a duration. Use parts like "30s", "5m", "1h 30m", or milliseconds.`,
41
+ );
42
+ }
43
+ total += Number(m[1]) * UNIT_MS[m[2] as Unit];
44
+ }
45
+ return total;
46
+ }
@@ -1,62 +1,62 @@
1
- import { join } from "node:path";
2
- import { filterPrivate, filterPublic } from "./index";
3
-
4
- /**
5
- * Source for the `$env/*` modules.
6
- *
7
- * - `$env/static/public` and `$env/static/private`: values read when the
8
- * module is built (the browser build, or server start), as `env` and as
9
- * one named export per variable.
10
- * - `$env/dynamic/public`: `env`, read live on the server; in the browser,
11
- * the values the server rendered into the page (`__grimoire_env__`).
12
- * - `$env/dynamic/private`: `env`, every variable, read live.
13
- *
14
- * `env` reads a missing variable as "".
15
- *
16
- * The private modules are server-only: importing one into browser code
17
- * fails the build rather than shipping secrets.
18
- */
19
- export const ENV_MODULE = /^\$env\/(static|dynamic)\/(public|private)$/;
20
-
21
- const IDENT = /^[A-Za-z_$][\w$]*$/;
22
-
23
- function snapshot(values: Record<string, string>): string {
24
- const names = Object.keys(values).filter((k) => IDENT.test(k));
25
- return [
26
- `export const env = ${JSON.stringify(values)};`,
27
- ...names.map((k) => `export const ${k} = env[${JSON.stringify(k)}];`),
28
- ].join("\n");
29
- }
30
-
31
- export function envModuleSource(
32
- specifier: string,
33
- target: "server" | "browser",
34
- ): string {
35
- const m = ENV_MODULE.exec(specifier);
36
- if (!m) throw new Error(`unknown env module ${specifier}`);
37
- const [, kind, visibility] = m;
38
- if (visibility === "private" && target === "browser") {
39
- throw new Error(
40
- `${specifier} holds server secrets and can't be imported into browser code. Import it from a .server.ts file, or use $env/${kind}/public for PUBLIC_ variables.`,
41
- );
42
- }
43
- if (kind === "static") {
44
- return snapshot(
45
- visibility === "public"
46
- ? filterPublic(process.env)
47
- : filterPrivate(process.env),
48
- );
49
- }
50
- if (target === "browser") {
51
- // like the server's: a missing PUBLIC_ variable reads as ""
52
- return `const values = globalThis.__grimoire_env__ ?? {};
53
- export const env = new Proxy(values, {
54
- get: (t, k) => (typeof k === "string" ? (t[k] ?? "") : undefined),
55
- });`;
56
- }
57
- const file = join(
58
- import.meta.dir,
59
- visibility === "public" ? "dynamic-public.ts" : "dynamic-private.ts",
60
- );
61
- return `export { env } from ${JSON.stringify(file)};`;
62
- }
1
+ import { join } from "node:path";
2
+ import { filterPrivate, filterPublic } from "./index";
3
+
4
+ /**
5
+ * Source for the `$env/*` modules.
6
+ *
7
+ * - `$env/static/public` and `$env/static/private`: values read when the
8
+ * module is built (the browser build, or server start), as `env` and as
9
+ * one named export per variable.
10
+ * - `$env/dynamic/public`: `env`, read live on the server; in the browser,
11
+ * the values the server rendered into the page (`__grimoire_env__`).
12
+ * - `$env/dynamic/private`: `env`, every variable, read live.
13
+ *
14
+ * `env` reads a missing variable as "".
15
+ *
16
+ * The private modules are server-only: importing one into browser code
17
+ * fails the build rather than shipping secrets.
18
+ */
19
+ export const ENV_MODULE = /^\$env\/(static|dynamic)\/(public|private)$/;
20
+
21
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
22
+
23
+ function snapshot(values: Record<string, string>): string {
24
+ const names = Object.keys(values).filter((k) => IDENT.test(k));
25
+ return [
26
+ `export const env = ${JSON.stringify(values)};`,
27
+ ...names.map((k) => `export const ${k} = env[${JSON.stringify(k)}];`),
28
+ ].join("\n");
29
+ }
30
+
31
+ export function envModuleSource(
32
+ specifier: string,
33
+ target: "server" | "browser",
34
+ ): string {
35
+ const m = ENV_MODULE.exec(specifier);
36
+ if (!m) throw new Error(`unknown env module ${specifier}`);
37
+ const [, kind, visibility] = m;
38
+ if (visibility === "private" && target === "browser") {
39
+ throw new Error(
40
+ `${specifier} holds server secrets and can't be imported into browser code. Import it from a .server.ts file, or use $env/${kind}/public for PUBLIC_ variables.`,
41
+ );
42
+ }
43
+ if (kind === "static") {
44
+ return snapshot(
45
+ visibility === "public"
46
+ ? filterPublic(process.env)
47
+ : filterPrivate(process.env),
48
+ );
49
+ }
50
+ if (target === "browser") {
51
+ // like the server's: a missing PUBLIC_ variable reads as ""
52
+ return `const values = globalThis.__grimoire_env__ ?? {};
53
+ export const env = new Proxy(values, {
54
+ get: (t, k) => (typeof k === "string" ? (t[k] ?? "") : undefined),
55
+ });`;
56
+ }
57
+ const file = join(
58
+ import.meta.dir,
59
+ visibility === "public" ? "dynamic-public.ts" : "dynamic-private.ts",
60
+ );
61
+ return `export { env } from ${JSON.stringify(file)};`;
62
+ }
@@ -1,42 +1,42 @@
1
- import type { GrimoireConfig } from "../types";
2
-
3
- /**
4
- * Names that must be set before a server starts, from `env.required` in the
5
- * config and from each plugin's `requiredEnv`.
6
- *
7
- * `$env/*` reads a missing variable as "", which turns an unset secret into a
8
- * confusing failure somewhere far from the cause. Checking at boot moves the
9
- * failure to the one place that can name the variable.
10
- *
11
- * Empty counts as missing: `FOO=` in a compose file is how a variable ends up
12
- * "set" and useless.
13
- */
14
- export function missingEnv(
15
- config: Pick<GrimoireConfig, "env" | "plugins">,
16
- env: Record<string, string | undefined> = process.env,
17
- ): { name: string; by: string }[] {
18
- const wanted = new Map<string, string>();
19
- for (const name of config.env?.required ?? [])
20
- wanted.set(name, "sigil.config.ts");
21
- for (const plugin of config.plugins ?? []) {
22
- for (const name of plugin.requiredEnv ?? []) {
23
- if (!wanted.has(name)) wanted.set(name, `plugin "${plugin.name}"`);
24
- }
25
- }
26
- return [...wanted]
27
- .filter(([name]) => !env[name])
28
- .map(([name, by]) => ({ name, by }));
29
- }
30
-
31
- /** Throws one error listing every missing variable, so a deploy is fixed in one pass. */
32
- export function assertRequiredEnv(
33
- config: Pick<GrimoireConfig, "env" | "plugins">,
34
- env: Record<string, string | undefined> = process.env,
35
- ): void {
36
- const missing = missingEnv(config, env);
37
- if (!missing.length) return;
38
- throw new Error(
39
- `Missing required environment variable${missing.length > 1 ? "s" : ""}:\n` +
40
- missing.map((m) => ` ${m.name} (required by ${m.by})`).join("\n"),
41
- );
42
- }
1
+ import type { GrimoireConfig } from "../types";
2
+
3
+ /**
4
+ * Names that must be set before a server starts, from `env.required` in the
5
+ * config and from each plugin's `requiredEnv`.
6
+ *
7
+ * `$env/*` reads a missing variable as "", which turns an unset secret into a
8
+ * confusing failure somewhere far from the cause. Checking at boot moves the
9
+ * failure to the one place that can name the variable.
10
+ *
11
+ * Empty counts as missing: `FOO=` in a compose file is how a variable ends up
12
+ * "set" and useless.
13
+ */
14
+ export function missingEnv(
15
+ config: Pick<GrimoireConfig, "env" | "plugins">,
16
+ env: Record<string, string | undefined> = process.env,
17
+ ): { name: string; by: string }[] {
18
+ const wanted = new Map<string, string>();
19
+ for (const name of config.env?.required ?? [])
20
+ wanted.set(name, "sigil.config.ts");
21
+ for (const plugin of config.plugins ?? []) {
22
+ for (const name of plugin.requiredEnv ?? []) {
23
+ if (!wanted.has(name)) wanted.set(name, `plugin "${plugin.name}"`);
24
+ }
25
+ }
26
+ return [...wanted]
27
+ .filter(([name]) => !env[name])
28
+ .map(([name, by]) => ({ name, by }));
29
+ }
30
+
31
+ /** Throws one error listing every missing variable, so a deploy is fixed in one pass. */
32
+ export function assertRequiredEnv(
33
+ config: Pick<GrimoireConfig, "env" | "plugins">,
34
+ env: Record<string, string | undefined> = process.env,
35
+ ): void {
36
+ const missing = missingEnv(config, env);
37
+ if (!missing.length) return;
38
+ throw new Error(
39
+ `Missing required environment variable${missing.length > 1 ? "s" : ""}:\n` +
40
+ missing.map((m) => ` ${m.name} (required by ${m.by})`).join("\n"),
41
+ );
42
+ }