@sigil-dev/grimoire 0.9.12 → 0.9.13

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,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
+
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
+ });
@@ -0,0 +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,4 +0,0 @@
1
-
2
- export const routes: Record<string, (props: any) => any> = {
3
-
4
- };
@@ -1,55 +0,0 @@
1
- // .grimoire/_routes.ts
2
- var routes = {};
3
-
4
- // src/client-router.ts
5
- var routeMap = {};
6
- async function navigate(path) {
7
- const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
8
- const json = await res.json();
9
- console.log("navigate response:", json);
10
- const { data, params, pattern, head } = json;
11
- const Page = routeMap[pattern];
12
- if (!Page) {
13
- window.location.href = path;
14
- return;
15
- }
16
- const node = Page({ ...data, params });
17
- const slot = document.getElementById("grimoire-page");
18
- if (!slot)
19
- return;
20
- slot.replaceChildren(node);
21
- updateHead(head);
22
- history.pushState({}, "", path);
23
- window.scrollTo(0, 0);
24
- }
25
- function initRouter(routes2) {
26
- routeMap = routes2;
27
- document.addEventListener("click", handleClick);
28
- window.addEventListener("popstate", () => navigate(location.pathname));
29
- }
30
- function updateHead(headHtml) {
31
- document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
32
- if (!headHtml)
33
- return;
34
- const tmp = document.createElement("head");
35
- tmp.innerHTML = headHtml;
36
- for (const el of Array.from(tmp.children)) {
37
- el.dataset.grimoireHead = "1";
38
- document.head.appendChild(el);
39
- }
40
- }
41
- function handleClick(e) {
42
- const a = e.target.closest("a");
43
- if (!a)
44
- return;
45
- const href = a.getAttribute("href");
46
- if (!href)
47
- return;
48
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
49
- return;
50
- e.preventDefault();
51
- navigate(href);
52
- }
53
-
54
- // src/client.ts
55
- initRouter(routes);
@@ -1,63 +0,0 @@
1
- // .grimoire/_routes.ts
2
- var routes = {};
3
-
4
- // src/client-router.ts
5
- var routeMap = {};
6
- async function navigate(path) {
7
- const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
8
- const json = await res.json();
9
- console.log("navigate response:", json);
10
- const { data, params, pattern, head } = json;
11
- const Page = routeMap[pattern];
12
- if (!Page) {
13
- window.location.href = path;
14
- return;
15
- }
16
- const node = Page({ ...data, params });
17
- const slot = document.getElementById("grimoire-page");
18
- if (!slot)
19
- return;
20
- slot.replaceChildren(node);
21
- updateHead(head);
22
- history.pushState({}, "", path);
23
- window.scrollTo(0, 0);
24
- }
25
- function initRouter(routes2) {
26
- routeMap = routes2;
27
- document.addEventListener("click", handleClick);
28
- window.addEventListener("popstate", () => navigate(location.pathname));
29
- }
30
- function updateHead(headHtml) {
31
- document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
32
- if (!headHtml)
33
- return;
34
- const tmp = document.createElement("head");
35
- tmp.innerHTML = headHtml;
36
- for (const el of Array.from(tmp.children)) {
37
- el.dataset.grimoireHead = "1";
38
- document.head.appendChild(el);
39
- }
40
- }
41
- function handleClick(e) {
42
- const a = e.target.closest("a");
43
- if (!a)
44
- return;
45
- const href = a.getAttribute("href");
46
- if (!href)
47
- return;
48
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
49
- return;
50
- e.preventDefault();
51
- navigate(href);
52
- }
53
-
54
- // src/hydrate.ts
55
- var stateEl = document.getElementById("__grimoire_state__");
56
- if (stateEl) {
57
- const state = JSON.parse(stateEl.textContent);
58
- const Page = routes[state.pattern];
59
- if (Page) {
60
- Page({ ...state.data, params: state.params });
61
- }
62
- }
63
- initRouter(routes);