@teyik0/furin 0.1.0-alpha.8 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4734 -548
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4713 -549
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +54 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5288 -601
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/server/context-logger.d.ts +28 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -4
  68. package/{src → dist/server}/render/shell.ts +31 -9
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +83 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +83 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/server/context-logger.ts +76 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1173
  163. package/dist/render/assemble.d.ts +0 -13
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -34
  169. package/dist/router.js +0 -830
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1035
  172. package/src/render/assemble.ts +0 -64
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -479
  176. package/src/render/loaders.ts +0 -113
  177. package/src/router.ts +0 -400
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
package/src/furin.ts CHANGED
@@ -5,18 +5,27 @@ import { staticPlugin } from "@elysiajs/static";
5
5
  import { type AnyElysia, Elysia, file } from "elysia";
6
6
  import { type DrainContext, initLogger } from "evlog";
7
7
  import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
- import type { EmbeddedAppData } from "./internal.ts";
9
- import { getCompileContext } from "./internal.ts";
10
8
  import {
11
9
  _runWithRequestInvalidationScope,
12
10
  consumePendingInvalidations,
13
11
  getBuildId,
14
12
  setBuildId,
15
- } from "./render/cache.ts";
16
- import { warmSSGCache } from "./render/index.ts";
17
- import { setProductionTemplateContent, setProductionTemplatePath } from "./render/template.ts";
18
- import { createRoutePlugin, loadProdRoutes } from "./router.ts";
19
- import { IS_DEV } from "./runtime-env.ts";
13
+ } from "./server/cache/invalidation.ts";
14
+ import { setSSGCache } from "./server/cache/ssg.ts";
15
+ import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
+ import { getCompileContext } from "./server/internal.ts";
17
+ import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
+ import {
19
+ setProductionTemplateContent,
20
+ setProductionTemplatePath,
21
+ } from "./server/render/template.ts";
22
+ import { createDataEndpoint, createRoutePlugin, loadProdRoutes } from "./server/router/index.ts";
23
+ import { IS_DEV } from "./server/runtime-env.ts";
24
+
25
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
26
+ export interface FurinCacheTags {}
27
+
28
+ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
20
29
 
21
30
  function resolveClientDirFromArgv(): string {
22
31
  return (
@@ -134,6 +143,32 @@ async function setupProdTemplate(
134
143
  setProductionTemplatePath(templatePath);
135
144
  }
136
145
 
146
+ /**
147
+ * Registers a HigherOrderFunction on the Elysia instance so that every request
148
+ * runs inside a fresh `AsyncLocalStorage` scope. This isolates
149
+ * `pendingInvalidations` per request, preventing concurrent requests from
150
+ * stealing each other's `revalidatePath()` calls.
151
+ *
152
+ * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
153
+ * `app.handle`, because handle mutations are lost when the Furin plugin is
154
+ * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
155
+ * plugin merge and wrap the entire composed `map` handler.
156
+ */
157
+ function wrapWithRequestScope(app: AnyElysia): Elysia {
158
+ return app.wrap(
159
+ (handler, _request) => (ctx: unknown) => _runWithRequestInvalidationScope(() => handler(ctx))
160
+ );
161
+ }
162
+
163
+ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
164
+ if (!ctx.ssgCache) {
165
+ return;
166
+ }
167
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
168
+ setSSGCache(path, entry);
169
+ }
170
+ }
171
+
137
172
  /**
138
173
  * Main Furin plugin.
139
174
  *
@@ -148,25 +183,20 @@ async function setupProdTemplate(
148
183
  * .listen(3000)
149
184
  * ```
150
185
  */
151
-
152
- /**
153
- * Wraps an Elysia app's `handle` method so that every request runs inside a
154
- * fresh `AsyncLocalStorage` scope. This isolates `pendingInvalidations` per
155
- * request, preventing concurrent requests from stealing each other's
156
- * `revalidatePath()` calls.
157
- */
158
- function wrapWithRequestScope(app: AnyElysia): Elysia {
159
- const original = app.handle.bind(app);
160
- app.handle = (request: Request) => _runWithRequestInvalidationScope(() => original(request));
161
- return app;
162
- }
163
-
164
186
  export async function furin({
165
187
  pagesDir,
166
188
  logger,
189
+ clientLogging,
167
190
  }: {
168
191
  pagesDir?: string;
169
192
  logger?: EvlogElysiaOptions;
193
+ /**
194
+ * Initialize the browser HTTP log drain in the hydration entry. Off by
195
+ * default — enabling it adds `evlog/http` drain setup and points browser
196
+ * events at `/_furin/ingest`. Server-side logging is configured via `logger`
197
+ * and unaffected.
198
+ */
199
+ clientLogging?: boolean;
170
200
  }) {
171
201
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
172
202
  initLogger({ env: { service: "furin" } });
@@ -179,8 +209,13 @@ export async function furin({
179
209
  "/_client/**",
180
210
  "/public/**",
181
211
  "/favicon.ico",
182
- "/_furin/!(ingest)",
183
212
  "/_bun_hmr_entry/**",
213
+ // Note: /_furin/data is logged with the *logical* path rewritten by
214
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
215
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
216
+ // /_furin/ingest is kept loggable so browser-side events show up.
217
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
218
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
184
219
  ...(userExclude ?? []),
185
220
  ],
186
221
  })
@@ -207,6 +242,7 @@ export async function furin({
207
242
  __proto__,
208
243
  constructor: _ctor,
209
244
  prototype,
245
+ environment: _browserEnv,
210
246
  ...safeEvent
211
247
  } = event as Record<string, unknown>;
212
248
  log.set({ ...safeEvent, service: "furin:browser" });
@@ -229,16 +265,24 @@ export async function furin({
229
265
  if (IS_DEV) {
230
266
  const furinDir = resolve(cwd, ".furin");
231
267
  // Lazy import — build pipeline has native deps not available in compiled binaries
232
- const { registerDevPagePlugin } = await import("./dev-page-plugin.ts");
268
+ const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
233
269
  registerDevPagePlugin();
234
270
 
235
- const { scanPages } = await import("./router.ts");
271
+ const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
272
+
273
+ const { scanPages } = await import("./server/router/index.ts");
236
274
  const { root, routes } = await scanPages(resolvedPagesDir);
237
275
 
238
276
  const { writeDevFiles } = await import("./build/hydrate.ts");
239
277
  writeDevFiles(
240
278
  routes,
241
- { outDir: furinDir, rootLayout: root.path, basePath: "", publicPath: "/_client/" },
279
+ {
280
+ outDir: furinDir,
281
+ rootLayout: root.path,
282
+ basePath: "",
283
+ publicPath: "/_client/",
284
+ clientLogging: clientLogging ?? false,
285
+ },
242
286
  cwd
243
287
  );
244
288
 
@@ -247,6 +291,11 @@ export async function furin({
247
291
 
248
292
  const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
249
293
  .use(loggerPlugin)
294
+ .onError({ as: "global" }, async ({ code, request }) => {
295
+ if (code === "NOT_FOUND") {
296
+ return await renderRootNotFound(root, request);
297
+ }
298
+ })
250
299
  .onAfterHandle({ as: "global" }, ({ set }) => {
251
300
  // Forward pending revalidation paths so the client can bust its prefetch cache
252
301
  const pending = consumePendingInvalidations();
@@ -264,6 +313,8 @@ export async function furin({
264
313
  ? file(join(publicDir, "favicon.ico"))
265
314
  : () => new Response(null, { status: 404 })
266
315
  )
316
+ .use(createDevInspectorPlugin())
317
+ .use(createDataEndpoint(routes))
267
318
  .use((app) => {
268
319
  for (const route of routes) {
269
320
  app.use(createRoutePlugin(route, root));
@@ -280,6 +331,7 @@ export async function furin({
280
331
  const { root, routes } = loadProdRoutes(ctx);
281
332
  const prodBuildId = ctx.buildId ?? "";
282
333
  setBuildId(prodBuildId);
334
+ hydrateSSGCacheFromCompileContext(ctx);
283
335
 
284
336
  const embedded = ctx?.embedded;
285
337
  const clientDir = embedded ? "" : resolveClientDirFromArgv();
@@ -287,6 +339,11 @@ export async function furin({
287
339
 
288
340
  const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
289
341
  .use(loggerPlugin)
342
+ .onError({ as: "global" }, async ({ code, request }) => {
343
+ if (code === "NOT_FOUND") {
344
+ return await renderRootNotFound(root, request);
345
+ }
346
+ })
290
347
  .onAfterHandle({ as: "global" }, ({ path, set }) => {
291
348
  // Content-hashed client assets are permanently cacheable — browsers never need to
292
349
  // revalidate them because any change produces a new filename.
@@ -305,6 +362,9 @@ export async function furin({
305
362
  }
306
363
  })
307
364
  .onStart(async ({ server }) => {
365
+ if (ctx.ssgCache) {
366
+ return;
367
+ }
308
368
  const origin = server?.url?.origin ?? "http://localhost:3000";
309
369
  await warmSSGCache(routes, root, origin);
310
370
  })
@@ -345,6 +405,7 @@ export async function furin({
345
405
  return app;
346
406
  })()
347
407
  )
408
+ .use(createDataEndpoint(routes))
348
409
  .use((app) => {
349
410
  for (const route of routes) {
350
411
  app.use(createRoutePlugin(route, root, prodBuildId));
@@ -354,6 +415,23 @@ export async function furin({
354
415
  return wrapWithRequestScope(prodApp);
355
416
  }
356
417
 
418
+ // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
419
+ export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
357
420
  // ── Public API re-export ──────────────────────────────────────────────────────
358
- // biome-ignore lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
359
- export { revalidatePath, setCachePurger } from "./render/cache.ts";
421
+ // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
422
+ export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
423
+ export { defer, isDeferred } from "./client.ts";
424
+ export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
425
+ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
426
+ export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
427
+ export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
428
+ export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
429
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
430
+ export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
431
+ export type {
432
+ NotFoundComponent,
433
+ NotFoundOptions,
434
+ NotFoundProps,
435
+ } from "./shared/not-found.ts";
436
+ export { isNotFoundError, notFound } from "./shared/not-found.ts";
437
+ // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
@@ -4,7 +4,6 @@ const ELYSIA_FILTER = /^elysia$/;
4
4
  const BUN_BUILTIN_FILTER = /^bun:/;
5
5
  const ANY_FILTER = /.*/;
6
6
  const TS_FILE_FILTER = /\.(tsx|ts)$/;
7
- const REACT_IMPORT_FILTER = /import\s+React\b/;
8
7
 
9
8
  // Minimal browser stub for elysia — `t` is only used for schema definitions
10
9
  // in params/query, which the client never validates at runtime.
@@ -62,13 +61,13 @@ const plugin: Bun.BunPlugin = {
62
61
 
63
62
  try {
64
63
  const result = transformForClient(source, args.path);
65
- let code = result.code;
66
-
67
- if (code.includes("React.createElement") && !REACT_IMPORT_FILTER.test(code)) {
68
- code = `import React from "react";\n${code}`;
69
- }
70
-
71
- return { contents: code, loader: "js" };
64
+ // Output is TS/TSX (yuku parses directly, no pre-transpile). Bun's
65
+ // bundler picks the loader from the file extension and applies the
66
+ // project tsconfig — including the JSX automatic runtime.
67
+ return {
68
+ contents: result.code,
69
+ loader: args.path.endsWith(".tsx") ? "tsx" : "ts",
70
+ };
72
71
  } catch (err) {
73
72
  console.error(`[furin] strip-plugin transform error for ${args.path}:`, err);
74
73
  return;
@@ -1,22 +1,15 @@
1
1
  import MagicString from "magic-string";
2
- import { parseSync } from "oxc-parser";
3
-
4
- // ---------------------------------------------------------------------------
5
- // Bun.Transpiler singleton — strips TypeScript + JSX before AST work.
6
- // Force classic JSX transform (React.createElement) regardless of the
7
- // project tsconfig's "jsx": "react-jsx" setting — the Bun.build() step
8
- // that consumes this output handles the automatic runtime itself.
9
- // ---------------------------------------------------------------------------
10
- const bunTranspiler = new Bun.Transpiler({
11
- loader: "tsx",
12
- tsconfig: {
13
- compilerOptions: {
14
- jsx: "react",
15
- jsxFactory: "React.createElement",
16
- jsxFragmentFactory: "React.Fragment",
17
- },
18
- },
19
- });
2
+ import {
3
+ type CallExpression,
4
+ type ImportDeclaration,
5
+ type ObjectExpression,
6
+ type ObjectProperty,
7
+ type Program,
8
+ parse,
9
+ type SourceLang,
10
+ } from "yuku-parser";
11
+ import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
12
+ import { type AstNode, walkAST } from "../shared/utils/ast-walk.ts";
20
13
 
21
14
  // loader: data fetching (runs on server only)
22
15
  // query / params: Elysia TypeBox schemas — validated server-side, not used in browser
@@ -28,71 +21,6 @@ interface TransformResult {
28
21
  removedServerCode: boolean;
29
22
  }
30
23
 
31
- // ---------------------------------------------------------------------------
32
- // ESTree node types (minimal subset needed for our walk)
33
- // ---------------------------------------------------------------------------
34
- interface AstNode {
35
- body?: AstNode[];
36
- end: number;
37
- start: number;
38
- type: string;
39
- [key: string]: unknown;
40
- }
41
-
42
- interface Property extends AstNode {
43
- // Identifier key: { loader: fn } → key.name === "loader"
44
- // Literal key: { "loader": fn } → key.value === "loader"
45
- key: AstNode & { name?: string; value?: unknown };
46
- type: "Property";
47
- }
48
-
49
- interface SpreadElement extends AstNode {
50
- argument: AstNode;
51
- type: "SpreadElement";
52
- }
53
-
54
- interface ObjectExpression extends AstNode {
55
- // properties may include SpreadElement nodes, e.g. { ...spread, loader: fn }
56
- properties: Array<Property | SpreadElement>;
57
- type: "ObjectExpression";
58
- }
59
-
60
- interface CallExpression extends AstNode {
61
- arguments: AstNode[];
62
- callee: AstNode & { name?: string; property?: AstNode & { name?: string } };
63
- type: "CallExpression";
64
- }
65
-
66
- interface ImportDeclaration extends AstNode {
67
- specifiers: Array<AstNode & { local: AstNode & { name: string } }>;
68
- type: "ImportDeclaration";
69
- }
70
-
71
- // ---------------------------------------------------------------------------
72
- // AST walking
73
- // ---------------------------------------------------------------------------
74
- function walk(node: unknown, visitor: (n: AstNode) => void): void {
75
- if (!node || typeof node !== "object") {
76
- return;
77
- }
78
- if (Array.isArray(node)) {
79
- for (const child of node) {
80
- walk(child, visitor);
81
- }
82
- return;
83
- }
84
- const n = node as AstNode;
85
- if (typeof n.type === "string") {
86
- visitor(n);
87
- }
88
- for (const key of Object.keys(n)) {
89
- if (key === "type" || key === "start" || key === "end") {
90
- continue;
91
- }
92
- walk(n[key], visitor);
93
- }
94
- }
95
-
96
24
  // ---------------------------------------------------------------------------
97
25
  // Check if a CallExpression is createRoute() or page() / route.page()
98
26
  // ---------------------------------------------------------------------------
@@ -105,7 +33,11 @@ function isRoutePageCall(node: CallExpression): boolean {
105
33
  if (callee.type === "Identifier" && callee.name === "page") {
106
34
  return true;
107
35
  }
108
- if (callee.type === "MemberExpression" && callee.property?.name === "page") {
36
+ if (
37
+ callee.type === "MemberExpression" &&
38
+ callee.property.type === "Identifier" &&
39
+ callee.property.name === "page"
40
+ ) {
109
41
  return true;
110
42
  }
111
43
  return false;
@@ -115,12 +47,16 @@ function isTargetCall(node: CallExpression): boolean {
115
47
  return isCreateRouteCall(node) || isRoutePageCall(node);
116
48
  }
117
49
 
50
+ function isObjectExpressionNode(node: { type: string }): node is ObjectExpression {
51
+ return node.type === "ObjectExpression";
52
+ }
53
+
118
54
  // ---------------------------------------------------------------------------
119
55
  // Remove server-only properties from an ObjectExpression using MagicString.
120
56
  // Returns true if any property was removed.
121
57
  // ---------------------------------------------------------------------------
122
58
  function removeServerProperties(s: MagicString, source: string, obj: ObjectExpression): boolean {
123
- const toRemove = obj.properties.filter((p): p is Property => {
59
+ const toRemove = obj.properties.filter((p): p is ObjectProperty => {
124
60
  // Skip spread elements — they have no key.
125
61
  if (p.type !== "Property") {
126
62
  return false;
@@ -184,47 +120,125 @@ function removeServerProperties(s: MagicString, source: string, obj: ObjectExpre
184
120
  return true;
185
121
  }
186
122
 
123
+ // TypeScript-specific node types that introduce a type-only scope. Any
124
+ // Identifier / JSXIdentifier beneath one of these nodes is a TypeScript type
125
+ // reference, not a runtime value reference, and must not count toward DCE refs.
126
+ const TYPE_SCOPE_NODES = new Set([
127
+ "TSTypeAnnotation", // `: Type` on variables, params, return types
128
+ "TSTypeParameterDeclaration", // `<T>` in generic type-param declarations
129
+ "TSTypeParameterInstantiation", // `<T>` in generic instantiation positions
130
+ "TSInterfaceDeclaration", // `interface Foo { … }` — entirely type-level
131
+ "TSTypeAliasDeclaration", // `type Foo = …` — entirely type-level
132
+ "TSTypePredicate", // `x is Type` in return-type position
133
+ "TSClassImplements", // `class C implements Iface` — the implements clause is type-only
134
+ ]);
135
+
136
+ // Walk `node` and add every Identifier / JSXIdentifier found inside it to
137
+ // `excluded`. Called for nodes that are entirely in type position (e.g. a
138
+ // TSTypeAnnotation) so their descendant identifiers are ignored by DCE.
139
+ function markTypeDescendants(node: unknown, excluded: Set<unknown>): void {
140
+ if (!node || typeof node !== "object") {
141
+ return;
142
+ }
143
+ if (Array.isArray(node)) {
144
+ for (const item of node) {
145
+ markTypeDescendants(item, excluded);
146
+ }
147
+ return;
148
+ }
149
+ const n = node as AstNode;
150
+ if (n.type === "Identifier" || n.type === "JSXIdentifier") {
151
+ excluded.add(n);
152
+ }
153
+ for (const key of Object.keys(n)) {
154
+ if (key === "type" || key === "start" || key === "end") {
155
+ continue;
156
+ }
157
+ markTypeDescendants(n[key], excluded);
158
+ }
159
+ }
160
+
161
+ // Excludes identifiers that appear in TypeScript type-only positions from the
162
+ // `excluded` set. Extracted from the Pass-1 walk callback to keep cognitive
163
+ // complexity within the allowed budget.
164
+ function excludeTypePositionIdentifiers(node: AstNode, excluded: Set<unknown>): void {
165
+ if (TYPE_SCOPE_NODES.has(node.type)) {
166
+ markTypeDescendants(node, excluded);
167
+ return;
168
+ }
169
+ // TSAsExpression (`x as T`), TSSatisfiesExpression (`x satisfies T`), and
170
+ // TSTypeAssertion (`<T>x`) are mixed: the expression child is runtime; only
171
+ // the typeAnnotation child is type-only.
172
+ if (
173
+ node.type === "TSAsExpression" ||
174
+ node.type === "TSSatisfiesExpression" ||
175
+ node.type === "TSTypeAssertion"
176
+ ) {
177
+ markTypeDescendants(node.typeAnnotation as unknown, excluded);
178
+ }
179
+ }
180
+
187
181
  // ---------------------------------------------------------------------------
188
- // Collect all Identifier names referenced in the AST (excluding imports).
189
- // Skips identifiers that appear as static (non-computed) property keys or
190
- // as static member-expression properties (both require computed=false),
191
- // because those positions are not identifier *references* and including them
192
- // would prevent DCE of same-named imports.
182
+ // Collect all Identifier / JSXIdentifier names referenced in the AST
183
+ // (excluding imports). Skips identifiers in non-reference positions:
184
+ //
185
+ // • Static (non-computed) object property keys — `{ loader: fn }`
186
+ // • Static (non-computed) member access properties — `obj.prop`
187
+ // • JSX attribute names — `<div className=...>`
188
+ // • Right-hand side of a JSXMemberExpression chain — `<UI.Button>` (Button)
189
+ // • TypeScript type positions — `: MyType`, `<T>`, etc.
190
+ //
193
191
  // Computed keys like `{ [someVar]: v }` are left in — they ARE references.
192
+ // JSX tag positions ARE references — `<Link>` requires the `Link` binding
193
+ // to be in scope, so omitting JSXIdentifier (the default after the parser
194
+ // switch from Bun.Transpiler to yuku-parser) silently drops imports that
195
+ // are only used as JSX tags.
194
196
  // ---------------------------------------------------------------------------
195
- function collectReferencedNames(program: AstNode): Set<string> {
197
+ function collectReferencedNames(program: Program): Set<string> {
196
198
  const refs = new Set<string>();
197
- // Nodes that occupy a non-reference Identifier position.
199
+ // Nodes that occupy a non-reference Identifier / JSXIdentifier position.
198
200
  const excluded = new Set<unknown>();
199
201
 
200
- for (const stmt of program.body ?? []) {
202
+ for (const stmt of program.body) {
201
203
  if (stmt.type === "ImportDeclaration") {
202
204
  continue;
203
205
  }
204
206
  // Pass 1 — mark non-reference identifier positions.
205
207
  // Only exclude *static* keys (computed=false); computed keys like
206
208
  // `{ [someVar]: v }` are genuine identifier references.
207
- walk(stmt, (node) => {
209
+ walkAST(stmt, (node) => {
208
210
  if (node.type === "Property" && !node.computed) {
209
211
  excluded.add(node.key);
210
212
  }
211
213
  if (node.type === "MemberExpression" && !node.computed) {
212
214
  excluded.add(node.property);
213
215
  }
216
+ // `<div className="...">` — the attribute *name* is a key, not a ref.
217
+ if (node.type === "JSXAttribute") {
218
+ excluded.add(node.name);
219
+ }
220
+ // `<UI.Button>` — `UI` is the live binding, `.Button` is a property
221
+ // lookup on it. Exclude the property side of every JSXMemberExpression
222
+ // so a same-named import (e.g. `import { Button } from ...`) doesn't
223
+ // get falsely kept alive by every `<Foo.Button>` in the file.
224
+ if (node.type === "JSXMemberExpression") {
225
+ excluded.add(node.property);
226
+ }
227
+ excludeTypePositionIdentifiers(node, excluded);
214
228
  });
215
229
  }
216
230
 
217
- for (const stmt of program.body ?? []) {
231
+ for (const stmt of program.body) {
218
232
  if (stmt.type === "ImportDeclaration") {
219
233
  continue;
220
234
  }
221
235
  // Pass 2 — collect genuine identifier references.
222
- walk(stmt, (node) => {
236
+ walkAST(stmt, (node) => {
223
237
  if (excluded.has(node)) {
224
238
  return;
225
239
  }
226
240
  if (
227
- node.type === "Identifier" &&
241
+ (node.type === "Identifier" || node.type === "JSXIdentifier") &&
228
242
  typeof (node as AstNode & { name: string }).name === "string"
229
243
  ) {
230
244
  refs.add((node as AstNode & { name: string }).name);
@@ -259,6 +273,7 @@ function removeUnusedSpecifiers(
259
273
  while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
260
274
  removeEnd++;
261
275
  }
276
+ // react-doctor-disable-next-line react-doctor/js-set-map-lookups
262
277
  if (!code.slice(spec.end, removeEnd).includes(",")) {
263
278
  while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
264
279
  removeStart--;
@@ -278,19 +293,19 @@ function removeUnusedSpecifiers(
278
293
  // original-source positions, which diverge from output positions whenever
279
294
  // earlier passes have removed content.
280
295
  // ---------------------------------------------------------------------------
281
- export function deadCodeElimination(s: MagicString): MagicString {
296
+ export function deadCodeElimination(s: MagicString, lang: SourceLang): MagicString {
282
297
  const code = s.toString();
283
- const { program, errors } = parseSync("dce.js", code);
284
- if (errors.length > 0) {
285
- console.error("[furin] DCE: failed to parse transformed output:", errors[0]?.message);
298
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
299
+ const firstError = diagnostics.find((d) => d.severity === "error");
300
+ if (firstError) {
301
+ console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
286
302
  return s;
287
303
  }
288
304
 
289
305
  const fresh = new MagicString(code);
290
- const programNode = program as unknown as AstNode;
291
- const refs = collectReferencedNames(programNode);
306
+ const refs = collectReferencedNames(program);
292
307
 
293
- const body = programNode.body ?? [];
308
+ const body = program.body;
294
309
  for (let i = body.length - 1; i >= 0; i--) {
295
310
  const stmt = body[i];
296
311
  if (!stmt) {
@@ -320,10 +335,10 @@ export function deadCodeElimination(s: MagicString): MagicString {
320
335
  // Remove server-only properties from createRoute() / page() / route.page()
321
336
  // calls found anywhere in the AST.
322
337
  // ---------------------------------------------------------------------------
323
- function removeServerExports(s: MagicString, source: string, program: AstNode): boolean {
338
+ function removeServerExports(s: MagicString, source: string, program: Program): boolean {
324
339
  let removedServerCode = false;
325
340
 
326
- walk(program, (node) => {
341
+ walkAST(program, (node) => {
327
342
  if (node.type !== "CallExpression") {
328
343
  return;
329
344
  }
@@ -331,11 +346,16 @@ function removeServerExports(s: MagicString, source: string, program: AstNode):
331
346
  if (!isTargetCall(call)) {
332
347
  return;
333
348
  }
334
- const arg = call.arguments[0];
335
- if (!arg || arg.type !== "ObjectExpression") {
349
+ // Unwrap `createRoute({...} as Config)` / `page({...} satisfies Opts)` etc.
350
+ const firstArg = call.arguments[0];
351
+ if (!firstArg) {
352
+ return;
353
+ }
354
+ const arg = unwrapTSExpression(firstArg);
355
+ if (!isObjectExpressionNode(arg)) {
336
356
  return;
337
357
  }
338
- if (removeServerProperties(s, source, arg as unknown as ObjectExpression)) {
358
+ if (removeServerProperties(s, source, arg)) {
339
359
  removedServerCode = true;
340
360
  }
341
361
  });
@@ -344,24 +364,30 @@ function removeServerExports(s: MagicString, source: string, program: AstNode):
344
364
  }
345
365
 
346
366
  export function transformForClient(code: string, filename: string): TransformResult {
347
- // Pass 1 — Bun.Transpiler: strip TypeScript + JSX → plain JS.
348
- const plainJs = bunTranspiler.transformSync(code);
367
+ // .d.ts files have no runtime code — yuku rejects parsing them as modules.
368
+ // Treat as a passthrough so callers don't need to pre-filter.
369
+ const lang = detectLangFromPath(filename);
370
+ if (lang === "dts") {
371
+ return { code, map: null, removedServerCode: false };
372
+ }
349
373
 
350
- // Pass 2 — oxc-parser: parse plain JS to ESTree AST with span offsets.
351
- const { program, errors } = parseSync(filename, plainJs);
352
- if (errors.length > 0) {
353
- throw new Error(`Failed to parse ${filename}: ${errors[0]?.message}`);
374
+ // Pass 1 — yuku-parser: parse TS/TSX/JS/JSX directly to ESTree AST with
375
+ // span offsets calibrated against `code` itself (no transpile step).
376
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
377
+ const firstError = diagnostics.find((d) => d.severity === "error");
378
+ if (firstError) {
379
+ throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
354
380
  }
355
381
 
356
- // Pass 3 — MagicString: surgically remove server-only properties.
357
- let s = new MagicString(plainJs);
358
- const removedServerCode = removeServerExports(s, plainJs, program as unknown as AstNode);
382
+ // Pass 2 — MagicString: surgically remove server-only properties.
383
+ let s = new MagicString(code);
384
+ const removedServerCode = removeServerExports(s, code, program);
359
385
 
360
- // Pass 4 — DCE: prune imports that are no longer referenced.
386
+ // Pass 3 — DCE: prune imports that are no longer referenced.
361
387
  // deadCodeElimination returns a fresh MagicString keyed on the current
362
388
  // output so its internal AST offsets remain consistent.
363
389
  if (removedServerCode) {
364
- s = deadCodeElimination(s);
390
+ s = deadCodeElimination(s, lang);
365
391
  }
366
392
 
367
393
  return {
@@ -0,0 +1,10 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: auto-invalidate has a small public/internal surface gathered for tests and furin.ts exports
2
+ export { furinInvalidate } from "./plugin.ts";
3
+ export { AutoInvalidateRegistry, autoInvalidateRegistry } from "./registry.ts";
4
+ export {
5
+ appendPendingInvalidationHeader,
6
+ isSuccessfulMutationResponse,
7
+ revalidateTag,
8
+ runInvalidationRules,
9
+ } from "./runtime.ts";
10
+ export type { InvalidationInput, InvalidationRule } from "./types.ts";