@sigil-dev/grimoire 0.9.4 → 0.9.5

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 (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +42 -20
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +10 -6
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +295 -298
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,187 +1,261 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import { join, relative } from "node:path";
3
- import type { ServerWebSocket } from "bun";
4
- import { log } from "../logger/instance";
5
- import { compileForBrowser } from "./compile-module";
6
- import type { DevGraph } from "./graph";
7
- import { normalizePath } from "./paths";
8
- import { safeRead } from "./watcher";
9
-
10
- const logger = log.scope("hmr");
11
-
12
- export class HmrServer {
13
- private clients = new Set<ServerWebSocket<any>>();
14
- private v = 0;
15
- get clientCount() {
16
- return this.clients.size;
17
- }
18
- addClient(ws: ServerWebSocket<any>) {
19
- this.clients.add(ws);
20
- ws.send(JSON.stringify({ type: "connected" }));
21
- }
22
-
23
- removeClient(ws: ServerWebSocket<any>) {
24
- this.clients.delete(ws);
25
- }
26
-
27
- send(msg: object) {
28
- const s = JSON.stringify(msg);
29
- for (const c of this.clients) c.send(s);
30
- }
31
-
32
- batch(payloads: object[]) {
33
- this.send({ type: "batch", payloads, v: ++this.v });
34
- }
35
-
36
- reload() {
37
- logger.info("sending reload to", this.clients.size, "clients");
38
- this.batch([{ kind: "reload" }]);
39
- }
40
-
41
- error(message: string, loc?: { file: string; line: number; col: number }) {
42
- this.send({ type: "error", message, loc });
43
- }
44
- }
45
-
46
- function extractLoc(
47
- e: any,
48
- filePath: string,
49
- ): { file: string; line: number; col: number } | undefined {
50
- // Babel errors have e.loc.line / e.loc.column
51
- if (e?.loc?.line) {
52
- return {
53
- file: filePath,
54
- line: e.loc.line,
55
- col: e.loc.column ?? 0,
56
- };
57
- }
58
- // fallback: parse "file:line:col" from message
59
- const m = String(e?.message ?? "").match(/:(\d+):(\d+)$/);
60
- if (m) {
61
- return {
62
- file: filePath,
63
- line: Number(m[1]),
64
- col: Number(m[2]),
65
- };
66
- }
67
- return undefined;
68
- }
69
-
70
- export async function compileAndSwap(
71
- filePath: string,
72
- graph: DevGraph,
73
- hmr: HmrServer,
74
- projectRoot: string,
75
- _routeTree: any,
76
- ): Promise<void> {
77
- const key = normalizePath(filePath);
78
- const node = graph.get(key);
79
-
80
- try {
81
- const result = await compileForBrowser(filePath, projectRoot);
82
-
83
- // write to dev-modules cache
84
- const devModulesDir = join(projectRoot, ".grimoire/dev-modules");
85
- mkdirSync(devModulesDir, { recursive: true });
86
- const { createHash } = await import("node:crypto");
87
- const fileHash = createHash("md5")
88
- .update(filePath)
89
- .digest("hex")
90
- .slice(0, 8);
91
- const v = graph.bump(key);
92
- const cachePath = join(devModulesDir, `${fileHash}_v${v}.js`);
93
- writeFileSync(cachePath, result.js);
94
-
95
- // store in graph node
96
- if (node) {
97
- node.compiled = {
98
- js: result.js,
99
- css: result.css,
100
- cssHash: result.cssHash,
101
- specifiers: [], // populated in Step 4
102
- };
103
- }
104
-
105
- // find affected route pattern
106
- const affectedRoutes = graph.affectedRoutes(key);
107
- const routeFile = node?.isRoute ?? affectedRoutes[0] ?? null;
108
-
109
- if (!routeFile) {
110
- // no route found — fall back to reload
111
- logger.info("no route affected, reloading");
112
- hmr.reload();
113
- return;
114
- }
115
-
116
- // client-relative path for the module URL
117
- const clientPath = relative(projectRoot, filePath).replace(/\\/g, "/");
118
- const modUrl = `${clientPath}.js`;
119
-
120
- logger.info(`compiled: ${filePath}, v=${v}`);
121
-
122
- const payloads: object[] = [];
123
-
124
- // CSS payload if style changed
125
- if (result.css) {
126
- payloads.push({
127
- kind: "css",
128
- hash: result.cssHash,
129
- text: result.css,
130
- });
131
- }
132
-
133
- // swap payload
134
- payloads.push({
135
- kind: "swap",
136
- pattern: routeFile.path,
137
- modUrl,
138
- version: v,
139
- cachePath: `${fileHash}_v${v}.js`, // server-side cache filename
140
- });
141
-
142
- // stale payloads for other affected routes
143
- const otherRoutes = affectedRoutes.filter((r) => r !== routeFile);
144
- if (otherRoutes.length > 0) {
145
- payloads.push({
146
- kind: "stale",
147
- patterns: otherRoutes.map((r) => r.path),
148
- });
149
- }
150
- logger.info("sending batch:", JSON.stringify(payloads, null, 2));
151
- hmr.batch(payloads);
152
- } catch (e: any) {
153
- const loc = extractLoc(e, filePath);
154
- console.error("[sigil hmr] compile error:", e.message);
155
- hmr.error(e.message ?? String(e), loc);
156
- // no bump — old version stays live
157
- }
158
- }
159
-
160
- export async function handleChange(
161
- filePath: string,
162
- graph: DevGraph,
163
- hmr: HmrServer,
164
- _srcDir: string,
165
- projectRoot: string,
166
- routeTree: any,
167
- ): Promise<void> {
168
- const key = normalizePath(filePath);
169
- const source = await safeRead(filePath);
170
- if (!source) {
171
- hmr.reload();
172
- return;
173
- }
174
- if (graph.hasCycle(key)) {
175
- hmr.reload();
176
- return;
177
- }
178
- const node = graph.get(key);
179
- if (!node) {
180
- logger.info("unknown file, reloading:", filePath);
181
- hmr.reload();
182
- return;
183
- }
184
-
185
- logger.info("changed:", filePath);
186
- await compileAndSwap(filePath, graph, hmr, projectRoot, routeTree);
187
- }
1
+ import { relative } from "node:path";
2
+ import type { ServerWebSocket } from "bun";
3
+ import { log } from "../logger/instance";
4
+ import { cacheDevModule, compileForBrowser } from "./compile-module";
5
+ import type { DevGraph } from "./graph";
6
+ import { normalizePath } from "./paths";
7
+ import { isServerOnly, isSourceFile } from "./resolve";
8
+ import { crawlFrom } from "./scan";
9
+ import { safeRead } from "./watcher";
10
+
11
+ const logger = log.scope("hmr");
12
+
13
+ export class HmrServer {
14
+ private clients = new Set<ServerWebSocket<unknown>>();
15
+ private v = 0;
16
+ get clientCount() {
17
+ return this.clients.size;
18
+ }
19
+ addClient(ws: ServerWebSocket<unknown>) {
20
+ this.clients.add(ws);
21
+ ws.send(JSON.stringify({ type: "connected" }));
22
+ }
23
+
24
+ removeClient(ws: ServerWebSocket<unknown>) {
25
+ this.clients.delete(ws);
26
+ }
27
+
28
+ send(msg: object) {
29
+ const s = JSON.stringify(msg);
30
+ for (const c of this.clients) c.send(s);
31
+ }
32
+
33
+ batch(payloads: object[]) {
34
+ this.send({ type: "batch", payloads, v: ++this.v });
35
+ }
36
+
37
+ reload() {
38
+ logger.info("sending reload to", this.clients.size, "clients");
39
+ this.batch([{ kind: "reload" }]);
40
+ }
41
+
42
+ error(message: string, loc?: { file: string; line: number; col: number }) {
43
+ this.send({ type: "error", message, loc });
44
+ }
45
+ }
46
+
47
+ interface ErrorLoc {
48
+ file: string;
49
+ line: number;
50
+ col: number;
51
+ }
52
+
53
+ function extractLoc(e: unknown, filePath: string): ErrorLoc | undefined {
54
+ // Babel errors carry loc.line / loc.column
55
+ if (e && typeof e === "object" && "loc" in e) {
56
+ const loc = e.loc;
57
+ if (loc && typeof loc === "object" && "line" in loc) {
58
+ const line = Number(loc.line);
59
+ const col = "column" in loc ? Number(loc.column) : 0;
60
+ if (Number.isFinite(line))
61
+ return { file: filePath, line, col: Number.isFinite(col) ? col : 0 };
62
+ }
63
+ }
64
+ // fallback: parse a trailing "file:line:col" out of the message
65
+ const m = errorMessage(e).match(/:(\d+):(\d+)$/);
66
+ return m
67
+ ? { file: filePath, line: Number(m[1]), col: Number(m[2]) }
68
+ : undefined;
69
+ }
70
+
71
+ function errorMessage(e: unknown): string {
72
+ if (e instanceof Error) return e.message;
73
+ if (e && typeof e === "object" && "message" in e) return String(e.message);
74
+ return String(e);
75
+ }
76
+
77
+ export interface DevContext {
78
+ graph: DevGraph;
79
+ hmr: HmrServer;
80
+ projectRoot: string;
81
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
82
+ aliases: Record<string, string>;
83
+ /** Route/layout/server files the graph is crawled from. */
84
+ entries: () => string[];
85
+ /**
86
+ * Rescan routes and rebuild the client bundles. Awaited before a full
87
+ * reload: `hydrate.js` is built once at startup, so reloading without a
88
+ * rebuild would serve the browser the code from before the edit.
89
+ */
90
+ rebuild: () => Promise<void>;
91
+ /**
92
+ * Same rebuild, off the critical path. Runs after a hot swap so that a
93
+ * later manual refresh — which loads the prebuilt bundle, not the swapped
94
+ * modules — shows the same code the running page already has.
95
+ */
96
+ scheduleRebuild: () => void;
97
+ }
98
+
99
+ /** `src/lib/Card.tsx` → the `/__grimoire__/m/` path the client imports. */
100
+ const clientModulePath = (filePath: string, projectRoot: string): string =>
101
+ `${relative(projectRoot, filePath).replace(/\\/g, "/")}.js`;
102
+
103
+ interface RouteEntryPayload {
104
+ pattern: string;
105
+ modUrl: string;
106
+ version: number;
107
+ }
108
+
109
+ interface LayoutEntryPayload {
110
+ path: string;
111
+ modUrl: string;
112
+ version: number;
113
+ }
114
+
115
+ /**
116
+ * Does an edit to this file change what a `load` returns? Route modules own
117
+ * their data loaders, so a swap alone would re-render the new component
118
+ * against data produced by the old loader.
119
+ */
120
+ function affectsData(filePath: string, source: string): boolean {
121
+ if (isServerOnly(filePath)) return true;
122
+ return /\bexport\s+(async\s+)?(function\s+load\b|const\s+load\b|const\s+actions\b|function\s+canMatch\b|const\s+canMatch\b)/.test(
123
+ source,
124
+ );
125
+ }
126
+
127
+ async function fullReload(ctx: DevContext): Promise<void> {
128
+ await ctx.rebuild();
129
+ ctx.hmr.reload();
130
+ }
131
+
132
+ export async function handleChange(
133
+ filePath: string,
134
+ ctx: DevContext,
135
+ ): Promise<void> {
136
+ const { graph, hmr, projectRoot } = ctx;
137
+ const key = normalizePath(filePath);
138
+
139
+ if (!isSourceFile(filePath)) {
140
+ logger.info("non-source change, reloading:", filePath);
141
+ await fullReload(ctx);
142
+ return;
143
+ }
144
+
145
+ const source = await safeRead(filePath);
146
+ if (source === null) {
147
+ // deleted or unreadable — the module graph can't be trusted any more
148
+ await fullReload(ctx);
149
+ return;
150
+ }
151
+
152
+ if (!graph.get(key)) {
153
+ // a brand-new file, or one that just became imported: recrawl from the
154
+ // route entries before giving up on a targeted update
155
+ await crawlFrom(ctx.entries(), {
156
+ graph,
157
+ projectRoot,
158
+ aliases: ctx.aliases,
159
+ });
160
+ }
161
+ if (!graph.get(key)) {
162
+ logger.info("file outside the route graph, reloading:", filePath);
163
+ await fullReload(ctx);
164
+ return;
165
+ }
166
+
167
+ // the edit may have added imports — pick them up before propagating
168
+ await crawlFrom([filePath], { graph, projectRoot, aliases: ctx.aliases });
169
+
170
+ const isClient = !isServerOnly(filePath);
171
+ let css: { hash: string; text: string } | null = null;
172
+ let compiled: string | null = null;
173
+
174
+ if (isClient) {
175
+ // compile the edited source before bumping anything: on a syntax error
176
+ // the overlay goes up and every previous version stays live, in the
177
+ // browser and in SSR alike. Never read the cache here — the whole point
178
+ // is to see what the developer just typed.
179
+ try {
180
+ const result = await compileForBrowser(filePath, {
181
+ projectRoot,
182
+ aliases: ctx.aliases,
183
+ graph,
184
+ });
185
+ compiled = result.js;
186
+ if (result.css) css = { hash: result.cssHash, text: result.css };
187
+ } catch (e: unknown) {
188
+ const message = errorMessage(e);
189
+ logger.error("compile error:", message);
190
+ hmr.error(message, extractLoc(e, filePath));
191
+ return;
192
+ }
193
+ }
194
+
195
+ // bump this module and every importer up to the routes, invalidating the
196
+ // SSR loader's cache and every stamped browser URL along the way
197
+ graph.invalidate(key);
198
+ if (compiled !== null) {
199
+ // dep versions are untouched by the bump, so the output just compiled
200
+ // is exactly what this new version should serve
201
+ cacheDevModule(
202
+ filePath,
203
+ graph.get(key)?.version ?? 0,
204
+ projectRoot,
205
+ compiled,
206
+ );
207
+ }
208
+
209
+ const affected = graph.affectedRoutes(key);
210
+ if (affected.length === 0) {
211
+ logger.info("no route reaches this module, reloading:", filePath);
212
+ await fullReload(ctx);
213
+ return;
214
+ }
215
+
216
+ const routeEntries: RouteEntryPayload[] = [];
217
+ const layoutEntries: LayoutEntryPayload[] = [];
218
+ let serverTouched = false;
219
+ let needsReload = false;
220
+
221
+ for (const route of affected) {
222
+ const modUrl = clientModulePath(route.filePath, projectRoot);
223
+ const version = graph.get(route.filePath)?.version ?? 0;
224
+ if (route.type === "page" || route.type === "simple") {
225
+ routeEntries.push({ pattern: route.path, modUrl, version });
226
+ } else if (route.type === "layout") {
227
+ layoutEntries.push({ path: route.path, modUrl, version });
228
+ } else if (route.type === "error") {
229
+ // error pages are never in the client route table — only a document
230
+ // request re-renders one
231
+ needsReload = true;
232
+ } else {
233
+ // +page.server / +layout.server / +server: nothing the client can
234
+ // swap, but the data behind the current page just changed
235
+ serverTouched = true;
236
+ }
237
+ }
238
+
239
+ if (needsReload) {
240
+ await fullReload(ctx);
241
+ return;
242
+ }
243
+
244
+ const payloads: object[] = [];
245
+ if (css) payloads.push({ kind: "css", ...css });
246
+ if (routeEntries.length)
247
+ payloads.push({ kind: "routes", entries: routeEntries });
248
+ if (layoutEntries.length)
249
+ payloads.push({ kind: "layouts", entries: layoutEntries });
250
+ if (serverTouched || affectsData(filePath, source))
251
+ payloads.push({ kind: "invalidate" });
252
+
253
+ const summary = affected.map((r) => `${r.type} ${r.path}`).join(", ");
254
+ logger.info(
255
+ `changed ${relative(projectRoot, filePath).replace(/\\/g, "/")} → ${summary}`,
256
+ );
257
+ hmr.batch(payloads);
258
+ // the prebuilt bundles still hold pre-edit code; refresh them so a manual
259
+ // reload agrees with the hot-swapped page
260
+ ctx.scheduleRebuild();
261
+ }
package/src/dev/loader.ts CHANGED
@@ -1,47 +1,120 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { disposeModuleEffects } from "./effect-registry";
5
- import type { DevGraph } from "./graph";
6
- import { normalizePath } from "./paths";
7
-
8
- export function makeDevLoader(graph: DevGraph, projectRoot: string) {
9
- const cacheDir = join(projectRoot, ".grimoire/dev-cache");
10
- mkdirSync(cacheDir, { recursive: true });
11
-
12
- return async function devLoadModule(filePath: string): Promise<any> {
13
- const key = normalizePath(filePath);
14
- disposeModuleEffects(key);
15
- const v = graph.get(key)?.version ?? 0;
16
-
17
- if (v === 0) {
18
- // first load — let Bun handle it normally via SSR plugin
19
- return import(filePath);
20
- }
21
-
22
- // versioned load — read the source, let the SSR plugin transform it,
23
- // write transformed output to a unique cache path, import that
24
- // We can't re-trigger the plugin, so we invoke the compile pipeline directly
25
- const source = await Bun.file(filePath).text();
26
- const { transformSync } = await import("@babel/core");
27
- const sigilPlugin = (await import("@sigil-dev/compiler/babel")).default;
28
- const { createHash } = await import("node:crypto");
29
- const hash = createHash("md5").update(filePath).digest("hex").slice(0, 8);
30
-
31
- const result = transformSync(source, {
32
- configFile: false,
33
- babelrc: false,
34
- parserOpts: { plugins: ["typescript", "jsx"] },
35
- plugins: [[sigilPlugin, { mode: "ssr", hash }]],
36
- filename: filePath,
37
- });
38
-
39
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
40
- const compiled = transpiler.transformSync(result?.code ?? "");
41
-
42
- const cachePath = join(cacheDir, `${hash}_v${v}.js`);
43
- writeFileSync(cachePath, compiled);
44
-
45
- return import(pathToFileURL(cachePath).href);
46
- };
47
- }
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 { disposeModuleEffects } from "./effect-registry";
8
+ import type { DevGraph } from "./graph";
9
+ import { normalizePath } from "./paths";
10
+ import { isSourceFile, resolveProjectImport } from "./resolve";
11
+
12
+ export interface DevLoaderOptions {
13
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
14
+ aliases?: Record<string, string>;
15
+ }
16
+
17
+ /**
18
+ * Module loader for dev SSR.
19
+ *
20
+ * Bun caches every module it imports for the process lifetime, so a changed
21
+ * file can only be re-executed under a fresh path. Each edited module (and
22
+ * each importer of one, since the graph bumps them together) is recompiled
23
+ * into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
24
+ * rewritten to the versioned files of its dependencies — otherwise a
25
+ * recompiled page would keep importing the cached copy of the component that
26
+ * was just edited.
27
+ */
28
+ export function makeDevLoader(
29
+ graph: DevGraph,
30
+ projectRoot: string,
31
+ options: DevLoaderOptions = {},
32
+ ) {
33
+ const cacheDir = join(projectRoot, ".grimoire/dev-cache");
34
+ const aliases = options.aliases ?? {};
35
+ // a previous session's cache cannot be trusted: same path, same version
36
+ // number, different source
37
+ rmSync(cacheDir, { recursive: true, force: true });
38
+ mkdirSync(cacheDir, { recursive: true });
39
+
40
+ /** Cache files this process has already written, by path. */
41
+ const written = new Set<string>();
42
+
43
+ const materialize = async (filePath: string): Promise<string> => {
44
+ const version = graph.get(filePath)?.version ?? 0;
45
+ // untouched since startup: the SSR plugin handles the source directly
46
+ if (version === 0) return pathToFileURL(filePath).href;
47
+
48
+ const hash = createHash("md5")
49
+ .update(normalizePath(filePath))
50
+ .digest("hex")
51
+ .slice(0, 8);
52
+ const cachePath = join(cacheDir, `${hash}_v${version}.js`);
53
+ const href = pathToFileURL(cachePath).href;
54
+ // (file, version) is immutable within a session; import cycles reach
55
+ // the same deterministic path, and the outer call writes it
56
+ if (written.has(cachePath)) return href;
57
+ written.add(cachePath);
58
+
59
+ try {
60
+ const source = await Bun.file(filePath).text();
61
+ const babelResult = transformSync(source, {
62
+ configFile: false,
63
+ babelrc: false,
64
+ parserOpts: { plugins: ["typescript", "jsx"] },
65
+ plugins: [[sigilPlugin, { mode: "ssr", hash }]],
66
+ filename: filePath,
67
+ });
68
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
69
+ let compiled = transpiler.transformSync(babelResult?.code ?? "");
70
+ compiled = await rewriteSpecifiers(compiled, async (specifier) => {
71
+ const resolved = resolveProjectImport(
72
+ specifier,
73
+ filePath,
74
+ projectRoot,
75
+ aliases,
76
+ );
77
+ // externals keep their specifier: node_modules resolution walks
78
+ // up from the cache dir to the project root all the same
79
+ if (!resolved || !isSourceFile(resolved)) return null;
80
+ return await materialize(resolved);
81
+ });
82
+ mkdirSync(cacheDir, { recursive: true });
83
+ writeFileSync(cachePath, compiled);
84
+ } catch (e) {
85
+ // let the next request retry instead of importing a half-written file
86
+ written.delete(cachePath);
87
+ throw e;
88
+ }
89
+ return href;
90
+ };
91
+
92
+ return async function devLoadModule(filePath: string): Promise<unknown> {
93
+ disposeModuleEffects(normalizePath(filePath));
94
+ return import(await materialize(filePath));
95
+ };
96
+ }
97
+
98
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
99
+
100
+ /** Replace every import specifier for which `resolve` returns a new one. */
101
+ async function rewriteSpecifiers(
102
+ code: string,
103
+ resolve: (specifier: string) => Promise<string | null>,
104
+ ): Promise<string> {
105
+ const replacements = new Map<string, string>();
106
+ for (const match of code.matchAll(SPEC_RE)) {
107
+ const specifier = match[3]!;
108
+ if (replacements.has(specifier)) continue;
109
+ const next = await resolve(specifier);
110
+ if (next) replacements.set(specifier, next);
111
+ }
112
+ if (replacements.size === 0) return code;
113
+ return code.replace(
114
+ SPEC_RE,
115
+ (match, keyword: string, quote: string, specifier: string) => {
116
+ const next = replacements.get(specifier);
117
+ return next ? `${keyword}${quote}${next}${quote}` : match;
118
+ },
119
+ );
120
+ }
package/src/dev/paths.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { resolve } from "node:path";
2
-
3
- export function normalizePath(p: string) {
4
- let n = resolve(p).replace(/\\/g, "/");
5
- if (process.platform === "win32") n = n.toLowerCase();
6
- return n;
7
- }
8
-
9
- export function keyFromUrl(pathname: string, prefix: string) {
10
- // __grimoire__/m/src/lib/Example.tsx.js -> src/lib/Example.tsx
11
- return decodeURIComponent(pathname.slice(prefix.length))
12
- .replace(/\.js(\?.*)?$/, "")
13
- .replace(/\\/g, "");
14
- }
1
+ import { resolve } from "node:path";
2
+
3
+ export function normalizePath(p: string) {
4
+ let n = resolve(p).replace(/\\/g, "/");
5
+ if (process.platform === "win32") n = n.toLowerCase();
6
+ return n;
7
+ }
8
+
9
+ export function keyFromUrl(pathname: string, prefix: string) {
10
+ // __grimoire__/m/src/lib/Example.tsx.js -> src/lib/Example.tsx
11
+ return decodeURIComponent(pathname.slice(prefix.length))
12
+ .replace(/\.js(\?.*)?$/, "")
13
+ .replace(/\\/g, "");
14
+ }