@sigil-dev/grimoire 0.9.26 → 0.9.27

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.
@@ -1,211 +1,193 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { join, relative } from "node:path";
4
- import { transformSync } from "@babel/core";
5
- import sigilPlugin from "@sigil-dev/compiler/babel";
6
- import {
7
- clientStyleSnippet,
8
- computeHash,
9
- extractStyles,
10
- } from "@sigil-dev/compiler/css";
11
- import type { DevGraph } from "./graph";
12
- import { normalizePath } from "./paths";
13
- import { resolveProjectImport } from "./resolve";
14
-
15
- const RUNTIME_URL = "/__grimoire__/runtime.js";
16
- const MODULES_BASE = "/__grimoire__/m/";
17
- const DEPS_BASE = "/__grimoire__/dep/";
18
-
19
- export interface BrowserCompileContext {
20
- projectRoot: string;
21
- /** GrimoireConfig.alias — prefix → project-relative directory. */
22
- aliases: Record<string, string>;
23
- /** Supplies the version each dependency URL is stamped with. */
24
- graph?: DevGraph;
25
- }
26
-
27
- /** `/__grimoire__/m/src/lib/Card.tsx.js?v=3` for a project module. */
28
- function moduleUrl(absPath: string, ctx: BrowserCompileContext): string {
29
- const rel = relative(ctx.projectRoot, absPath).replace(/\\/g, "/");
30
- const version = ctx.graph?.get(absPath)?.version ?? 0;
31
- return `${MODULES_BASE}${rel}.js?v=${version}`;
32
- }
33
-
34
- /**
35
- * Rewrite one import specifier to a browser-servable URL.
36
- *
37
- * Project modules carry their graph version in the query string: the browser
38
- * caches ES modules by URL forever, so an edited component is only re-fetched
39
- * when the importing module's own text points at a new URL.
40
- */
41
- function rewriteSpecifier(
42
- specifier: string,
43
- fromFile: string,
44
- ctx: BrowserCompileContext,
45
- ): string {
46
- if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
47
- if (specifier.startsWith("$env/"))
48
- return `/__grimoire__/env/${specifier.slice("$env/".length)}.js`;
49
-
50
- const resolved = resolveProjectImport(
51
- specifier,
52
- fromFile,
53
- ctx.projectRoot,
54
- ctx.aliases,
55
- );
56
- if (resolved) return moduleUrl(resolved, ctx);
57
-
58
- // unresolvable relative import (missing file) — keep a module URL so the
59
- // browser reports the 404 against a path the developer recognises
60
- if (specifier.startsWith(".") || specifier.startsWith("$lib/")) {
61
- const rel = specifier.startsWith("$lib/")
62
- ? specifier.replace("$lib/", "src/lib/")
63
- : relative(ctx.projectRoot, join(fromFile, "..", specifier)).replace(
64
- /\\/g,
65
- "/",
66
- );
67
- return `${MODULES_BASE}${rel}.js`;
68
- }
69
-
70
- const pkgName = specifier.startsWith("@")
71
- ? specifier.split("/").slice(0, 2).join("/")
72
- : specifier.split("/")[0];
73
- return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
74
- }
75
-
76
- /** Rewrite static `from "…"` / `import "…"` and dynamic `import("…")`. */
77
- function rewriteImports(
78
- code: string,
79
- filePath: string,
80
- ctx: BrowserCompileContext,
81
- ): string {
82
- return code
83
- .replace(
84
- /(from\s+|import\s+)(["'])([^"']+)\2/g,
85
- (_m, keyword: string, quote: string, specifier: string) =>
86
- `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
87
- )
88
- .replace(
89
- /(import\s*\(\s*)(["'])([^"']+)\2/g,
90
- (_m, keyword: string, quote: string, specifier: string) =>
91
- `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
92
- );
93
- }
94
-
95
- export interface CompileResult {
96
- js: string;
97
- css: string | null;
98
- cssHash: string;
99
- }
100
-
101
- const RUNTIME_SPECIFIERS = [
102
- "createSignal",
103
- "createRawSignal",
104
- "createEffect",
105
- "createMemo",
106
- "reconcile",
107
- "claim",
108
- "claimText",
109
- "claimComment",
110
- "hydrateKeyedList",
111
- "insert",
112
- "getHydrationNodes",
113
- "pushHydrationNodes",
114
- "popHydrationNodes",
115
- "snapshot",
116
- "tracking",
117
- "createEffectPre",
118
- "createInspectEffect",
119
- "withEffectScope",
120
- ].join(", ");
121
-
122
- export async function compileForBrowser(
123
- filePath: string,
124
- ctx: BrowserCompileContext,
125
- ): Promise<CompileResult> {
126
- const source = await Bun.file(filePath).text();
127
-
128
- // the scope hash must be the compiler's own: a swapped module whose
129
- // elements carry a different class than the emitted CSS loses its styles
130
- const hash = computeHash(filePath);
131
- const { code: sourceNoStyle, css } = extractStyles(source, hash, filePath);
132
-
133
- // dom mode: swapped modules always re-render from scratch, they never
134
- // claim server-rendered nodes
135
- const babelResult = transformSync(sourceNoStyle, {
136
- configFile: false,
137
- babelrc: false,
138
- parserOpts: { plugins: ["typescript", "jsx"] },
139
- plugins: [
140
- [sigilPlugin, { mode: "dom", hash: css ? hash : undefined, dev: true }],
141
- ],
142
- filename: filePath,
143
- });
144
- // strip TypeScript types
145
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
146
- let js = transpiler.transformSync(babelResult?.code ?? "");
147
-
148
- js = js.replace(
149
- /import\s*\{[^}]+\}\s*from\s*["']@sigil-dev\/runtime["'];?/,
150
- `import { ${RUNTIME_SPECIFIERS} } from "@sigil-dev/runtime";`,
151
- );
152
-
153
- // inject scoped CSS at runtime
154
- if (css) js = clientStyleSnippet(hash, css) + js;
155
-
156
- js = rewriteImports(js, filePath, ctx);
157
-
158
- return { js, css, cssHash: hash };
159
- }
160
-
161
- const cacheName = (absPath: string, version: number): string => {
162
- // hashed so one flat cache dir holds every module, path separators and all
163
- const hash = createHash("md5")
164
- .update(normalizePath(absPath))
165
- .digest("hex")
166
- .slice(0, 8);
167
- return `${hash}_v${version}.js`;
168
- };
169
-
170
- /**
171
- * Compile a module for the browser at its current graph version, memoised on
172
- * disk. The version comes from the graph, not the request URL: a client may
173
- * ask for a stale `?v=`, and serving anything but current code would
174
- * reintroduce the mismatch HMR exists to avoid.
175
- */
176
- export async function getDevModule(
177
- absPath: string,
178
- ctx: BrowserCompileContext,
179
- ): Promise<CompileResult> {
180
- const version = ctx.graph?.get(absPath)?.version ?? 0;
181
- const cachePath = join(
182
- ctx.projectRoot,
183
- ".grimoire/dev-modules",
184
- cacheName(absPath, version),
185
- );
186
-
187
- const cached = Bun.file(cachePath);
188
- if (await cached.exists()) {
189
- return { js: await cached.text(), css: null, cssHash: "" };
190
- }
191
-
192
- const result = await compileForBrowser(absPath, ctx);
193
- cacheDevModule(absPath, version, ctx.projectRoot, result.js);
194
- return result;
195
- }
196
-
197
- /**
198
- * Store already-compiled output for a version. Used by the HMR pipeline, which
199
- * must compile the edited source *before* bumping the version — a failed
200
- * compile has to leave the previous version live.
201
- */
202
- export function cacheDevModule(
203
- absPath: string,
204
- version: number,
205
- projectRoot: string,
206
- js: string,
207
- ): void {
208
- const dir = join(projectRoot, ".grimoire/dev-modules");
209
- mkdirSync(dir, { recursive: true });
210
- writeFileSync(join(dir, cacheName(absPath, version)), js);
211
- }
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ import { transformSync } from "@babel/core";
5
+ import sigilPlugin from "@sigil-dev/compiler/babel";
6
+ import {
7
+ clientStyleSnippet,
8
+ computeHash,
9
+ extractStyles,
10
+ } from "@sigil-dev/compiler/css";
11
+ import type { DevGraph } from "./graph";
12
+ import { normalizePath } from "./paths";
13
+ import { absoluteAliases, resolveProjectImport } from "./resolve";
14
+
15
+ const RUNTIME_URL = "/__grimoire__/runtime.js";
16
+ const MODULES_BASE = "/__grimoire__/m/";
17
+ const DEPS_BASE = "/__grimoire__/dep/";
18
+
19
+ export interface BrowserCompileContext {
20
+ projectRoot: string;
21
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
22
+ aliases: Record<string, string>;
23
+ /** Supplies the version each dependency URL is stamped with. */
24
+ graph?: DevGraph;
25
+ }
26
+
27
+ /** `/__grimoire__/m/src/lib/Card.tsx.js?v=3` for a project module. */
28
+ function moduleUrl(absPath: string, ctx: BrowserCompileContext): string {
29
+ const rel = relative(ctx.projectRoot, absPath).replace(/\\/g, "/");
30
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
31
+ return `${MODULES_BASE}${rel}.js?v=${version}`;
32
+ }
33
+
34
+ /**
35
+ * Rewrite one import specifier to a browser-servable URL.
36
+ *
37
+ * Project modules carry their graph version in the query string: the browser
38
+ * caches ES modules by URL forever, so an edited component is only re-fetched
39
+ * when the importing module's own text points at a new URL.
40
+ */
41
+ function rewriteSpecifier(
42
+ specifier: string,
43
+ fromFile: string,
44
+ ctx: BrowserCompileContext,
45
+ ): string {
46
+ if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
47
+ if (specifier.startsWith("$env/"))
48
+ return `/__grimoire__/env/${specifier.slice("$env/".length)}.js`;
49
+
50
+ const resolved = resolveProjectImport(
51
+ specifier,
52
+ fromFile,
53
+ ctx.projectRoot,
54
+ ctx.aliases,
55
+ );
56
+ if (resolved) return moduleUrl(resolved, ctx);
57
+
58
+ // unresolvable relative import (missing file) — keep a module URL so the
59
+ // browser reports the 404 against a path the developer recognises
60
+ if (specifier.startsWith(".") || specifier.startsWith("$lib/")) {
61
+ const rel = specifier.startsWith("$lib/")
62
+ ? specifier.replace("$lib/", "src/lib/")
63
+ : relative(ctx.projectRoot, join(fromFile, "..", specifier)).replace(
64
+ /\\/g,
65
+ "/",
66
+ );
67
+ return `${MODULES_BASE}${rel}.js`;
68
+ }
69
+
70
+ const pkgName = specifier.startsWith("@")
71
+ ? specifier.split("/").slice(0, 2).join("/")
72
+ : specifier.split("/")[0];
73
+ return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
74
+ }
75
+
76
+ /** Rewrite static `from "…"` / `import "…"` and dynamic `import("…")`. */
77
+ function rewriteImports(
78
+ code: string,
79
+ filePath: string,
80
+ ctx: BrowserCompileContext,
81
+ ): string {
82
+ return code
83
+ .replace(
84
+ /(from\s+|import\s+)(["'])([^"']+)\2/g,
85
+ (_m, keyword: string, quote: string, specifier: string) =>
86
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
87
+ )
88
+ .replace(
89
+ /(import\s*\(\s*)(["'])([^"']+)\2/g,
90
+ (_m, keyword: string, quote: string, specifier: string) =>
91
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
92
+ );
93
+ }
94
+
95
+ export interface CompileResult {
96
+ js: string;
97
+ css: string | null;
98
+ cssHash: string;
99
+ }
100
+
101
+ export async function compileForBrowser(
102
+ filePath: string,
103
+ ctx: BrowserCompileContext,
104
+ ): Promise<CompileResult> {
105
+ const source = await Bun.file(filePath).text();
106
+
107
+ // the scope hash must be the compiler's own: a swapped module whose
108
+ // elements carry a different class than the emitted CSS loses its styles
109
+ const hash = computeHash(filePath);
110
+ const { code: sourceNoStyle, css } = extractStyles(source, hash, filePath);
111
+
112
+ // dom mode: swapped modules always re-render from scratch, they never
113
+ // claim server-rendered nodes
114
+ const babelResult = transformSync(sourceNoStyle, {
115
+ configFile: false,
116
+ babelrc: false,
117
+ parserOpts: { plugins: ["typescript", "jsx"] },
118
+ plugins: [
119
+ [
120
+ sigilPlugin,
121
+ {
122
+ mode: "dom",
123
+ hash: css ? hash : undefined,
124
+ dev: true,
125
+ aliases: absoluteAliases(ctx.projectRoot, ctx.aliases),
126
+ },
127
+ ],
128
+ ],
129
+ filename: filePath,
130
+ });
131
+ // strip TypeScript types
132
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
133
+ let js = transpiler.transformSync(babelResult?.code ?? "");
134
+
135
+ // inject scoped CSS at runtime
136
+ if (css) js = clientStyleSnippet(hash, css) + js;
137
+
138
+ js = rewriteImports(js, filePath, ctx);
139
+
140
+ return { js, css, cssHash: hash };
141
+ }
142
+
143
+ const cacheName = (absPath: string, version: number): string => {
144
+ // hashed so one flat cache dir holds every module, path separators and all
145
+ const hash = createHash("md5")
146
+ .update(normalizePath(absPath))
147
+ .digest("hex")
148
+ .slice(0, 8);
149
+ return `${hash}_v${version}.js`;
150
+ };
151
+
152
+ /**
153
+ * Compile a module for the browser at its current graph version, memoised on
154
+ * disk. The version comes from the graph, not the request URL: a client may
155
+ * ask for a stale `?v=`, and serving anything but current code would
156
+ * reintroduce the mismatch HMR exists to avoid.
157
+ */
158
+ export async function getDevModule(
159
+ absPath: string,
160
+ ctx: BrowserCompileContext,
161
+ ): Promise<CompileResult> {
162
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
163
+ const cachePath = join(
164
+ ctx.projectRoot,
165
+ ".grimoire/dev-modules",
166
+ cacheName(absPath, version),
167
+ );
168
+
169
+ const cached = Bun.file(cachePath);
170
+ if (await cached.exists()) {
171
+ return { js: await cached.text(), css: null, cssHash: "" };
172
+ }
173
+
174
+ const result = await compileForBrowser(absPath, ctx);
175
+ cacheDevModule(absPath, version, ctx.projectRoot, result.js);
176
+ return result;
177
+ }
178
+
179
+ /**
180
+ * Store already-compiled output for a version. Used by the HMR pipeline, which
181
+ * must compile the edited source *before* bumping the version — a failed
182
+ * compile has to leave the previous version live.
183
+ */
184
+ export function cacheDevModule(
185
+ absPath: string,
186
+ version: number,
187
+ projectRoot: string,
188
+ js: string,
189
+ ): void {
190
+ const dir = join(projectRoot, ".grimoire/dev-modules");
191
+ mkdirSync(dir, { recursive: true });
192
+ writeFileSync(join(dir, cacheName(absPath, version)), js);
193
+ }
package/src/dev/graph.ts CHANGED
@@ -69,7 +69,11 @@ export class DevGraph {
69
69
  return [...seen];
70
70
  }
71
71
 
72
- /** Walk importers up to routes. Returns affected RouteFiles. */
72
+ /**
73
+ * Walk importers up to routes. Returns affected RouteFiles. The walk goes on
74
+ * past a route: a page that imports another page (or a layout) is stale
75
+ * too, and invalidate() has already bumped it.
76
+ */
73
77
  affectedRoutes(changedKey: string): RouteFile[] {
74
78
  const key = normalizePath(changedKey);
75
79
  const seen = new Set<string>([key]);
@@ -79,10 +83,7 @@ export class DevGraph {
79
83
  const f = queue.pop()!;
80
84
  const node = this.nodes.get(f);
81
85
  if (!node) continue;
82
- if (node.isRoute) {
83
- hits.push(node.isRoute);
84
- continue;
85
- }
86
+ if (node.isRoute) hits.push(node.isRoute);
86
87
  for (const importer of node.importers) {
87
88
  if (!seen.has(importer)) {
88
89
  seen.add(importer);
@@ -167,7 +167,12 @@ export async function handleChange(
167
167
  // the edit may have added imports — pick them up before propagating
168
168
  await crawlFrom([filePath], { graph, projectRoot, aliases: ctx.aliases });
169
169
 
170
- const isClient = !isServerOnly(filePath);
170
+ // error pages render on the server only: compiling one for the browser can
171
+ // fail on code that never ships there, and a failure would throw the edit
172
+ // away before the SSR loader ever saw the new version
173
+ const reaches = graph.affectedRoutes(key);
174
+ const isClient =
175
+ !isServerOnly(filePath) && reaches.some((r) => r.type !== "error");
171
176
  let css: { hash: string; text: string } | null = null;
172
177
  let compiled: string | null = null;
173
178
 
@@ -206,7 +211,7 @@ export async function handleChange(
206
211
  );
207
212
  }
208
213
 
209
- const affected = graph.affectedRoutes(key);
214
+ const affected = reaches;
210
215
  if (affected.length === 0) {
211
216
  logger.info("no route reaches this module, reloading:", filePath);
212
217
  await fullReload(ctx);