@teyik0/furin 0.1.0-alpha.7 → 0.1.0-alpha.8

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.
@@ -26,17 +26,171 @@
26
26
  * Modules in a virtual namespace cannot resolve relative specifiers on their
27
27
  * own (there is no real directory context). We rewrite every `./` / `../`
28
28
  * path to an absolute one before returning the source.
29
+ *
30
+ * ## Bare specifier rewriting
31
+ *
32
+ * When `onLoad` returns `loader: "js"`, Bun resolves bare specifiers
33
+ * (e.g. `@teyik0/furin/link`, `shiki`) from the process CWD — not from the
34
+ * page file's directory. On a cold start the CWD and the file's directory
35
+ * often agree, but after `bun --hot` re-evaluates the server the module
36
+ * cache for project-local packages (like `packages/core/src/link.tsx`) may
37
+ * be cleared and re-loaded with a fresh React instance that diverges from the
38
+ * one already cached by `react-dom/server`. The result is the classic
39
+ * "two React copies" crash: `dispatcher.useState === null`.
40
+ *
41
+ * Fix: after transpilation, resolve every bare specifier from the page
42
+ * file's directory via `Bun.resolveSync` and replace it with the
43
+ * canonical on-disk path. This pins each import to exactly the same
44
+ * file-system location that Bun's native module resolver would choose,
45
+ * guaranteeing a single shared React instance regardless of CWD or
46
+ * hot-reload state.
47
+ *
48
+ * All import/re-export occurrences of each quoted specifier are replaced using
49
+ * a context-aware regex (requires a preceding `from` or `import` keyword) so
50
+ * that modules which both import and re-export from the same package are fully
51
+ * rewritten while string literals in non-import positions are left untouched.
29
52
  */
30
53
 
31
54
  import { dirname, resolve } from "node:path";
55
+ import { fileURLToPath } from "node:url";
32
56
 
33
57
  // Matches ?furin-server with an optional &t=<ms> cache-buster.
34
58
  const FURIN_SERVER_FILTER = /\?furin-server(?:&t=\d+)?$/;
35
59
  const ANY_FILTER = /.*/;
60
+ const WORKSPACE_SOURCE_FILTER =
61
+ /^(?!.*(?:\/node_modules\/|\/\.bun\/))(?!.*\.(?:test|spec)\.[jt]sx?$).*\.[jt]sx?$/;
36
62
  const T_PARAM_RE = /&t=(\d+)/;
37
63
  const STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
38
64
  const STRIP_T_PARAM_RE = /\?t=\d+$/;
39
65
 
66
+ type SourceLoader = "js" | "jsx" | "ts" | "tsx";
67
+
68
+ // ── Singleton package resolution ───────────────────────────────────────────────
69
+ //
70
+ // React (and react-dom) must be singletons: every module in the render graph
71
+ // must import the EXACT same object instance so that ReactSharedInternals.H
72
+ // (the hooks dispatcher) is shared between react-dom/server and the page.
73
+ //
74
+ // We resolve the absolute on-disk path once at module-evaluation time and
75
+ // rewrite every explicit import in the transpiled source to use that path.
76
+ // The auto-injected jsx-dev-runtime import (added by Bun.Transpiler AFTER the
77
+ // source is transformed) is handled by injectJsxHelperImports below.
78
+
79
+ /** React packages that must share a single instance across the module graph. */
80
+ const SINGLETON_PKGS = [
81
+ "react",
82
+ "react/jsx-runtime",
83
+ "react/jsx-dev-runtime",
84
+ "react-dom",
85
+ "react-dom/server",
86
+ "react-dom/client",
87
+ ] as const;
88
+
89
+ /** package specifier → absolute file path, resolved once at plugin registration time. */
90
+ const SINGLETON_PATHS = new Map<string, string>();
91
+ for (const pkg of SINGLETON_PKGS) {
92
+ try {
93
+ SINGLETON_PATHS.set(pkg, fileURLToPath(import.meta.resolve(pkg)));
94
+ } catch {
95
+ // Package not installed — skip (e.g. react-dom/client in a server-only env)
96
+ }
97
+ }
98
+
99
+ function escapeRegExp(s: string): string {
100
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
101
+ }
102
+
103
+ /**
104
+ * Rewrites bare React/react-dom singleton imports in source text to their
105
+ * absolute resolved paths. Handles explicit static import / re-export forms:
106
+ *
107
+ * import { useState } from "react" → import { useState } from "/abs/…"
108
+ * import type { FC } from "react"
109
+ * export { x } from "react"
110
+ * import "react/jsx-dev-runtime"
111
+ *
112
+ * Does NOT touch dynamic `import("react")` or `require("react")`.
113
+ *
114
+ * @internal exported for testing
115
+ */
116
+ export function rewriteSingletonImports(source: string): string {
117
+ let result = source;
118
+ for (const [pkg, absPath] of SINGLETON_PATHS) {
119
+ const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
120
+ result = result.replace(re, (_, g1: string) => `${g1}"${absPath}"`);
121
+ }
122
+ return result;
123
+ }
124
+
125
+ /**
126
+ * `Bun.Transpiler.transformSync` converts JSX syntax to function calls using
127
+ * mangled helper names (e.g. `jsxDEV_7x81h0kn`, `Fragment_8vg9x3sq`) but does
128
+ * NOT emit the corresponding import statement — it expects Bun's full bundler
129
+ * pipeline to inject it later.
130
+ *
131
+ * When we return pre-transpiled JS from `onLoad`, that pipeline step never
132
+ * runs, leaving the helpers as undefined free variables. This function scans
133
+ * the transpiled source, detects which mangled helper names are used, and
134
+ * prepends the correct import statements using absolute on-disk paths from
135
+ * `SINGLETON_PATHS`.
136
+ *
137
+ * Helper → package mapping:
138
+ * jsxDEV_* → `{ jsxDEV as … }` from react/jsx-dev-runtime
139
+ * Fragment_* → `{ Fragment as … }` from react/jsx-dev-runtime
140
+ * jsx_* → `{ jsx as … }` from react/jsx-runtime (prod only)
141
+ * jsxs_* → `{ jsxs as … }` from react/jsx-runtime (prod only)
142
+ *
143
+ * @internal exported for testing
144
+ */
145
+ export function injectJsxHelperImports(transpiled: string): string {
146
+ // Match mangled JSX helper names. Alternation order matters: try longer
147
+ // prefixes first so "jsxDEV_xxx" isn't partially matched as "jsx_xxx".
148
+ const JSX_HELPER_RE = /\b(jsxDEV|jsxs|jsx|Fragment)_([0-9a-z]{8})\b/g;
149
+
150
+ // Package → Map<varName, exportName>
151
+ const devRuntime = new Map<string, string>(); // react/jsx-dev-runtime
152
+ const prodRuntime = new Map<string, string>(); // react/jsx-runtime
153
+
154
+ for (const [, base, hash] of transpiled.matchAll(JSX_HELPER_RE)) {
155
+ if (!(base && hash)) {
156
+ continue;
157
+ }
158
+ const varName = `${base}_${hash}`;
159
+ if (base === "jsxDEV" || base === "Fragment") {
160
+ devRuntime.set(varName, base);
161
+ } else {
162
+ prodRuntime.set(varName, base);
163
+ }
164
+ }
165
+
166
+ const lines: string[] = [];
167
+
168
+ if (devRuntime.size > 0) {
169
+ const absPath = SINGLETON_PATHS.get("react/jsx-dev-runtime");
170
+ if (absPath) {
171
+ const specifiers = [...devRuntime.entries()]
172
+ .map(([varName, exportName]) => `${exportName} as ${varName}`)
173
+ .join(", ");
174
+ lines.push(`import { ${specifiers} } from "${absPath}";`);
175
+ }
176
+ }
177
+
178
+ if (prodRuntime.size > 0) {
179
+ const absPath = SINGLETON_PATHS.get("react/jsx-runtime");
180
+ if (absPath) {
181
+ const specifiers = [...prodRuntime.entries()]
182
+ .map(([varName, exportName]) => `${exportName} as ${varName}`)
183
+ .join(", ");
184
+ lines.push(`import { ${specifiers} } from "${absPath}";`);
185
+ }
186
+ }
187
+
188
+ if (lines.length === 0) {
189
+ return transpiled;
190
+ }
191
+ return `${lines.join("\n")}\n${transpiled}`;
192
+ }
193
+
40
194
  /**
41
195
  * Matches relative specifiers in all ESM import / re-export forms:
42
196
  *
@@ -64,6 +218,118 @@ export function rewriteRelativeImports(source: string, dir: string): string {
64
218
  });
65
219
  }
66
220
 
221
+ /**
222
+ * Rewrites all remaining bare specifiers in the transpiled JS to absolute
223
+ * on-disk paths resolved from `dir` (the page file's directory).
224
+ *
225
+ * Uses `Bun.Transpiler.scan()` on the original source to get the authoritative
226
+ * list of *actual* import specifiers (parsing correctly handles template
227
+ * literals, comments, etc.). For each bare specifier that is not already
228
+ * handled by `rewriteSingletonImports`, it calls `Bun.resolveSync` and
229
+ * replaces **every** import/re-export occurrence of the quoted specifier using
230
+ * a context-aware regex with the `g` flag — mirroring the approach used by
231
+ * `rewriteSingletonImports`. This correctly handles modules that both import
232
+ * and re-export from the same package without leaving any bare specifier
233
+ * behind. String literals that happen to contain the same text (inside
234
+ * template literals, JSX props, etc.) are not touched because the regex
235
+ * requires a preceding `from` or `import` keyword.
236
+ *
237
+ * @internal exported for testing
238
+ */
239
+ export function rewriteBareImports(source: string, transpiled: string, dir: string): string {
240
+ const scanner = new Bun.Transpiler({ loader: "tsx" });
241
+ let { imports } = scanner.scan(source);
242
+ // Deduplicate: scan() may return the same specifier multiple times if it
243
+ // appears in both `import` and `export ... from` positions.
244
+ const seen = new Set<string>();
245
+ imports = imports.filter((imp) => {
246
+ if (seen.has(imp.path)) {
247
+ return false;
248
+ }
249
+ seen.add(imp.path);
250
+ return true;
251
+ });
252
+
253
+ let result = transpiled;
254
+ for (const imp of imports) {
255
+ const spec = imp.path;
256
+ // Skip relative paths (already rewritten by rewriteRelativeImports before transpilation)
257
+ // and already-absolute paths.
258
+ if (spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("file:")) {
259
+ continue;
260
+ }
261
+ // Skip React singletons — already handled by rewriteSingletonImports.
262
+ if (SINGLETON_PATHS.has(spec)) {
263
+ continue;
264
+ }
265
+
266
+ let resolved: string;
267
+ try {
268
+ resolved = Bun.resolveSync(spec, dir);
269
+ } catch {
270
+ // Not resolvable from the file's directory — leave as a bare specifier
271
+ // so Bun falls back to CWD-relative resolution (adequate for most cases).
272
+ continue;
273
+ }
274
+
275
+ // Replace ALL import/re-export occurrences of the bare specifier using a
276
+ // context-aware regex with the `g` flag. This correctly handles modules
277
+ // that both import and re-export from the same package. The regex only
278
+ // matches when the specifier is preceded by `from` or `import` so string
279
+ // literals in non-import positions are left untouched.
280
+ const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
281
+ result = result.replace(re, (_, g1: string) => `${g1}"${resolved}"`);
282
+ }
283
+ return result;
284
+ }
285
+
286
+ function getSourceLoader(filePath: string): SourceLoader | null {
287
+ if (filePath.endsWith(".tsx")) {
288
+ return "tsx";
289
+ }
290
+ if (filePath.endsWith(".ts")) {
291
+ return "ts";
292
+ }
293
+ if (filePath.endsWith(".jsx")) {
294
+ return "jsx";
295
+ }
296
+ if (filePath.endsWith(".js")) {
297
+ return "js";
298
+ }
299
+ return null;
300
+ }
301
+
302
+ function shouldSkipWorkspaceTransform(filePath: string): boolean {
303
+ const normalized = filePath.replace(/\\/g, "/");
304
+ return normalized.includes("/.furin/");
305
+ }
306
+
307
+ function transformDevSource(
308
+ raw: string,
309
+ filePath: string,
310
+ options: { rewriteBareImports: boolean; rewriteRelativeImports: boolean }
311
+ ): string {
312
+ const loader = getSourceLoader(filePath);
313
+ if (!loader) {
314
+ throw new Error(`[furin] Unsupported source loader for ${filePath}`);
315
+ }
316
+
317
+ const dir = dirname(filePath);
318
+ const sourceForTranspile = options.rewriteRelativeImports
319
+ ? rewriteRelativeImports(raw, dir)
320
+ : raw;
321
+ const transpiler = new Bun.Transpiler({ loader });
322
+ const transpiled = transpiler.transformSync(sourceForTranspile, loader);
323
+
324
+ let result = transpiled;
325
+ if (options.rewriteBareImports) {
326
+ result = rewriteBareImports(raw, result, dir);
327
+ }
328
+
329
+ result = rewriteSingletonImports(result);
330
+ return injectJsxHelperImports(result);
331
+ }
332
+
67
333
  export function registerDevPagePlugin(): void {
68
334
  Bun.plugin({
69
335
  name: "furin-dev-page-loader",
@@ -79,19 +345,88 @@ export function registerDevPagePlugin(): void {
79
345
  return { path: resolvedPath, namespace: "furin-dev-page" };
80
346
  });
81
347
 
348
+ /**
349
+ * Workspace source files (root.tsx, _route.tsx, local components, core
350
+ * packages, etc.) still load through Bun's normal file namespace in dev.
351
+ *
352
+ * After bun --hot re-evaluates part of that graph, those modules can
353
+ * re-import React through a different logical path than react-dom/server,
354
+ * which recreates the classic "dispatcher is null" invalid hook crash.
355
+ *
356
+ * Pre-transpile those files and rewrite only the React singleton imports
357
+ * so every SSR module observes the exact same React instance, while still
358
+ * keeping the files in Bun's watched graph for root.tsx HMR.
359
+ */
360
+ build.onLoad({ filter: WORKSPACE_SOURCE_FILTER }, async (args) => {
361
+ const raw = await Bun.file(args.path).text();
362
+ const loader = getSourceLoader(args.path);
363
+ if (!loader) {
364
+ throw new Error(`[furin] Unsupported source loader for ${args.path}`);
365
+ }
366
+
367
+ if (shouldSkipWorkspaceTransform(args.path)) {
368
+ return {
369
+ contents: raw,
370
+ loader,
371
+ };
372
+ }
373
+
374
+ const contents = transformDevSource(raw, args.path, {
375
+ rewriteBareImports: false,
376
+ rewriteRelativeImports: false,
377
+ });
378
+
379
+ return {
380
+ contents,
381
+ loader: "js",
382
+ };
383
+ });
384
+
82
385
  /**
83
386
  * Read the page file fresh from disk. The `?t=...` suffix guarantees
84
387
  * this handler is called on every request; strip it before file I/O.
85
- * Return the raw TypeScript/TSX source — Bun transpiles it correctly
86
- * (including JSX runtime helpers) when given `loader: "tsx"`.
388
+ *
389
+ * ## Why we pre-transpile with Bun.Transpiler
390
+ *
391
+ * Bun's runtime plugin system (used by `bun --hot`) does NOT route
392
+ * sub-imports from virtual-namespace modules through `onResolve` hooks —
393
+ * the `namespace` filter on `onResolve` only works in the bundler context
394
+ * (`Bun.build()`), not in the runtime module loader. This means two
395
+ * classes of specifiers inside a `furin-dev-page` module cannot be
396
+ * intercepted after the fact:
397
+ *
398
+ * 1. **Relative imports** (`./root`, `../utils`) — no real directory
399
+ * context in the virtual namespace → Bun fails to resolve them.
400
+ * 2. **Auto-injected JSX runtime** — `import { jsx } from
401
+ * "react/jsx-dev-runtime"` added by Bun's TSX transpiler AFTER
402
+ * `onLoad` returns → cannot be rewritten in the source text.
403
+ *
404
+ * Solution: pre-transpile the source with `Bun.Transpiler` ourselves,
405
+ * then rewrite all specifiers in the resulting JS text before returning
406
+ * it with `loader: "js"` (which Bun loads as-is, with no further
407
+ * transpilation or automatic import injection):
408
+ *
409
+ * • `rewriteRelativeImports` → converts `./root` to `/abs/path/root`
410
+ * • `rewriteBareImports` → resolves ALL bare specifiers (including
411
+ * `@teyik0/furin/link`, `shiki`, etc.) to canonical absolute paths
412
+ * from the page file's directory, preventing "two React copies" after
413
+ * bun --hot re-evaluation.
414
+ * • `rewriteSingletonImports` → belt-and-suspenders for react singletons
415
+ * (covered by rewriteBareImports but kept for safety).
416
+ * • `injectJsxHelperImports` → adds the JSX helper imports that
417
+ * `Bun.Transpiler` emits as free variables without corresponding imports.
87
418
  */
88
419
  build.onLoad({ namespace: "furin-dev-page", filter: ANY_FILTER }, async (args) => {
89
420
  const filePath = args.path.replace(STRIP_T_PARAM_RE, "");
90
421
  const raw = await Bun.file(filePath).text();
91
- const contents = rewriteRelativeImports(raw, dirname(filePath));
422
+ const contents = transformDevSource(raw, filePath, {
423
+ rewriteBareImports: true,
424
+ rewriteRelativeImports: true,
425
+ });
426
+
92
427
  return {
93
428
  contents,
94
- loader: filePath.endsWith(".tsx") ? "tsx" : "ts",
429
+ loader: "js", // Already fully transpiled — skip Bun's own TSX step.
95
430
  };
96
431
  });
97
432
  },
package/src/furin.ts CHANGED
@@ -236,7 +236,11 @@ export async function furin({
236
236
  const { root, routes } = await scanPages(resolvedPagesDir);
237
237
 
238
238
  const { writeDevFiles } = await import("./build/hydrate.ts");
239
- writeDevFiles(routes, { outDir: furinDir, rootLayout: root.path }, cwd);
239
+ writeDevFiles(
240
+ routes,
241
+ { outDir: furinDir, rootLayout: root.path, basePath: "", publicPath: "/_client/" },
242
+ cwd
243
+ );
240
244
 
241
245
  const publicDir = resolve(cwd, "public");
242
246
  const publicExists = existsSync(publicDir);
@@ -250,7 +254,7 @@ export async function furin({
250
254
  set.headers["x-furin-revalidate"] = pending.join(",");
251
255
  }
252
256
  })
253
- .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry" }))
257
+ .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
254
258
  .use(
255
259
  publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
256
260
  )