@sigil-dev/grimoire 0.9.22 → 0.9.24

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.
@@ -0,0 +1,38 @@
1
+ import { matchRoute } from "../routing/router";
2
+ import type { RouteTree } from "../routing/scanner";
3
+ import type { GrimoirePlugin } from "../types";
4
+
5
+ export interface ShadowedRoute {
6
+ plugin: string;
7
+ path: string;
8
+ /** The app's route file that never sees requests for `path`. */
9
+ file: string;
10
+ }
11
+
12
+ /**
13
+ * App routes that a plugin's `handle` answers first, so they never run for
14
+ * those paths. A warning rather than an error: the overlap can be deliberate.
15
+ */
16
+ export function shadowedRoutes(
17
+ plugins: GrimoirePlugin[],
18
+ tree: RouteTree,
19
+ matchers?: Record<string, (value: string) => boolean>,
20
+ ): ShadowedRoute[] {
21
+ const found: ShadowedRoute[] = [];
22
+ for (const plugin of plugins) {
23
+ for (const path of plugin.routes ?? []) {
24
+ const hit = matchRoute(tree, new URL(path, "http://localhost"), matchers);
25
+ if (hit && !hit.notFound) {
26
+ found.push({ plugin: plugin.name, path, file: hit.route.clientPath });
27
+ }
28
+ }
29
+ }
30
+ return found;
31
+ }
32
+
33
+ export function shadowedRouteMessage(s: ShadowedRoute): string {
34
+ return (
35
+ `${s.file} never runs for ${s.path}: the "${s.plugin}" plugin answers that path first. ` +
36
+ "Move the route, or if it was meant to add to what the plugin does, do that in hooks.server.ts instead."
37
+ );
38
+ }
@@ -92,7 +92,11 @@ export function rewriteAliases(
92
92
  const file = resolveFile(
93
93
  join(aliases[prefix]!, specifier.slice(prefix.length)),
94
94
  );
95
- return file ? `${keyword}${quote}${file}${quote}` : match;
95
+ // Forward slashes: this lands inside a JS string literal, where a
96
+ // Windows path's backslashes would be read as escapes (\P → P).
97
+ return file
98
+ ? `${keyword}${quote}${file.replaceAll("\\", "/")}${quote}`
99
+ : match;
96
100
  },
97
101
  );
98
102
  }
package/src/types.ts CHANGED
@@ -16,6 +16,7 @@ export interface CliCommand {
16
16
  alias(alias: string): CliCommand;
17
17
  option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
18
18
  argument(name: string, description?: string): CliCommand;
19
+ addHelpText(position: "before" | "after", text: string): CliCommand;
19
20
  action(fn: (...args: never[]) => unknown): CliCommand;
20
21
  }
21
22
 
@@ -194,6 +195,12 @@ export interface GrimoirePlugin {
194
195
  * the app's own handle sees whatever the plugins put on `locals`.
195
196
  */
196
197
  handle?: Handle;
198
+ /**
199
+ * Paths `handle` answers without calling `resolve`, such as auth's
200
+ * `/auth/github/callback`. Listing them lets Grimoire warn at startup when
201
+ * an app route sits on one and would never run.
202
+ */
203
+ routes?: readonly string[];
197
204
 
198
205
  // request pipeline
199
206
  onRequest?(
package/test/env.test.ts CHANGED
@@ -159,7 +159,10 @@ describe("$env modules in builds", () => {
159
159
  'import { db } from "$lib/db";\nimport x from "other";',
160
160
  { $lib: join(dir, "lib") },
161
161
  );
162
- expect(out).toContain(`from "${join(dir, "lib/db.ts")}"`);
162
+ // forward slashes even on Windows: the path lands in a string literal
163
+ expect(out).toContain(
164
+ `from "${join(dir, "lib/db.ts").replaceAll("\\", "/")}"`,
165
+ );
163
166
  expect(out).toContain('from "other"');
164
167
  } finally {
165
168
  await rm(dir, { recursive: true, force: true });
@@ -1,92 +1,92 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { transformSync } from "@babel/core";
3
- import type { ParserPlugin } from "@babel/core";
4
-
5
- /**
6
- * The parser configuration the SSR plugin uses, pinned here so a change to
7
- * it has to be made in two places deliberately.
8
- *
9
- * Kept in sync by hand rather than imported: the plugin builds its own
10
- * parserOpts inline, and a test that imported that would be testing the
11
- * import rather than the behaviour. The failing case is named below, and it
12
- * was found by a real adapter rather than by reading the config.
13
- */
14
- const parserOptsFor = (path: string): { plugins: ParserPlugin[] } =>
15
- path.endsWith(".tsx")
16
- ? { plugins: ["typescript", "jsx"] }
17
- : { plugins: ["typescript"] };
18
-
19
- const parse = (source: string, filename: string) =>
20
- transformSync(source, {
21
- configFile: false,
22
- babelrc: false,
23
- parserOpts: parserOptsFor(filename),
24
- filename,
25
- });
26
-
27
- describe("the jsx parser plugin is scoped to .tsx", () => {
28
- test("a generic arrow function compiles in a .ts file", () => {
29
- // This is the regression. With ["typescript", "jsx"] on every file,
30
- // Babel reads `<R>(x: R) => x` as the start of a JSX element and
31
- // fails with "Unexpected token `>`". Generic arrows are ordinary
32
- // TypeScript, and this is the exact line that lets a Drizzle adapter
33
- // drop an `as any`:
34
- //
35
- // transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
36
- // db.transaction(fn)
37
- expect(() =>
38
- parse(
39
- "const o = { f: <R>(x: R): R => x };\nexport const out = o;",
40
- "adapter.ts",
41
- ),
42
- ).not.toThrow();
43
- });
44
-
45
- test("a generic arrow in an object literal, the failing shape", () => {
46
- // The minimal repro. Inside a call argument the parser is in a
47
- // different state, which is why the one above passes and this failed.
48
- expect(() =>
49
- parse("define({ f: <R>(x: R): R => x });", "adapter.ts"),
50
- ).not.toThrow();
51
- });
52
-
53
- test("JSX still compiles in a .tsx file", () => {
54
- // The whole reason the jsx plugin exists must keep working.
55
- expect(() =>
56
- parse("const a = <div x={1} />;\nexport default a;", "page.tsx"),
57
- ).not.toThrow();
58
- });
59
-
60
- test("a JSX fragment compiles in a .tsx file", () => {
61
- expect(() =>
62
- parse("const a = <><b/></>;\nexport default a;", "page.tsx"),
63
- ).not.toThrow();
64
- });
65
-
66
- test("a generic arrow in a .tsx file needs the comma, as TypeScript says", () => {
67
- // Genuinely ambiguous, so the error is correct behaviour rather than a
68
- // bug — and worth pinning so the fix is not "regressed" later by
69
- // someone trying to make this pass without the comma.
70
- expect(() =>
71
- parse("const o = { f: <R,>(x: R): R => x };\nexport default o;", "a.tsx"),
72
- ).not.toThrow();
73
- });
74
- });
75
-
76
- describe("other TypeScript syntax in a .ts file", () => {
77
- // Dropping jsx from .ts must not cost anything else, which is the risk a
78
- // one-line parser change carries.
79
- for (const [label, source] of [
80
- ["as const", "const x = { a: 1 } as const;\nexport default x;"],
81
- ["satisfies", "const x = { a: 1 } satisfies Record<string, number>;\nexport default x;"],
82
- ["a generic interface", "interface I<T> { v: T }\nexport default I;"],
83
- ["an enum", "enum E { A }\nexport default E;"],
84
- ["optional chaining", "const x = a?.b?.c;\nexport default x;"],
85
- ["a type-only import", 'import type { A } from "./a.ts";\nexport default A;'],
86
- ["decorators-free classes", "class C { x = 1 }\nexport default C;"],
87
- ] as Array<[string, string]>) {
88
- test(label, () => {
89
- expect(() => parse(source, "file.ts")).not.toThrow();
90
- });
91
- }
92
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { transformSync } from "@babel/core";
3
+ import type { ParserPlugin } from "@babel/parser";
4
+
5
+ /**
6
+ * The parser configuration the SSR plugin uses, pinned here so a change to
7
+ * it has to be made in two places deliberately.
8
+ *
9
+ * Kept in sync by hand rather than imported: the plugin builds its own
10
+ * parserOpts inline, and a test that imported that would be testing the
11
+ * import rather than the behaviour. The failing case is named below, and it
12
+ * was found by a real adapter rather than by reading the config.
13
+ */
14
+ const parserOptsFor = (path: string): { plugins: ParserPlugin[] } =>
15
+ path.endsWith(".tsx")
16
+ ? { plugins: ["typescript", "jsx"] }
17
+ : { plugins: ["typescript"] };
18
+
19
+ const parse = (source: string, filename: string) =>
20
+ transformSync(source, {
21
+ configFile: false,
22
+ babelrc: false,
23
+ parserOpts: parserOptsFor(filename),
24
+ filename,
25
+ });
26
+
27
+ describe("the jsx parser plugin is scoped to .tsx", () => {
28
+ test("a generic arrow function compiles in a .ts file", () => {
29
+ // This is the regression. With ["typescript", "jsx"] on every file,
30
+ // Babel reads `<R>(x: R) => x` as the start of a JSX element and
31
+ // fails with "Unexpected token `>`". Generic arrows are ordinary
32
+ // TypeScript, and this is the exact line that lets a Drizzle adapter
33
+ // drop an `as any`:
34
+ //
35
+ // transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
36
+ // db.transaction(fn)
37
+ expect(() =>
38
+ parse(
39
+ "const o = { f: <R>(x: R): R => x };\nexport const out = o;",
40
+ "adapter.ts",
41
+ ),
42
+ ).not.toThrow();
43
+ });
44
+
45
+ test("a generic arrow in an object literal, the failing shape", () => {
46
+ // The minimal repro. Inside a call argument the parser is in a
47
+ // different state, which is why the one above passes and this failed.
48
+ expect(() =>
49
+ parse("define({ f: <R>(x: R): R => x });", "adapter.ts"),
50
+ ).not.toThrow();
51
+ });
52
+
53
+ test("JSX still compiles in a .tsx file", () => {
54
+ // The whole reason the jsx plugin exists must keep working.
55
+ expect(() =>
56
+ parse("const a = <div x={1} />;\nexport default a;", "page.tsx"),
57
+ ).not.toThrow();
58
+ });
59
+
60
+ test("a JSX fragment compiles in a .tsx file", () => {
61
+ expect(() =>
62
+ parse("const a = <><b/></>;\nexport default a;", "page.tsx"),
63
+ ).not.toThrow();
64
+ });
65
+
66
+ test("a generic arrow in a .tsx file needs the comma, as TypeScript says", () => {
67
+ // Genuinely ambiguous, so the error is correct behaviour rather than a
68
+ // bug — and worth pinning so the fix is not "regressed" later by
69
+ // someone trying to make this pass without the comma.
70
+ expect(() =>
71
+ parse("const o = { f: <R,>(x: R): R => x };\nexport default o;", "a.tsx"),
72
+ ).not.toThrow();
73
+ });
74
+ });
75
+
76
+ describe("other TypeScript syntax in a .ts file", () => {
77
+ // Dropping jsx from .ts must not cost anything else, which is the risk a
78
+ // one-line parser change carries.
79
+ for (const [label, source] of [
80
+ ["as const", "const x = { a: 1 } as const;\nexport default x;"],
81
+ ["satisfies", "const x = { a: 1 } satisfies Record<string, number>;\nexport default x;"],
82
+ ["a generic interface", "interface I<T> { v: T }\nexport default I;"],
83
+ ["an enum", "enum E { A }\nexport default E;"],
84
+ ["optional chaining", "const x = a?.b?.c;\nexport default x;"],
85
+ ["a type-only import", 'import type { A } from "./a.ts";\nexport default A;'],
86
+ ["decorators-free classes", "class C { x = 1 }\nexport default C;"],
87
+ ] as Array<[string, string]>) {
88
+ test(label, () => {
89
+ expect(() => parse(source, "file.ts")).not.toThrow();
90
+ });
91
+ }
92
+ });
@@ -0,0 +1,42 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { scanRoutes } from "../src/routing/scanner";
6
+ import { shadowedRouteMessage, shadowedRoutes } from "../src/server/plugin-routes";
7
+
8
+ async function treeWith(files: string[]) {
9
+ const root = mkdtempSync(join(tmpdir(), "grimoire-shadow-"));
10
+ const routes = join(root, "src/routes");
11
+ for (const f of files) {
12
+ mkdirSync(join(routes, f, ".."), { recursive: true });
13
+ writeFileSync(join(routes, f), "export default () => null;");
14
+ }
15
+ return scanRoutes(routes, root);
16
+ }
17
+
18
+ test("an app route on a path a plugin answers is reported, by file", async () => {
19
+ const tree = await treeWith([
20
+ "+page.tsx",
21
+ "auth/github/callback/+page.tsx",
22
+ "auth/[provider]/+page.tsx",
23
+ ]);
24
+ const found = shadowedRoutes(
25
+ [
26
+ { name: "tome", routes: ["/auth/github", "/auth/github/callback"] },
27
+ { name: "quiet" },
28
+ ],
29
+ tree,
30
+ );
31
+ expect(found.map((f) => [f.plugin, f.path])).toEqual([
32
+ ["tome", "/auth/github"],
33
+ ["tome", "/auth/github/callback"],
34
+ ]);
35
+ expect(found[1]!.file).toContain("auth/github/callback/+page.tsx");
36
+ expect(shadowedRouteMessage(found[1]!)).toContain("hooks.server.ts");
37
+ });
38
+
39
+ test("no overlap, no warning", async () => {
40
+ const tree = await treeWith(["+page.tsx", "login/+page.tsx"]);
41
+ expect(shadowedRoutes([{ name: "tome", routes: ["/auth/github"] }], tree)).toEqual([]);
42
+ });
@@ -534,7 +534,8 @@ describe("renderRoute", () => {
534
534
  expect(html).toContain("My Blog");
535
535
  // the state JSON embeds data under the data key
536
536
  const stateJson = JSON.parse(
537
- html.match(/<script[^>]*>([^<]+)<\/script>/)?.[1] ?? "{}",
537
+ html.match(/<script id="__grimoire_state__"[^>]*>([^<]+)<\/script>/)?.[1] ??
538
+ "{}",
538
539
  );
539
540
  expect(stateJson.data?.title).toBe("My Blog");
540
541
  expect(html).not.toContain("[object Object]");
@@ -0,0 +1,23 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { rewriteAliases } from "../src/server/resolver";
6
+
7
+ // On Windows the resolved file is D:\Projects\app\src\lib\x.ts. Written into a
8
+ // string literal as is, every backslash is an escape and the import becomes
9
+ // "D:Projectsappsrclibx.ts". The specifier must use forward slashes.
10
+ test("aliased imports are written with forward slashes", () => {
11
+ const root = mkdtempSync(join(tmpdir(), "grimoire-alias-"));
12
+ mkdirSync(join(root, "src/lib/server"), { recursive: true });
13
+ writeFileSync(join(root, "src/lib/server/auth.ts"), "export const auth = 1;");
14
+
15
+ const out = rewriteAliases(
16
+ 'import { auth } from "$lib/server/auth";',
17
+ { $lib: join(root, "src/lib") },
18
+ );
19
+
20
+ const specifier = out.match(/from "([^"]+)"/)?.[1] ?? "";
21
+ expect(specifier).not.toContain("\\");
22
+ expect(specifier.endsWith("/src/lib/server/auth.ts")).toBe(true);
23
+ });
@@ -5,6 +5,9 @@ import { join } from "node:path";
5
5
  import { renderRoute } from "../src/rendering";
6
6
  import { matchRoute } from "../src/routing/router";
7
7
  import { scanRoutes } from "../src/routing/scanner";
8
+
9
+ // An absolute path, because the fixture lives in a temp dir outside the package.
10
+ const DEFERRED_SRC = join(import.meta.dir, "../src/client/deferred.ts").replaceAll("\\", "/");
8
11
 
9
12
  function makeMatched(path: string, filePath: string, params = {}) {
10
13
  return {
@@ -347,7 +350,7 @@ describe("streamed promises (deferred data)", () => {
347
350
  await writeFile(
348
351
  join(dir, "+page.tsx"),
349
352
  [
350
- 'import { deferred } from "/opt/sigil/packages/grimoire/src/client/deferred.ts";',
353
+ `import { deferred } from ${JSON.stringify(DEFERRED_SRC)};`,
351
354
  "export default function P({ data }) {",
352
355
  " const reviews = deferred(data.reviews, []);",
353
356
  " return (",
@@ -600,6 +600,9 @@ export async function comment() {
600
600
  }`,
601
601
  );
602
602
 
603
+ // the scanner rejects a +page.server.ts that has no page beside it
604
+ await writeFile(join(routeDir, "+page.tsx"), "export default () => null;\n");
605
+
603
606
  // a +server.ts route: its types must compile without Bun's types installed
604
607
  const chatDir = join(tscDir, "src", "routes", "chat");
605
608
  await mkdir(chatDir, { recursive: true });
@@ -1,131 +1,131 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { readFileSync, readdirSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- /**
6
- * A packed tarball must not carry a version its manifest does not have.
7
- *
8
- * `bun pm pack` rewrites `workspace:*` to a concrete version by reading the
9
- * *lockfile*, not the manifest. So editing a package.json to bump a version
10
- * and then packing, without installing first, produces a tarball that
11
- * silently depends on the old version of a sibling.
12
- *
13
- * Not hypothetical. Bumping `packages/compiler` to 0.9.12 without running
14
- * `bun install` left `bun.lock` at 0.9.10, so every grimoire tarball packed
15
- * afterwards pinned `@sigil-dev/compiler: 0.9.10`. The app installed it and
16
- * failed at boot with
17
- *
18
- * Export named 'clientStyleSnippet' not found in
19
- * .../@sigil-dev/compiler/src/babel/util/css.ts
20
- *
21
- * which reads like a compiler bug and is really a packaging one. It cost a
22
- * long time to find, because nothing in the failure mentioned a version.
23
- */
24
-
25
- const ROOT = new URL("../../../", import.meta.url).pathname;
26
- const lock = readFileSync(join(ROOT, "bun.lock"), "utf8");
27
-
28
- interface Manifest {
29
- name?: string;
30
- version?: string;
31
- private?: boolean;
32
- }
33
-
34
- /** Every workspace under `packages/*`, whether or not it carries a version. */
35
- function allWorkspaces(): { dir: string; manifest: Manifest }[] {
36
- return readdirSync(join(ROOT, "packages"), { withFileTypes: true })
37
- .filter((e) => e.isDirectory())
38
- .flatMap((e) => {
39
- try {
40
- const manifest = JSON.parse(
41
- readFileSync(join(ROOT, "packages", e.name, "package.json"), "utf8"),
42
- ) as Manifest;
43
- return [{ dir: e.name, manifest }];
44
- } catch {
45
- return [];
46
- }
47
- })
48
- .filter(({ manifest }) => manifest.name?.startsWith("@sigil-dev/"));
49
- }
50
-
51
- /**
52
- * The ones an app can install. `site` and the two demos carry no version and
53
- * are never packed, so demanding one of them would be this test failing for a
54
- * reason that has nothing to do with the bug it exists to catch.
55
- */
56
- function shipped(): { dir: string; manifest: Manifest & { name: string; version: string } }[] {
57
- return allWorkspaces().filter(
58
- (w): w is { dir: string; manifest: Manifest & { name: string; version: string } } =>
59
- typeof w.manifest.name === "string" &&
60
- typeof w.manifest.version === "string" &&
61
- !w.manifest.private,
62
- );
63
- }
64
-
65
- describe("workspace versions", () => {
66
- test("the lockfile agrees with every shipped manifest", () => {
67
- // bun.lock records each workspace as
68
- // "packages/compiler": { "name": "@sigil-dev/compiler", "version": "0.9.12",
69
- // so a stale entry is a correct name next to a wrong version.
70
- const mismatches: string[] = [];
71
- for (const { dir, manifest } of shipped()) {
72
- const entry = new RegExp(
73
- `"packages/${dir}": \\{\\s*"name": "${manifest.name}",\\s*"version": "([^"]+)"`,
74
- ).exec(lock);
75
- if (!entry) {
76
- mismatches.push(`${manifest.name}: absent from bun.lock`);
77
- continue;
78
- }
79
- if (entry[1] !== manifest.version) {
80
- mismatches.push(
81
- `${manifest.name}: manifest says ${manifest.version} but bun.lock says ` +
82
- `${entry[1]} — run \`bun install\` before \`bun pm pack\`, or the ` +
83
- `tarball pins the old version of a sibling`,
84
- );
85
- }
86
- }
87
- expect(mismatches).toEqual([]);
88
- });
89
-
90
- test("every shipped package is at the same version", () => {
91
- // Two packages at different versions means a `workspace:*` between
92
- // them resolves to whichever one the lockfile saw, which is how a
93
- // packed dependency ends up pointing at a version nothing claims.
94
- const distinct = [...new Set(shipped().map(({ manifest }) => manifest.version))];
95
- expect(
96
- distinct.length === 1
97
- ? []
98
- : [`packages sit at ${distinct.join(", ")} — a release moves them together`],
99
- ).toEqual([]);
100
- });
101
-
102
- test("the release version is not already published with other content", async () => {
103
- // The same trap wearing a different hat. `@sigil-dev/grimoire@0.9.12`
104
- // was on npm, published before plugin services existed, while this
105
- // tree kept calling itself 0.9.12. An app pinning that exact version
106
- // installed the registry copy *beside* the local tarball: two copies,
107
- // both reporting 0.9.12, one with no `collectServices` at all.
108
- //
109
- // So a version is only safe to depend on once it is published *with*
110
- // this content. Until then a consumer resolves to the older tarball.
111
- const version = shipped()[0]?.manifest.version;
112
- if (!version) return;
113
-
114
- // Registry access is best-effort: a suite that needs the network to
115
- // pass is a suite that gets skipped in CI without saying so.
116
- const res = await fetch("https://registry.npmjs.org/@sigil-dev%2Fgrimoire", {
117
- signal: AbortSignal.timeout(4000),
118
- }).catch(() => null);
119
- if (!res?.ok) return;
120
- const body = (await res.json()) as { versions?: Record<string, unknown> };
121
- const alreadyThere = Boolean(body.versions?.[version]);
122
- expect(
123
- alreadyThere
124
- ? []
125
- : [
126
- `${version} is not on npm yet, so it cannot be pinned by a consumer`,
127
- `without pulling a different tarball at the same version number`,
128
- ],
129
- ).toEqual([]);
130
- });
131
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * A packed tarball must not carry a version its manifest does not have.
7
+ *
8
+ * `bun pm pack` rewrites `workspace:*` to a concrete version by reading the
9
+ * *lockfile*, not the manifest. So editing a package.json to bump a version
10
+ * and then packing, without installing first, produces a tarball that
11
+ * silently depends on the old version of a sibling.
12
+ *
13
+ * Not hypothetical. Bumping `packages/compiler` to 0.9.12 without running
14
+ * `bun install` left `bun.lock` at 0.9.10, so every grimoire tarball packed
15
+ * afterwards pinned `@sigil-dev/compiler: 0.9.10`. The app installed it and
16
+ * failed at boot with
17
+ *
18
+ * Export named 'clientStyleSnippet' not found in
19
+ * .../@sigil-dev/compiler/src/babel/util/css.ts
20
+ *
21
+ * which reads like a compiler bug and is really a packaging one. It cost a
22
+ * long time to find, because nothing in the failure mentioned a version.
23
+ */
24
+
25
+ const ROOT = join(import.meta.dir, "../../..");
26
+ const lock = readFileSync(join(ROOT, "bun.lock"), "utf8");
27
+
28
+ interface Manifest {
29
+ name?: string;
30
+ version?: string;
31
+ private?: boolean;
32
+ }
33
+
34
+ /** Every workspace under `packages/*`, whether or not it carries a version. */
35
+ function allWorkspaces(): { dir: string; manifest: Manifest }[] {
36
+ return readdirSync(join(ROOT, "packages"), { withFileTypes: true })
37
+ .filter((e) => e.isDirectory())
38
+ .flatMap((e) => {
39
+ try {
40
+ const manifest = JSON.parse(
41
+ readFileSync(join(ROOT, "packages", e.name, "package.json"), "utf8"),
42
+ ) as Manifest;
43
+ return [{ dir: e.name, manifest }];
44
+ } catch {
45
+ return [];
46
+ }
47
+ })
48
+ .filter(({ manifest }) => manifest.name?.startsWith("@sigil-dev/"));
49
+ }
50
+
51
+ /**
52
+ * The ones an app can install. `site` and the two demos carry no version and
53
+ * are never packed, so demanding one of them would be this test failing for a
54
+ * reason that has nothing to do with the bug it exists to catch.
55
+ */
56
+ function shipped(): { dir: string; manifest: Manifest & { name: string; version: string } }[] {
57
+ return allWorkspaces().filter(
58
+ (w): w is { dir: string; manifest: Manifest & { name: string; version: string } } =>
59
+ typeof w.manifest.name === "string" &&
60
+ typeof w.manifest.version === "string" &&
61
+ !w.manifest.private,
62
+ );
63
+ }
64
+
65
+ describe("workspace versions", () => {
66
+ test("the lockfile agrees with every shipped manifest", () => {
67
+ // bun.lock records each workspace as
68
+ // "packages/compiler": { "name": "@sigil-dev/compiler", "version": "0.9.12",
69
+ // so a stale entry is a correct name next to a wrong version.
70
+ const mismatches: string[] = [];
71
+ for (const { dir, manifest } of shipped()) {
72
+ const entry = new RegExp(
73
+ `"packages/${dir}": \\{\\s*"name": "${manifest.name}",\\s*"version": "([^"]+)"`,
74
+ ).exec(lock);
75
+ if (!entry) {
76
+ mismatches.push(`${manifest.name}: absent from bun.lock`);
77
+ continue;
78
+ }
79
+ if (entry[1] !== manifest.version) {
80
+ mismatches.push(
81
+ `${manifest.name}: manifest says ${manifest.version} but bun.lock says ` +
82
+ `${entry[1]} — run \`bun install\` before \`bun pm pack\`, or the ` +
83
+ `tarball pins the old version of a sibling`,
84
+ );
85
+ }
86
+ }
87
+ expect(mismatches).toEqual([]);
88
+ });
89
+
90
+ test("every shipped package is at the same version", () => {
91
+ // Two packages at different versions means a `workspace:*` between
92
+ // them resolves to whichever one the lockfile saw, which is how a
93
+ // packed dependency ends up pointing at a version nothing claims.
94
+ const distinct = [...new Set(shipped().map(({ manifest }) => manifest.version))];
95
+ expect(
96
+ distinct.length === 1
97
+ ? []
98
+ : [`packages sit at ${distinct.join(", ")} — a release moves them together`],
99
+ ).toEqual([]);
100
+ });
101
+
102
+ test("the release version is not already published with other content", async () => {
103
+ // The same trap wearing a different hat. `@sigil-dev/grimoire@0.9.12`
104
+ // was on npm, published before plugin services existed, while this
105
+ // tree kept calling itself 0.9.12. An app pinning that exact version
106
+ // installed the registry copy *beside* the local tarball: two copies,
107
+ // both reporting 0.9.12, one with no `collectServices` at all.
108
+ //
109
+ // So a version is only safe to depend on once it is published *with*
110
+ // this content. Until then a consumer resolves to the older tarball.
111
+ const version = shipped()[0]?.manifest.version;
112
+ if (!version) return;
113
+
114
+ // Registry access is best-effort: a suite that needs the network to
115
+ // pass is a suite that gets skipped in CI without saying so.
116
+ const res = await fetch("https://registry.npmjs.org/@sigil-dev%2Fgrimoire", {
117
+ signal: AbortSignal.timeout(4000),
118
+ }).catch(() => null);
119
+ if (!res?.ok) return;
120
+ const body = (await res.json()) as { versions?: Record<string, unknown> };
121
+ const alreadyThere = Boolean(body.versions?.[version]);
122
+ expect(
123
+ alreadyThere
124
+ ? []
125
+ : [
126
+ `${version} is not on npm yet, so it cannot be pinned by a consumer`,
127
+ `without pulling a different tarball at the same version number`,
128
+ ],
129
+ ).toEqual([]);
130
+ });
131
+ });