@sigil-dev/grimoire 0.9.21 → 0.9.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -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 +101 -101
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -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 +1138 -1018
  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 +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
package/test/warm.test.ts CHANGED
@@ -1,96 +1,96 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { preloadModules, startWarming } from "../src/server/warm.ts";
3
-
4
- describe("preloadModules", () => {
5
- test("imports each file once and reports failures without throwing", async () => {
6
- const seen: string[] = [];
7
- const warnings: string[] = [];
8
- const loaded = await preloadModules(
9
- ["/a.tsx", "/b.tsx", "/a.tsx", "/bad.tsx"],
10
- async (f) => {
11
- seen.push(f);
12
- if (f === "/bad.tsx") throw new Error("boom");
13
- },
14
- (msg) => warnings.push(msg),
15
- );
16
- expect(loaded).toBe(2);
17
- expect(seen.sort()).toEqual(["/a.tsx", "/b.tsx", "/bad.tsx"]);
18
- expect(warnings).toEqual(["could not preload /bad.tsx:"]);
19
- });
20
- });
21
-
22
- describe("startWarming", () => {
23
- test("requests paths in order, with the given headers, and drains bodies", async () => {
24
- const calls: Array<{ path: string; header: string | null }> = [];
25
- let drained = 0;
26
- const warmer = startWarming({
27
- paths: ["/one", "/two"],
28
- origin: "http://127.0.0.1:1234",
29
- headers: { "x-grimoire-internal": "s3cret" },
30
- handle: async (req) => {
31
- calls.push({
32
- path: new URL(req.url).pathname,
33
- header: req.headers.get("x-grimoire-internal"),
34
- });
35
- const stream = new ReadableStream({
36
- pull(c) {
37
- drained++;
38
- c.enqueue(new TextEncoder().encode("x"));
39
- c.close();
40
- },
41
- });
42
- return new Response(stream);
43
- },
44
- log: () => {},
45
- });
46
- await warmer.firstPass;
47
- warmer.stop();
48
- expect(calls).toEqual([
49
- { path: "/one", header: "s3cret" },
50
- { path: "/two", header: "s3cret" },
51
- ]);
52
- expect(drained).toBe(2);
53
- });
54
-
55
- test("a failing path is logged and does not stop the rest", async () => {
56
- const logs: string[] = [];
57
- const paths: string[] = [];
58
- const warmer = startWarming({
59
- paths: ["/bad", "/good"],
60
- origin: "http://x",
61
- handle: async (req) => {
62
- const p = new URL(req.url).pathname;
63
- paths.push(p);
64
- if (p === "/bad") throw new Error("nope");
65
- return new Response("ok");
66
- },
67
- log: (m) => logs.push(m),
68
- });
69
- await warmer.firstPass;
70
- warmer.stop();
71
- expect(paths).toEqual(["/bad", "/good"]);
72
- expect(logs[0]).toContain("/bad failed: nope");
73
- expect(logs[1]).toContain("warmed /good (200)");
74
- });
75
-
76
- test("every repeats the pass until stopped", async () => {
77
- let n = 0;
78
- const warmer = startWarming({
79
- paths: ["/p"],
80
- every: 20,
81
- origin: "http://x",
82
- handle: async () => {
83
- n++;
84
- return new Response("ok");
85
- },
86
- log: () => {},
87
- });
88
- await warmer.firstPass;
89
- await Bun.sleep(90);
90
- warmer.stop();
91
- const seen = n;
92
- expect(seen).toBeGreaterThanOrEqual(3);
93
- await Bun.sleep(60);
94
- expect(n).toBe(seen);
95
- });
96
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { preloadModules, startWarming } from "../src/server/warm.ts";
3
+
4
+ describe("preloadModules", () => {
5
+ test("imports each file once and reports failures without throwing", async () => {
6
+ const seen: string[] = [];
7
+ const warnings: string[] = [];
8
+ const loaded = await preloadModules(
9
+ ["/a.tsx", "/b.tsx", "/a.tsx", "/bad.tsx"],
10
+ async (f) => {
11
+ seen.push(f);
12
+ if (f === "/bad.tsx") throw new Error("boom");
13
+ },
14
+ (msg) => warnings.push(msg),
15
+ );
16
+ expect(loaded).toBe(2);
17
+ expect(seen.sort()).toEqual(["/a.tsx", "/b.tsx", "/bad.tsx"]);
18
+ expect(warnings).toEqual(["could not preload /bad.tsx:"]);
19
+ });
20
+ });
21
+
22
+ describe("startWarming", () => {
23
+ test("requests paths in order, with the given headers, and drains bodies", async () => {
24
+ const calls: Array<{ path: string; header: string | null }> = [];
25
+ let drained = 0;
26
+ const warmer = startWarming({
27
+ paths: ["/one", "/two"],
28
+ origin: "http://127.0.0.1:1234",
29
+ headers: { "x-grimoire-internal": "s3cret" },
30
+ handle: async (req) => {
31
+ calls.push({
32
+ path: new URL(req.url).pathname,
33
+ header: req.headers.get("x-grimoire-internal"),
34
+ });
35
+ const stream = new ReadableStream({
36
+ pull(c) {
37
+ drained++;
38
+ c.enqueue(new TextEncoder().encode("x"));
39
+ c.close();
40
+ },
41
+ });
42
+ return new Response(stream);
43
+ },
44
+ log: () => {},
45
+ });
46
+ await warmer.firstPass;
47
+ warmer.stop();
48
+ expect(calls).toEqual([
49
+ { path: "/one", header: "s3cret" },
50
+ { path: "/two", header: "s3cret" },
51
+ ]);
52
+ expect(drained).toBe(2);
53
+ });
54
+
55
+ test("a failing path is logged and does not stop the rest", async () => {
56
+ const logs: string[] = [];
57
+ const paths: string[] = [];
58
+ const warmer = startWarming({
59
+ paths: ["/bad", "/good"],
60
+ origin: "http://x",
61
+ handle: async (req) => {
62
+ const p = new URL(req.url).pathname;
63
+ paths.push(p);
64
+ if (p === "/bad") throw new Error("nope");
65
+ return new Response("ok");
66
+ },
67
+ log: (m) => logs.push(m),
68
+ });
69
+ await warmer.firstPass;
70
+ warmer.stop();
71
+ expect(paths).toEqual(["/bad", "/good"]);
72
+ expect(logs[0]).toContain("/bad failed: nope");
73
+ expect(logs[1]).toContain("warmed /good (200)");
74
+ });
75
+
76
+ test("every repeats the pass until stopped", async () => {
77
+ let n = 0;
78
+ const warmer = startWarming({
79
+ paths: ["/p"],
80
+ every: 20,
81
+ origin: "http://x",
82
+ handle: async () => {
83
+ n++;
84
+ return new Response("ok");
85
+ },
86
+ log: () => {},
87
+ });
88
+ await warmer.firstPass;
89
+ await Bun.sleep(90);
90
+ warmer.stop();
91
+ const seen = n;
92
+ expect(seen).toBeGreaterThanOrEqual(3);
93
+ await Bun.sleep(60);
94
+ expect(n).toBe(seen);
95
+ });
96
+ });
@@ -1,59 +1,59 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { workerContext } from "../src/types.ts";
3
-
4
- /**
5
- * `workers` exists so a per-worker resource can divide a global budget.
6
- * A wrong value here is not a crash, it is a connection pool quietly
7
- * sized N-times too large — which shows up as a database refusing
8
- * connections in production and nowhere else.
9
- */
10
- describe("workerContext", () => {
11
- test("reads index and count from a coordinator spawn", () => {
12
- expect(
13
- workerContext({
14
- GRIMOIRE_WORKER_INDEX: "3",
15
- GRIMOIRE_WORKER_COUNT: "4",
16
- GRIMOIRE_MODE: "production",
17
- }),
18
- ).toEqual({ workerId: 2, workers: 4, dev: false });
19
- });
20
-
21
- test("is zero-based", () => {
22
- // The coordinator writes 1-based indices, so index "1" is the first
23
- // worker and must read back as 0, not 1.
24
- expect(workerContext({ GRIMOIRE_WORKER_INDEX: "1" }).workerId).toBe(0);
25
- });
26
-
27
- test("dev mode is read from GRIMOIRE_MODE", () => {
28
- expect(workerContext({ GRIMOIRE_MODE: "development" }).dev).toBe(true);
29
- expect(workerContext({ GRIMOIRE_MODE: "production" }).dev).toBe(false);
30
- });
31
-
32
- test("no coordinator means one worker of one", () => {
33
- // `sigil dev` and a plain single-process start set no vars. That is a
34
- // real situation, not a failure, and it has to resolve to something
35
- // usable.
36
- expect(workerContext({})).toEqual({
37
- workerId: 0,
38
- workers: 1,
39
- dev: false,
40
- });
41
- });
42
-
43
- test("workers is never zero", () => {
44
- // The whole point of the number is to divide by it. Zero would make
45
- // `maxTotal / workers` Infinity.
46
- expect(workerContext({ GRIMOIRE_WORKER_COUNT: "0" }).workers).toBe(1);
47
- expect(workerContext({ GRIMOIRE_WORKER_COUNT: "garbage" }).workers).toBe(1);
48
- expect(workerContext({ GRIMOIRE_WORKER_COUNT: "-4" }).workers).toBe(1);
49
- });
50
-
51
- test("a budget divides evenly", () => {
52
- // The arithmetic the field exists for.
53
- const ctx = workerContext({
54
- GRIMOIRE_WORKER_INDEX: "1",
55
- GRIMOIRE_WORKER_COUNT: "4",
56
- });
57
- expect(Math.ceil(20 / ctx.workers)).toBe(5);
58
- });
59
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { workerContext } from "../src/types.ts";
3
+
4
+ /**
5
+ * `workers` exists so a per-worker resource can divide a global budget.
6
+ * A wrong value here is not a crash, it is a connection pool quietly
7
+ * sized N-times too large — which shows up as a database refusing
8
+ * connections in production and nowhere else.
9
+ */
10
+ describe("workerContext", () => {
11
+ test("reads index and count from a coordinator spawn", () => {
12
+ expect(
13
+ workerContext({
14
+ GRIMOIRE_WORKER_INDEX: "3",
15
+ GRIMOIRE_WORKER_COUNT: "4",
16
+ GRIMOIRE_MODE: "production",
17
+ }),
18
+ ).toEqual({ workerId: 2, workers: 4, dev: false });
19
+ });
20
+
21
+ test("is zero-based", () => {
22
+ // The coordinator writes 1-based indices, so index "1" is the first
23
+ // worker and must read back as 0, not 1.
24
+ expect(workerContext({ GRIMOIRE_WORKER_INDEX: "1" }).workerId).toBe(0);
25
+ });
26
+
27
+ test("dev mode is read from GRIMOIRE_MODE", () => {
28
+ expect(workerContext({ GRIMOIRE_MODE: "development" }).dev).toBe(true);
29
+ expect(workerContext({ GRIMOIRE_MODE: "production" }).dev).toBe(false);
30
+ });
31
+
32
+ test("no coordinator means one worker of one", () => {
33
+ // `sigil dev` and a plain single-process start set no vars. That is a
34
+ // real situation, not a failure, and it has to resolve to something
35
+ // usable.
36
+ expect(workerContext({})).toEqual({
37
+ workerId: 0,
38
+ workers: 1,
39
+ dev: false,
40
+ });
41
+ });
42
+
43
+ test("workers is never zero", () => {
44
+ // The whole point of the number is to divide by it. Zero would make
45
+ // `maxTotal / workers` Infinity.
46
+ expect(workerContext({ GRIMOIRE_WORKER_COUNT: "0" }).workers).toBe(1);
47
+ expect(workerContext({ GRIMOIRE_WORKER_COUNT: "garbage" }).workers).toBe(1);
48
+ expect(workerContext({ GRIMOIRE_WORKER_COUNT: "-4" }).workers).toBe(1);
49
+ });
50
+
51
+ test("a budget divides evenly", () => {
52
+ // The arithmetic the field exists for.
53
+ const ctx = workerContext({
54
+ GRIMOIRE_WORKER_INDEX: "1",
55
+ GRIMOIRE_WORKER_COUNT: "4",
56
+ });
57
+ expect(Math.ceil(20 / ctx.workers)).toBe(5);
58
+ });
59
+ });
@@ -1,146 +1,149 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { execFileSync } from "node:child_process";
3
- import { existsSync, readFileSync, readdirSync } from "node:fs";
4
- import { dirname, join, normalize, relative } from "node:path";
5
-
6
- /**
7
- * A packed tarball must contain every file its entry points import.
8
- *
9
- * `files` in package.json is a list someone types, and a module added later
10
- * is not on it. Nothing in the workspace notices, because every import
11
- * resolves against the source tree; only the installed tarball is missing
12
- * the file, and it fails at boot in the app.
13
- *
14
- * Not hypothetical, twice: plugin-sql shipped without `database.ts` and
15
- * `fragment.ts`, which `index.ts` imports, and plugin-jobs shipped without
16
- * `store.ts`, `store-bun.ts` and `store-drizzle.ts`.
17
- */
18
-
19
- const ROOT = new URL("../../../", import.meta.url).pathname;
20
-
21
- interface Manifest {
22
- name?: string;
23
- version?: string;
24
- private?: boolean;
25
- module?: string;
26
- main?: string;
27
- exports?: unknown;
28
- }
29
-
30
- function shipped(): { dir: string; manifest: Manifest }[] {
31
- return readdirSync(join(ROOT, "packages"), { withFileTypes: true })
32
- .filter((e) => e.isDirectory())
33
- .flatMap((e) => {
34
- const file = join(ROOT, "packages", e.name, "package.json");
35
- if (!existsSync(file)) return [];
36
- const manifest = JSON.parse(readFileSync(file, "utf8")) as Manifest;
37
- return [{ dir: join(ROOT, "packages", e.name), manifest }];
38
- })
39
- .filter(
40
- ({ manifest }) =>
41
- manifest.name?.startsWith("@sigil-dev/") &&
42
- typeof manifest.version === "string" &&
43
- !manifest.private,
44
- );
45
- }
46
-
47
- /** Every path string reachable in an `exports` map. */
48
- function exportTargets(exp: unknown): string[] {
49
- if (typeof exp === "string") return [exp];
50
- if (exp && typeof exp === "object") {
51
- return Object.values(exp).flatMap(exportTargets);
52
- }
53
- return [];
54
- }
55
-
56
- const SOURCE = /\.(ts|tsx|js|mjs)$/;
57
- const IMPORT =
58
- /(?:^|[\s;])(?:import|export)\s[^'"]*?from\s*["'](\.{1,2}\/[^"']+)["']|import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)|^import\s+["'](\.{1,2}\/[^"']+)["']/gm;
59
-
60
- /** Source without comments, so an import shown in a doc example is not one. */
61
- const code = (file: string): string =>
62
- readFileSync(file, "utf8")
63
- .replace(/\/\*[\s\S]*?\*\//g, "")
64
- .replace(/^\s*\/\/.*$/gm, "");
65
-
66
- function resolveImport(from: string, spec: string): string | null {
67
- const base = normalize(join(dirname(from), spec));
68
- // TypeScript's `./x.js` for `./x.ts`.
69
- const ts = base.replace(/\.js$/, ".ts");
70
- for (const candidate of [base, ts, `${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
71
- if (existsSync(candidate) && SOURCE.test(candidate)) return candidate;
72
- }
73
- return null;
74
- }
75
-
76
- /** The files the entry points reach through relative imports. */
77
- function reachable(dir: string, entries: string[]): Set<string> {
78
- const seen = new Set<string>();
79
- const queue = entries.map((e) => normalize(join(dir, e))).filter((f) => SOURCE.test(f));
80
- while (queue.length) {
81
- const file = queue.pop()!;
82
- if (seen.has(file) || !existsSync(file)) continue;
83
- seen.add(file);
84
- for (const m of code(file).matchAll(IMPORT)) {
85
- const spec = m[1] ?? m[2] ?? m[3];
86
- if (!spec) continue;
87
- const target = resolveImport(file, spec);
88
- // Only files inside the package: a relative import that escapes
89
- // it is a different bug, and one the pack cannot fix.
90
- if (target && !relative(dir, target).startsWith("..")) queue.push(target);
91
- }
92
- }
93
- return seen;
94
- }
95
-
96
- function packedFiles(dir: string): Set<string> {
97
- const out = execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], {
98
- cwd: dir,
99
- encoding: "utf8",
100
- stdio: ["ignore", "pipe", "ignore"],
101
- });
102
- const [report] = JSON.parse(out) as Array<{ files: Array<{ path: string }> }>;
103
- return new Set(report!.files.map((f) => normalize(join(dir, f.path))));
104
- }
105
-
106
- describe("workspace files", () => {
107
- test("every file an entry point imports is in the tarball", () => {
108
- const missing: string[] = [];
109
- for (const { dir, manifest } of shipped()) {
110
- const entries = [
111
- ...(manifest.module ? [manifest.module] : []),
112
- ...(manifest.main ? [manifest.main] : []),
113
- ...exportTargets(manifest.exports),
114
- ];
115
- const packed = packedFiles(dir);
116
- for (const file of reachable(dir, entries)) {
117
- if (!packed.has(file)) {
118
- missing.push(`${manifest.name}: ${relative(dir, file)} is imported but not packed`);
119
- }
120
- }
121
- }
122
- expect(missing).toEqual([]);
123
- }, 60_000);
124
-
125
- test("no relative import points at a file that does not exist", () => {
126
- // A type-only import of a missing file still runs, because Bun erases
127
- // it, so this is the only thing that notices.
128
- const broken: string[] = [];
129
- for (const { dir, manifest } of shipped()) {
130
- const entries = [
131
- ...(manifest.module ? [manifest.module] : []),
132
- ...exportTargets(manifest.exports),
133
- ];
134
- for (const file of reachable(dir, entries)) {
135
- for (const m of code(file).matchAll(IMPORT)) {
136
- const spec = m[1] ?? m[2] ?? m[3];
137
- // `./$types` is generated per route, not a file here.
138
- if (spec && !spec.includes("$") && !resolveImport(file, spec)) {
139
- broken.push(`${manifest.name}: ${relative(dir, file)} imports ${spec}`);
140
- }
141
- }
142
- }
143
- }
144
- expect(broken).toEqual([]);
145
- });
146
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { dirname, join, normalize, relative } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /**
8
+ * A packed tarball must contain every file its entry points import.
9
+ *
10
+ * `files` in package.json is a list someone types, and a module added later
11
+ * is not on it. Nothing in the workspace notices, because every import
12
+ * resolves against the source tree; only the installed tarball is missing
13
+ * the file, and it fails at boot in the app.
14
+ *
15
+ * Not hypothetical, twice: plugin-sql shipped without `database.ts` and
16
+ * `fragment.ts`, which `index.ts` imports, and plugin-jobs shipped without
17
+ * `store.ts`, `store-bun.ts` and `store-drizzle.ts`.
18
+ */
19
+
20
+ const ROOT = fileURLToPath(new URL("../../../", import.meta.url));
21
+
22
+ interface Manifest {
23
+ name?: string;
24
+ version?: string;
25
+ private?: boolean;
26
+ module?: string;
27
+ main?: string;
28
+ exports?: unknown;
29
+ bin?: string | Record<string, string>;
30
+ }
31
+
32
+ function shipped(): { dir: string; manifest: Manifest }[] {
33
+ return readdirSync(join(ROOT, "packages"), { withFileTypes: true })
34
+ .filter((e) => e.isDirectory())
35
+ .flatMap((e) => {
36
+ const file = join(ROOT, "packages", e.name, "package.json");
37
+ if (!existsSync(file)) return [];
38
+ const manifest = JSON.parse(readFileSync(file, "utf8")) as Manifest;
39
+ return [{ dir: join(ROOT, "packages", e.name), manifest }];
40
+ })
41
+ .filter(
42
+ ({ manifest }) =>
43
+ manifest.name?.startsWith("@sigil-dev/") &&
44
+ typeof manifest.version === "string" &&
45
+ !manifest.private,
46
+ );
47
+ }
48
+
49
+ /** Every path string reachable in an `exports` map. */
50
+ function exportTargets(exp: unknown): string[] {
51
+ if (typeof exp === "string") return [exp];
52
+ if (exp && typeof exp === "object") {
53
+ return Object.values(exp).flatMap(exportTargets);
54
+ }
55
+ return [];
56
+ }
57
+
58
+ const SOURCE = /\.(ts|tsx|js|mjs)$/;
59
+ const IMPORT =
60
+ /(?:^|[\s;])(?:import|export)\s[^'"]*?from\s*["'](\.{1,2}\/[^"']+)["']|import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)|^import\s+["'](\.{1,2}\/[^"']+)["']/gm;
61
+
62
+ /** Source without comments, so an import shown in a doc example is not one. */
63
+ const code = (file: string): string =>
64
+ readFileSync(file, "utf8")
65
+ .replace(/\/\*[\s\S]*?\*\//g, "")
66
+ .replace(/^\s*\/\/.*$/gm, "");
67
+
68
+ function resolveImport(from: string, spec: string): string | null {
69
+ const base = normalize(join(dirname(from), spec));
70
+ // TypeScript's `./x.js` for `./x.ts`.
71
+ const ts = base.replace(/\.js$/, ".ts");
72
+ for (const candidate of [base, ts, `${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
73
+ if (existsSync(candidate) && SOURCE.test(candidate)) return candidate;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /** The files the entry points reach through relative imports. */
79
+ function reachable(dir: string, entries: string[]): Set<string> {
80
+ const seen = new Set<string>();
81
+ const queue = entries.map((e) => normalize(join(dir, e))).filter((f) => SOURCE.test(f));
82
+ while (queue.length) {
83
+ const file = queue.pop()!;
84
+ if (seen.has(file) || !existsSync(file)) continue;
85
+ seen.add(file);
86
+ for (const m of code(file).matchAll(IMPORT)) {
87
+ const spec = m[1] ?? m[2] ?? m[3];
88
+ if (!spec) continue;
89
+ const target = resolveImport(file, spec);
90
+ // Only files inside the package: a relative import that escapes
91
+ // it is a different bug, and one the pack cannot fix.
92
+ if (target && !relative(dir, target).startsWith("..")) queue.push(target);
93
+ }
94
+ }
95
+ return seen;
96
+ }
97
+
98
+ function packedFiles(dir: string): Set<string> {
99
+ const out = execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], {
100
+ cwd: dir,
101
+ encoding: "utf8",
102
+ stdio: ["ignore", "pipe", "ignore"],
103
+ });
104
+ const [report] = JSON.parse(out) as Array<{ files: Array<{ path: string }> }>;
105
+ return new Set(report!.files.map((f) => normalize(join(dir, f.path))));
106
+ }
107
+
108
+ describe("workspace files", () => {
109
+ test("every file an entry point imports is in the tarball", () => {
110
+ const missing: string[] = [];
111
+ for (const { dir, manifest } of shipped()) {
112
+ const entries = [
113
+ ...(manifest.module ? [manifest.module] : []),
114
+ ...(manifest.main ? [manifest.main] : []),
115
+ ...exportTargets(manifest.bin),
116
+ ...exportTargets(manifest.exports),
117
+ ];
118
+ const packed = packedFiles(dir);
119
+ for (const file of reachable(dir, entries)) {
120
+ if (!packed.has(file)) {
121
+ missing.push(`${manifest.name}: ${relative(dir, file)} is imported but not packed`);
122
+ }
123
+ }
124
+ }
125
+ expect(missing).toEqual([]);
126
+ }, 60_000);
127
+
128
+ test("no relative import points at a file that does not exist", () => {
129
+ // A type-only import of a missing file still runs, because Bun erases
130
+ // it, so this is the only thing that notices.
131
+ const broken: string[] = [];
132
+ for (const { dir, manifest } of shipped()) {
133
+ const entries = [
134
+ ...(manifest.module ? [manifest.module] : []),
135
+ ...exportTargets(manifest.exports),
136
+ ];
137
+ for (const file of reachable(dir, entries)) {
138
+ for (const m of code(file).matchAll(IMPORT)) {
139
+ const spec = m[1] ?? m[2] ?? m[3];
140
+ // `./$types` is generated per route, not a file here.
141
+ if (spec && !spec.includes("$") && !resolveImport(file, spec)) {
142
+ broken.push(`${manifest.name}: ${relative(dir, file)} imports ${spec}`);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ expect(broken).toEqual([]);
148
+ });
149
+ });