@teyik0/furin 0.5.0-alpha.2 → 0.6.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 (97) hide show
  1. package/dist/adapter/runtime-build.d.ts +2 -0
  2. package/dist/build/entry-template.d.ts +2 -0
  3. package/dist/build/entry-template.ts +2 -0
  4. package/dist/build/index.js +8082 -6573
  5. package/dist/build/request-keys.d.ts +4 -0
  6. package/dist/cli/index.js +8071 -6562
  7. package/dist/client/browser-events-runtime.d.ts +2 -1
  8. package/dist/client/define-route.d.ts +0 -1
  9. package/dist/client/dev-error-overlay.ts +1 -0
  10. package/dist/client/document.d.ts +1 -0
  11. package/dist/client/hmr.d.ts +1 -1
  12. package/dist/client/link.js +101 -61
  13. package/dist/client.js +13 -8
  14. package/dist/define-route.d.ts +163 -101
  15. package/dist/furin.d.ts +3 -0
  16. package/dist/furin.js +7663 -6480
  17. package/dist/plugin/index.js +462 -127
  18. package/dist/plugin/transform-dev-page.d.ts +7 -0
  19. package/dist/server/auto-invalidate/registry.d.ts +4 -2
  20. package/dist/server/browser-events/plugin.d.ts +3 -0
  21. package/dist/server/dev/runtime.production.d.ts +1 -0
  22. package/dist/server/dev-page-plugin.d.ts +1 -0
  23. package/dist/server/internal.d.ts +2 -0
  24. package/dist/server/internal.js +67 -39
  25. package/dist/server/production-server.js +66 -38
  26. package/dist/server/render/assemble.d.ts +6 -6
  27. package/dist/server/render/document.d.ts +1 -1
  28. package/dist/server/render/element.d.ts +1 -1
  29. package/dist/server/render/loaders.d.ts +11 -3
  30. package/dist/server/render/mixed-cache.d.ts +6 -0
  31. package/dist/server/render/ssr.d.ts +3 -3
  32. package/dist/server/router/discovery.d.ts +1 -0
  33. package/dist/server/router/patterns.d.ts +3 -0
  34. package/dist/server/router/plugin.d.ts +3 -0
  35. package/dist/server/router/types.d.ts +4 -0
  36. package/dist/server/security/csp.d.ts +12 -0
  37. package/dist/server/sync/index.js +65 -37
  38. package/dist/server/sync/postgres/index.js +8 -0
  39. package/package.json +12 -11
  40. package/src/adapter/README.md +3 -0
  41. package/src/adapter/bun.ts +3 -0
  42. package/src/adapter/package.ts +4 -0
  43. package/src/adapter/runtime-build.ts +36 -2
  44. package/src/adapter/static.ts +10 -4
  45. package/src/adapter/vercel.ts +18 -10
  46. package/src/build/entry-template.ts +2 -0
  47. package/src/build/hydrate.ts +1 -0
  48. package/src/build/request-keys.ts +93 -0
  49. package/src/build/ssg-cache.ts +9 -4
  50. package/src/client/boundaries.tsx +1 -1
  51. package/src/client/browser-events-runtime.ts +69 -16
  52. package/src/client/define-route.ts +0 -1
  53. package/src/client/dev-error-overlay.ts +1 -0
  54. package/src/client/document.tsx +19 -2
  55. package/src/client/hmr.ts +3 -2
  56. package/src/client/router/boundary-tree.tsx +3 -4
  57. package/src/client/router/provider.tsx +109 -61
  58. package/src/define-route.ts +356 -127
  59. package/src/furin.ts +138 -25
  60. package/src/plugin/route-config-autofix.ts +2 -2
  61. package/src/plugin/routes.ts +16 -5
  62. package/src/plugin/transform-dev-page.ts +231 -0
  63. package/src/rsc/version.ts +5 -0
  64. package/src/server/auto-invalidate/registry.ts +53 -25
  65. package/src/server/browser-events/plugin.ts +112 -1
  66. package/src/server/cache/dev-loader.ts +1 -1
  67. package/src/server/cache/invalidation.ts +2 -0
  68. package/src/server/cache/isr-ssg.ts +1 -1
  69. package/src/server/cache/ssg.ts +1 -1
  70. package/src/server/dev/diagnostics.ts +4 -2
  71. package/src/server/dev/error.ts +2 -1
  72. package/src/server/dev/graph.ts +55 -6
  73. package/src/server/dev/runtime.production.ts +4 -0
  74. package/src/server/dev/symbolicate.ts +2 -0
  75. package/src/server/dev-page-plugin.ts +67 -4
  76. package/src/server/evlog.ts +1 -1
  77. package/src/server/internal.ts +2 -0
  78. package/src/server/render/assemble.ts +15 -11
  79. package/src/server/render/document.tsx +3 -1
  80. package/src/server/render/element.tsx +5 -5
  81. package/src/server/render/isr.ts +11 -5
  82. package/src/server/render/loaders.ts +243 -56
  83. package/src/server/render/mixed-cache.ts +298 -0
  84. package/src/server/render/not-found.ts +10 -4
  85. package/src/server/render/ppr-document.ts +45 -10
  86. package/src/server/render/ppr-route.ts +26 -12
  87. package/src/server/render/ssg.ts +2 -1
  88. package/src/server/render/ssr.ts +55 -31
  89. package/src/server/render/static-params.ts +1 -1
  90. package/src/server/router/discovery.ts +14 -0
  91. package/src/server/router/hmr.ts +106 -16
  92. package/src/server/router/patterns.ts +27 -0
  93. package/src/server/router/plugin.ts +69 -9
  94. package/src/server/router/source-version.ts +20 -2
  95. package/src/server/router/types.ts +4 -0
  96. package/src/server/security/csp.ts +44 -0
  97. package/src/server/sync/postgres/index.ts +8 -0
package/src/furin.ts CHANGED
@@ -10,6 +10,7 @@ import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
10
10
  import type { PageCacheAdapter } from "./server/cache/page-cache.ts";
11
11
  import { setPageCacheAdapter } from "./server/cache/page-cache-state.ts";
12
12
  import { setSSGCache } from "./server/cache/ssg.ts";
13
+ import { getLogger } from "./server/context-logger.ts";
13
14
  import type { DevelopmentRouteSnapshot, DevGraph } from "./server/dev/graph.ts";
14
15
  import {
15
16
  createInstrumentationPlugin,
@@ -42,16 +43,22 @@ import {
42
43
  import { loadProdRoutes } from "./server/router/discovery.ts";
43
44
  import { invalidateStampedRouteModules, resolveCurrentDevRoute } from "./server/router/hmr.ts";
44
45
  import { buildRouteMatcher } from "./server/router/patterns.ts";
45
- import { createDataEndpoint, renderResolvedRoute } from "./server/router/plugin.ts";
46
+ import {
47
+ renderResolvedRoute,
48
+ renderRouteData,
49
+ serializeGuardRedirect,
50
+ } from "./server/router/plugin.ts";
46
51
  import { mergeRouteSchemas } from "./server/router/schema-merge.ts";
47
52
  import {
48
53
  createSearchRouteMetadata,
54
+ parseDataEndpointPath,
49
55
  parseRouteParams,
50
56
  parseRouteQuery,
51
57
  } from "./server/router/schemas.ts";
52
58
  import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
53
59
  import { IS_DEV } from "./server/runtime-env.ts";
54
60
  import { type FurinSyncOption, resolveSyncPath } from "./server/sync/config.ts";
61
+ import { physicalPath } from "./shared/prefix.ts";
55
62
 
56
63
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
57
64
  export interface FurinCacheTags {}
@@ -59,11 +66,17 @@ export interface FurinCacheTags {}
59
66
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
60
67
 
61
68
  async function createProductionBrowserEventsPlugin(
62
- sync: FurinSyncOption | undefined
69
+ sync: FurinSyncOption | undefined,
70
+ deploymentTarget: "vercel" | undefined
63
71
  ): Promise<AnyElysia> {
64
- return sync
65
- ? (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({ sync })
66
- : new Elysia();
72
+ if (!sync) {
73
+ return new Elysia();
74
+ }
75
+ const browserEvents = await import("./server/browser-events/plugin.ts");
76
+ // Vercel invokes app.handle(Request), so Elysia's Bun.Server WebSocket upgrade is unavailable.
77
+ return deploymentTarget === "vercel"
78
+ ? browserEvents.createSseBrowserEventsPlugin({ sync })
79
+ : browserEvents.createBrowserEventsPlugin({ sync });
67
80
  }
68
81
 
69
82
  function repairedDevelopmentRoutes(
@@ -108,6 +121,7 @@ export {
108
121
  type IsomorphicFnBuilder,
109
122
  type ServerIsomorphicFn,
110
123
  } from "./isomorphic.ts";
124
+ export { type FurinCspOptions, furinCsp } from "./server/security/csp.ts";
111
125
  export { clientDirNameForPrefix } from "./shared/prefix.ts";
112
126
 
113
127
  const MAX_BROWSER_INGEST_BYTES = 64 * 1024;
@@ -336,8 +350,7 @@ function createLoggerPlugin(
336
350
  `${prefix}/_bun_hmr_entry/**`,
337
351
  ...instrumentationLoggerExclusions(prefix),
338
352
  ...(syncPath ? [`${prefix}${syncPath}/**`] : []),
339
- // Note: /_furin/data is logged with the *logical* path rewritten by
340
- // createDataEndpoint via getLogger().set({ path }), so SPA navigations
353
+ // Note: /_furin/data is logged with the logical page path, so SPA navigations
341
354
  // appear as "GET /board/123 200" — same shape as a normal SSR nav.
342
355
  // /_furin/ingest remains loggable when browser logging is explicitly
343
356
  // enabled so browser-side events show up.
@@ -415,6 +428,67 @@ function initializeLogger(logger: FurinLoggerOptions | undefined): FurinEvlogOpt
415
428
  * owning instance is resolved from the request PATH, never from this
416
429
  * closure — which wrap executes first is therefore irrelevant.
417
430
  */
431
+ const navigationDataRequests = new WeakSet<Request>();
432
+ const navigationDataRefreshers = new WeakMap<FurinInstance, () => Promise<void>>();
433
+ const navigationDataMatchers = new WeakMap<FurinInstance, (path: string) => boolean>();
434
+
435
+ /** Whether a request targets a registered page in the specified Furin mount. */
436
+ export function isFurinPageRequest(request: Request, prefix: string): boolean {
437
+ if (request.method !== "GET") {
438
+ return false;
439
+ }
440
+ const url = new URL(request.url);
441
+ const { pathname } = url;
442
+ const mountPrefix = normalizePrefix(prefix);
443
+ const instance = resolveInstanceByPath(pathname);
444
+ if (instance.prefix !== mountPrefix) {
445
+ return false;
446
+ }
447
+ const path = pathname.slice(mountPrefix.length) || "/";
448
+ if (path === "/_furin/data") {
449
+ const dataPath = parseDataEndpointPath(url.searchParams.get("path") ?? "");
450
+ return (
451
+ dataPath !== undefined && (navigationDataMatchers.get(instance)?.(dataPath.pathname) ?? false)
452
+ );
453
+ }
454
+ if (
455
+ path.startsWith("/_client/") ||
456
+ path.startsWith("/_furin/") ||
457
+ path.startsWith("/_bun_hmr_entry") ||
458
+ path.startsWith("/public/") ||
459
+ path === "/favicon.ico"
460
+ ) {
461
+ return false;
462
+ }
463
+ return navigationDataMatchers.get(instance)?.(path) ?? false;
464
+ }
465
+
466
+ function rewriteNavigationDataRequest(
467
+ request: Request,
468
+ instance: FurinInstance
469
+ ): Request | Response {
470
+ const url = new URL(request.url);
471
+ if (request.method !== "GET" || url.pathname !== `${instance.prefix}/_furin/data`) {
472
+ return request;
473
+ }
474
+ const rawPath = url.searchParams.get("path");
475
+ if (!rawPath) {
476
+ return new Response("Missing required query param: path", { status: 400 });
477
+ }
478
+ const parsed = parseDataEndpointPath(rawPath);
479
+ if (!parsed) {
480
+ return new Response("Invalid path", { status: 400 });
481
+ }
482
+ if (!navigationDataMatchers.get(instance)?.(parsed.pathname)) {
483
+ return new Response("Not Found", { status: 404 });
484
+ }
485
+ url.pathname = physicalPath(instance.prefix, parsed.pathname);
486
+ url.search = parsed.url.search;
487
+ const rewritten = new Request(url, request);
488
+ navigationDataRequests.add(rewritten);
489
+ return rewritten;
490
+ }
491
+
418
492
  function wrapWithRequestScope(app: AnyElysia): Elysia {
419
493
  return app.wrap((fetch) => (request, ...rest) => {
420
494
  if (hasRequestScope()) {
@@ -424,10 +498,36 @@ function wrapWithRequestScope(app: AnyElysia): Elysia {
424
498
  const { pathname } = new URL(request.url);
425
499
  const instance = resolveInstanceByPath(pathname);
426
500
  return runWithInstanceScope(instance, () => {
427
- if (!shouldInstrumentRequest(pathname, instance.prefix)) {
428
- return fetch(request, ...rest);
429
- }
430
- return runWithRequestInstrumentation(request, () => fetch(request, ...rest));
501
+ const dispatch = () => {
502
+ const rewritten = rewriteNavigationDataRequest(request, instance);
503
+ if (rewritten instanceof Response) {
504
+ return rewritten;
505
+ }
506
+ const response = shouldInstrumentRequest(pathname, instance.prefix)
507
+ ? runWithRequestInstrumentation(request, () => fetch(rewritten, ...rest))
508
+ : fetch(rewritten, ...rest);
509
+ if (rewritten === request) {
510
+ return response;
511
+ }
512
+ return Promise.resolve(response).then((resolved) =>
513
+ resolved.status >= 300 && resolved.status < 400
514
+ ? serializeGuardRedirect(resolved, request)
515
+ : resolved
516
+ );
517
+ };
518
+ const dataPath =
519
+ pathname === `${instance.prefix}/_furin/data`
520
+ ? parseDataEndpointPath(new URL(request.url).searchParams.get("path") ?? "")
521
+ : undefined;
522
+ const refresh =
523
+ pathname === `${instance.prefix}/_furin/data` &&
524
+ request.method === "GET" &&
525
+ dataPath !== undefined &&
526
+ navigationDataMatchers.get(instance)?.(dataPath.pathname) === true &&
527
+ request.headers.get("x-furin-hmr-refresh") === "1"
528
+ ? navigationDataRefreshers.get(instance)
529
+ : undefined;
530
+ return refresh ? refresh().then(dispatch) : dispatch();
431
531
  });
432
532
  });
433
533
  }
@@ -499,6 +599,22 @@ function createNativeRouteRenderer(
499
599
  }
500
600
  context.params = parsedParams.params;
501
601
  context.query = parsedQuery.query;
602
+ if (navigationDataRequests.has(request)) {
603
+ getLogger().set({
604
+ path: logicalPath + requestUrl.search,
605
+ routePattern: matched.route.pattern,
606
+ });
607
+ const current = IS_DEV
608
+ ? await resolveCurrentDevRoute(matched.route, root)
609
+ : { root, route: matched.route };
610
+ return renderRouteData(
611
+ current.route,
612
+ context as unknown as Parameters<typeof renderRouteData>[1],
613
+ current.root,
614
+ searchRoutes,
615
+ logicalPath + requestUrl.search
616
+ );
617
+ }
502
618
  return renderResolvedRoute(
503
619
  matched.route,
504
620
  context as unknown as Parameters<typeof renderResolvedRoute>[1],
@@ -721,6 +837,8 @@ export async function furin({
721
837
  const initialSnapshot = createDevelopmentRouteSnapshot(prefix, root, routes);
722
838
  const currentSnapshot = (): DevelopmentRouteSnapshot => graph.snapshot ?? initialSnapshot;
723
839
  nativeRouteRenderers.set(instance, (context) => currentSnapshot().render(context));
840
+ let matchNavigationData = buildRouteMatcher(initialSnapshot.routes);
841
+ navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
724
842
 
725
843
  const { writeDevFiles } = await import("./build/hydrate.ts");
726
844
  const writeCurrentDevFiles = (snapshot: DevelopmentRouteSnapshot): void => {
@@ -752,6 +870,7 @@ export async function furin({
752
870
  const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
753
871
  writeCurrentDevFiles(nextSnapshot);
754
872
  graph.commit(nextSnapshot);
873
+ matchNavigationData = buildRouteMatcher(nextSnapshot.routes);
755
874
  const diagnostics = devDiagnosticStore(instance);
756
875
  if (repaired.root) {
757
876
  diagnostics.markReady("*");
@@ -773,6 +892,9 @@ export async function furin({
773
892
  const publicDir = resolve(cwd, "public");
774
893
  const publicExists = existsSync(publicDir);
775
894
  let routeTopologyWatcher: ReturnType<typeof registerDevRouteTopologyWatcher> | undefined;
895
+ navigationDataRefreshers.set(instance, async () => {
896
+ await routeTopologyWatcher?.refresh();
897
+ });
776
898
 
777
899
  // Routes registered below are LOGICAL — Elysia's `prefix` makes them
778
900
  // physical when this plugin is merged into the parent app (child prefixes
@@ -815,6 +937,8 @@ export async function furin({
815
937
  .cleanup(() => {
816
938
  routeTopologyWatcher?.close();
817
939
  routeTopologyWatcher = undefined;
940
+ navigationDataRefreshers.delete(instance);
941
+ navigationDataMatchers.delete(instance);
818
942
  })
819
943
  .get("/_bun_hmr_entry/index.html", hmrEntry)
820
944
  .get("/_bun_hmr_entry", hmrEntry)
@@ -857,18 +981,6 @@ export async function furin({
857
981
  ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync)
858
982
  : new Elysia()
859
983
  )
860
- .use(
861
- createDataEndpoint(
862
- async (request) => {
863
- if (request.headers.get("x-furin-hmr-refresh") === "1") {
864
- await routeTopologyWatcher?.refresh();
865
- }
866
- return currentSnapshot().routes;
867
- },
868
- undefined,
869
- (route) => resolveCurrentDevRoute(route, currentSnapshot().root)
870
- )
871
- )
872
984
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
873
985
  .use(nativeRoutesApp)
874
986
  .use(
@@ -907,6 +1019,8 @@ export async function furin({
907
1019
  searchRoutes
908
1020
  );
909
1021
  nativeRouteRenderers.set(instance, renderNativeRoute);
1022
+ const matchNavigationData = buildRouteMatcher(routes);
1023
+ navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
910
1024
  instance.buildId = prodBuildId;
911
1025
  // Init-time writes target THIS instance explicitly — with several mounted
912
1026
  // apps there is no ambient request scope to resolve it from.
@@ -951,11 +1065,10 @@ export async function furin({
951
1065
  await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
952
1066
  })
953
1067
  .use(await createProductionAssetsPlugin(ctx, embedded, clientDir))
954
- .use(await createProductionBrowserEventsPlugin(sync))
1068
+ .use(await createProductionBrowserEventsPlugin(sync, ctx?.deploymentTarget))
955
1069
  .use(
956
1070
  sync ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync) : new Elysia()
957
1071
  )
958
- .use(createDataEndpoint(routes, root))
959
1072
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
960
1073
  .use(ctx.nativeRoutes)
961
1074
  .use(createNotFoundHandling(prefix, routes, root));
@@ -176,7 +176,7 @@ function collectImportBinding(
176
176
  imports: LayoutImport[],
177
177
  allBindings: Set<string>
178
178
  ): string | null {
179
- const specifierValue = declaration.source?.value;
179
+ const specifierValue = declaration.source.value;
180
180
  if (typeof specifierValue !== "string") {
181
181
  return null;
182
182
  }
@@ -302,7 +302,7 @@ function collectBindingsFromDeclaration(
302
302
  declaration: ImportDeclaration,
303
303
  bindings: BuilderBindings
304
304
  ): void {
305
- const specifierValue = declaration.source?.value;
305
+ const specifierValue = declaration.source.value;
306
306
  if (typeof specifierValue !== "string" || !FURIN_BUILDER_MODULES.has(specifierValue)) {
307
307
  return;
308
308
  }
@@ -13,6 +13,7 @@ import { type AnyElysia, Elysia } from "elysia";
13
13
  import { type FurinNativeRouteContext, getFurinRenderer } from "../define-route.ts";
14
14
  import { detectLoaderFromPath } from "../server/lang-detect.ts";
15
15
  import { parseDynamicRouteSegment, routeSegmentToPattern } from "../server/router/patterns.ts";
16
+ import { routeModuleSourceVersion } from "../server/router/source-version.ts";
16
17
 
17
18
  const ROUTES_NAMESPACE_PREFIX = "furin-routes";
18
19
  const ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
@@ -763,8 +764,14 @@ function resolveRouteModuleImports(dependencyPath: string, packageRoot: string):
763
764
  continue;
764
765
  }
765
766
  try {
766
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname(dependencyPath)));
767
- if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
767
+ const resolvedImport = realpathSync.native(
768
+ Bun.resolveSync(imported.path, dirname(dependencyPath))
769
+ );
770
+ if (
771
+ isAbsolute(resolvedImport) &&
772
+ isWithinDirectory(resolvedImport, packageRoot) &&
773
+ !relative(packageRoot, resolvedImport).split(sep).includes("node_modules")
774
+ ) {
768
775
  resolvedImports.push(resolvedImport);
769
776
  }
770
777
  } catch {
@@ -775,7 +782,7 @@ function resolveRouteModuleImports(dependencyPath: string, packageRoot: string):
775
782
  }
776
783
 
777
784
  function collectRouteModuleDependencies(sourcePath: string): RouteModuleDependency[] {
778
- const packageRoot = realpathSync(findPackageRoot(sourcePath));
785
+ const packageRoot = realpathSync.native(findPackageRoot(sourcePath));
779
786
  const pending = [sourcePath];
780
787
  const visited = new Set<string>();
781
788
  const dependencies: RouteModuleDependency[] = [];
@@ -873,7 +880,9 @@ async function loadRouteModule(sourcePath: string): Promise<{
873
880
  }
874
881
 
875
882
  async function composableRouteApps(route: RouteFile): Promise<DevRoutesApps | undefined> {
876
- const module = await loadRouteModule(route.sourcePath);
883
+ const module = (await import(
884
+ `${route.sourcePath}?furin-server&t=${routeModuleSourceVersion(route.sourcePath)}`
885
+ )) as Awaited<ReturnType<typeof loadRouteModule>>;
877
886
  if (!module.route?.elysia) {
878
887
  return;
879
888
  }
@@ -932,7 +941,9 @@ async function composeRuntimeNode(node: RouteTreeNode): Promise<DevRoutesApps> {
932
941
  };
933
942
  }
934
943
 
935
- function composeRuntimeInstance(instance: RouteInstanceSpec): Promise<DevRoutesApps> {
944
+ async function composeRuntimeInstance(instance: RouteInstanceSpec): Promise<DevRoutesApps> {
945
+ const { registerDevPagePlugin } = await import("../server/dev-page-plugin.ts");
946
+ registerDevPagePlugin();
936
947
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
937
948
  return composeRuntimeNode(buildRouteTree(instance.pagesDir, instanceId));
938
949
  }
@@ -0,0 +1,231 @@
1
+ import MagicString from "magic-string";
2
+ import {
3
+ detectLangFromPath,
4
+ detectLoaderFromPath,
5
+ unwrapTSExpression,
6
+ } from "../server/lang-detect.ts";
7
+ import { parseSource } from "../shared/parser.ts";
8
+ import { type AstNode, walkAST } from "../shared/utils/ast-walk.ts";
9
+ import { deadCodeElimination } from "./dead-code-elimination.ts";
10
+
11
+ interface SplitDevPage {
12
+ contract: string;
13
+ render: string;
14
+ }
15
+
16
+ function node(value: unknown): AstNode | undefined {
17
+ if (value && typeof value === "object" && "type" in value) {
18
+ return unwrapTSExpression(value as AstNode) as AstNode;
19
+ }
20
+ }
21
+
22
+ function namesIn(value: unknown): Set<string> {
23
+ const names = new Set<string>();
24
+ walkAST(value, (entry) => {
25
+ if (
26
+ (entry.type === "Identifier" || entry.type === "JSXIdentifier") &&
27
+ typeof entry.name === "string"
28
+ ) {
29
+ names.add(entry.name);
30
+ }
31
+ });
32
+ return names;
33
+ }
34
+
35
+ const CALLBACK_BINDING_TYPES = new Set([
36
+ "ArrowFunctionExpression",
37
+ "CatchClause",
38
+ "ClassDeclaration",
39
+ "ClassExpression",
40
+ "FunctionDeclaration",
41
+ "FunctionExpression",
42
+ "VariableDeclarator",
43
+ ]);
44
+
45
+ function callbackBindings(callback: AstNode): Set<string> {
46
+ const bindings = new Set<string>();
47
+ walkAST(callback, (entry) => {
48
+ if (!CALLBACK_BINDING_TYPES.has(entry.type)) {
49
+ return;
50
+ }
51
+ const patterns = [entry.id, entry.param, ...(Array.isArray(entry.params) ? entry.params : [])];
52
+ for (const pattern of patterns) {
53
+ for (const name of namesIn(pattern)) {
54
+ bindings.add(name);
55
+ }
56
+ }
57
+ });
58
+ return bindings;
59
+ }
60
+
61
+ function defineRouteBindings(imports: AstNode[]): Set<string> {
62
+ const bindings = new Set<string>();
63
+ for (const declaration of imports) {
64
+ const specifier = node(declaration.source)?.value;
65
+ if (specifier !== "furin" && specifier !== "@teyik0/furin") {
66
+ continue;
67
+ }
68
+ for (const entry of declaration.specifiers as AstNode[]) {
69
+ const local = node(entry.local)?.name;
70
+ if (node(entry.imported)?.name === "defineRoute" && typeof local === "string") {
71
+ bindings.add(local);
72
+ }
73
+ }
74
+ }
75
+ return bindings;
76
+ }
77
+
78
+ function inspectModule(statements: AstNode[]) {
79
+ const imports = statements.filter((statement) => statement.type === "ImportDeclaration");
80
+ let localBindings = new Set<string>();
81
+ let terminal: AstNode | undefined;
82
+ for (const statement of statements) {
83
+ const declaration = statement.type.startsWith("Export")
84
+ ? node(statement.declaration)
85
+ : statement;
86
+ if (declaration?.type === "VariableDeclaration") {
87
+ for (const binding of declaration.declarations as AstNode[]) {
88
+ localBindings = localBindings.union(namesIn(binding.id));
89
+ if (statement.type === "ExportNamedDeclaration" && node(binding.id)?.name === "route") {
90
+ terminal = node(binding.init);
91
+ }
92
+ }
93
+ } else if (declaration) {
94
+ localBindings = localBindings.union(namesIn(declaration.id));
95
+ }
96
+ }
97
+ return { imports, localBindings, terminal };
98
+ }
99
+
100
+ function inlinePage(terminal: AstNode | undefined, bindings: Set<string>): AstNode | undefined {
101
+ const callee = node(terminal?.callee);
102
+ const args = terminal?.arguments as AstNode[] | undefined;
103
+ const callback = node(args?.[0]);
104
+ if (
105
+ terminal?.type !== "CallExpression" ||
106
+ callee?.type !== "MemberExpression" ||
107
+ callee.computed ||
108
+ node(callee.property)?.name !== "page" ||
109
+ args?.length !== 1 ||
110
+ !callback ||
111
+ (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression")
112
+ ) {
113
+ return;
114
+ }
115
+ let root = node(callee.object);
116
+ while (root?.type === "CallExpression" || root?.type === "MemberExpression") {
117
+ root = node(root.type === "CallExpression" ? root.callee : root.object);
118
+ }
119
+ if (typeof root?.name === "string" && bindings.has(root.name)) {
120
+ return callback;
121
+ }
122
+ }
123
+
124
+ function hasLexicalCapture(callback: AstNode, program: unknown): boolean {
125
+ let opaque = false;
126
+ walkAST(program, (entry) => {
127
+ if (
128
+ (entry.type === "VariableDeclaration" && entry.kind === "var") ||
129
+ (entry.type === "Identifier" && entry.name === "eval")
130
+ ) {
131
+ opaque = true;
132
+ }
133
+ if (entry.start < callback.start || entry.end > callback.end) {
134
+ return;
135
+ }
136
+ if (
137
+ entry.type === "ThisExpression" ||
138
+ entry.type === "MetaProperty" ||
139
+ (entry.type === "Identifier" && (entry.name === "eval" || entry.name === "arguments"))
140
+ ) {
141
+ opaque = true;
142
+ }
143
+ });
144
+ return opaque;
145
+ }
146
+
147
+ function routeHasConsumers(statements: AstNode[]): boolean {
148
+ let references = 0;
149
+ for (const statement of statements) {
150
+ if (statement.type === "ImportDeclaration") {
151
+ continue;
152
+ }
153
+ walkAST(statement, (entry) => {
154
+ if (
155
+ (entry.type === "Identifier" || entry.type === "JSXIdentifier") &&
156
+ entry.name === "route"
157
+ ) {
158
+ references += 1;
159
+ }
160
+ });
161
+ }
162
+ return references !== 1; // The declaration itself accounts for one reference.
163
+ }
164
+
165
+ /** Split only a top-level route with an inline page that captures imports, not module state. */
166
+ export function splitDevPage(
167
+ source: string,
168
+ filePath: string,
169
+ renderSpecifier: string
170
+ ): SplitDevPage | undefined {
171
+ if (!source.includes(".page") || source.includes("@jsx")) {
172
+ return;
173
+ }
174
+ const lang = detectLangFromPath(filePath);
175
+ const { program, diagnostics } = parseSource(source, lang);
176
+ if (diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
177
+ return;
178
+ }
179
+ const statements = program.body as unknown as AstNode[];
180
+ if (routeHasConsumers(statements)) {
181
+ return;
182
+ }
183
+ const { imports, localBindings, terminal } = inspectModule(statements);
184
+ const callback = inlinePage(terminal, defineRouteBindings(imports));
185
+ if (!callback || hasLexicalCapture(callback, program)) {
186
+ return;
187
+ }
188
+ const shadowed = callbackBindings(callback);
189
+ if (
190
+ imports.some((entry) =>
191
+ (entry.specifiers as AstNode[]).some((specifier) =>
192
+ shadowed.has(String(node(specifier.local)?.name))
193
+ )
194
+ )
195
+ ) {
196
+ return;
197
+ }
198
+ const references = namesIn(callback);
199
+ const bindings = localBindings.union(
200
+ new Set(
201
+ imports.flatMap((entry) =>
202
+ (entry.specifiers as AstNode[]).map((specifier) => String(node(specifier.local)?.name))
203
+ )
204
+ )
205
+ );
206
+ if (
207
+ [...localBindings].some((name) => references.has(name)) ||
208
+ ["__furinDeferredRender", "Object", "Symbol", "Error"].some((name) => bindings.has(name))
209
+ ) {
210
+ return;
211
+ }
212
+ const renderImports = imports.filter((entry) =>
213
+ (entry.specifiers as AstNode[]).some((specifier) =>
214
+ references.has(String(node(specifier.local)?.name))
215
+ )
216
+ );
217
+ const rewritten = new MagicString(source);
218
+ rewritten.overwrite(callback.start, callback.end, "__furinDeferredRender");
219
+ const contract = deadCodeElimination(rewritten, source, lang).toString();
220
+ // Splitting without removing an import cannot avoid loading any dependency.
221
+ const scanner = new Bun.Transpiler({ loader: detectLoaderFromPath(filePath) });
222
+ const retained = new Set(scanner.scanImports(contract).map((entry) => entry.path));
223
+ if (!renderImports.some((entry) => !retained.has(String(node(entry.source)?.value)))) {
224
+ return;
225
+ }
226
+ const fragment = `${renderImports.map((entry) => source.slice(entry.start, entry.end)).join("\n")}\nexport default ${source.slice(callback.start, callback.end)};`;
227
+ return {
228
+ contract: `const __furinDeferredRender = Object.assign(() => { throw new Error("Unresolved Furin page"); }, { [Symbol.for("furin.dev.render")]: () => import(${JSON.stringify(renderSpecifier)}) });\n${contract}`,
229
+ render: deadCodeElimination(new MagicString(fragment), source, lang).toString(),
230
+ };
231
+ }
@@ -6,6 +6,7 @@ const MINIMUM_REACT_19_PATCH = new Map([
6
6
  [0, 6],
7
7
  [1, 7],
8
8
  [2, 6],
9
+ [3, 0],
9
10
  ]);
10
11
 
11
12
  export interface RscVersions {
@@ -23,10 +24,14 @@ export function assertCompatibleRscVersions(versions: RscVersions): void {
23
24
  );
24
25
  }
25
26
  const match = STABLE_REACT_VERSION.exec(versions.react);
27
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: exec returns null for unsupported versions.
26
28
  const major = Number(match?.[1]);
29
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: exec returns null for unsupported versions.
27
30
  const minor = Number(match?.[2]);
31
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: exec returns null for unsupported versions.
28
32
  const patch = Number(match?.[3]);
29
33
  const minimumPatch = MINIMUM_REACT_19_PATCH.get(minor);
34
+ // biome-ignore lint/suspicious/noUnnecessaryConditions: exec returns null for unsupported versions.
30
35
  if (!match || major !== 19 || minimumPatch === undefined || patch < minimumPatch) {
31
36
  throw new Error("[furin/rsc] RSC requires a supported patched React 19 version.");
32
37
  }