@teyik0/furin 0.9.0-alpha.0 → 0.9.0-alpha.2

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 (100) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/runtime-build.d.ts +7 -3
  3. package/dist/adapter/vercel.js +31 -6
  4. package/dist/build/client.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -12
  6. package/dist/build/entry-template.ts +3 -15
  7. package/dist/build/hydrate.d.ts +6 -1
  8. package/dist/build/index.d.ts +1 -1
  9. package/dist/build/index.js +565 -401
  10. package/dist/build/route-metadata.d.ts +2 -2
  11. package/dist/build/route-types.d.ts +1 -1
  12. package/dist/build/types.d.ts +10 -4
  13. package/dist/cli/dev-worker.ts +10 -4
  14. package/dist/cli/index.js +624 -445
  15. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  16. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  17. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  18. package/dist/client/define-route.d.ts +14 -0
  19. package/dist/client/internal/runtime-types.d.ts +8 -0
  20. package/dist/client/link.js +20 -17
  21. package/dist/client/router/link-utils.d.ts +3 -2
  22. package/dist/client/router/search/index.js +2 -2
  23. package/dist/client/router/types.d.ts +9 -3
  24. package/dist/client.js +22 -6
  25. package/dist/config.d.ts +4 -0
  26. package/dist/config.js +4 -1
  27. package/dist/define-route.d.ts +53 -12
  28. package/dist/furin.d.ts +13 -3
  29. package/dist/furin.js +815 -661
  30. package/dist/plugin/route-config.d.ts +3 -3
  31. package/dist/plugin/route-manifest.d.ts +46 -0
  32. package/dist/plugin/route-tree.d.ts +13 -29
  33. package/dist/routes.d.ts +2 -2
  34. package/dist/server/dev/runtime.d.ts +2 -1
  35. package/dist/server/internal.d.ts +6 -0
  36. package/dist/server/internal.js +97 -114
  37. package/dist/server/registrations.d.ts +4 -2
  38. package/dist/server/render/index.d.ts +0 -1
  39. package/dist/server/render/index.ts +0 -1
  40. package/dist/server/render/shell.d.ts +1 -13
  41. package/dist/server/render/shell.ts +1 -90
  42. package/dist/server/router/defined-route.d.ts +4 -0
  43. package/dist/server/router/discovery.d.ts +14 -4
  44. package/dist/server/router/hmr.d.ts +12 -12
  45. package/dist/server/router/patterns.d.ts +4 -12
  46. package/dist/server/router/types.d.ts +16 -1
  47. package/dist/server/static-export.js +128 -158
  48. package/dist/server/sync/drizzle/index.d.ts +8 -10
  49. package/dist/shared/not-found.d.ts +1 -1
  50. package/dist/shared/route-specificity.d.ts +10 -1
  51. package/package.json +8 -11
  52. package/src/adapter/package.ts +11 -37
  53. package/src/adapter/runtime-build.ts +5 -4
  54. package/src/adapter/static.ts +1 -1
  55. package/src/adapter/vercel.ts +2 -1
  56. package/src/build/client.ts +3 -3
  57. package/src/build/discover-pages-process.ts +1 -1
  58. package/src/build/elysia-aot.ts +2 -2
  59. package/src/build/entry-template.ts +3 -15
  60. package/src/build/hydrate.ts +12 -6
  61. package/src/build/index.ts +19 -9
  62. package/src/build/route-metadata.ts +15 -8
  63. package/src/build/route-types.ts +18 -43
  64. package/src/build/types.ts +12 -5
  65. package/src/cli/config.ts +6 -0
  66. package/src/cli/dev-worker.ts +10 -4
  67. package/src/cli/dev.ts +41 -26
  68. package/src/cli/index.ts +30 -14
  69. package/src/client/define-route.ts +29 -4
  70. package/src/client/internal/runtime-types.ts +8 -0
  71. package/src/client/link.tsx +21 -22
  72. package/src/client/router/context.ts +8 -7
  73. package/src/client/router/link-utils.ts +16 -8
  74. package/src/client/router/provider.tsx +5 -0
  75. package/src/client/router/types.ts +40 -14
  76. package/src/config.ts +5 -0
  77. package/src/define-route.ts +85 -16
  78. package/src/furin.ts +31 -7
  79. package/src/plugin/dev-routes.ts +8 -17
  80. package/src/plugin/route-config.ts +77 -62
  81. package/src/plugin/route-manifest.ts +437 -0
  82. package/src/plugin/route-modules.ts +6 -1
  83. package/src/plugin/route-registry.ts +7 -21
  84. package/src/plugin/route-tree.ts +71 -181
  85. package/src/routes.ts +2 -2
  86. package/src/server/dev/runtime.ts +16 -22
  87. package/src/server/internal.ts +4 -1
  88. package/src/server/registrations.ts +5 -2
  89. package/src/server/render/index.ts +0 -1
  90. package/src/server/render/shell.ts +1 -90
  91. package/src/server/render/static-params.ts +2 -10
  92. package/src/server/router/defined-route.ts +8 -0
  93. package/src/server/router/discovery.ts +237 -196
  94. package/src/server/router/hmr.ts +45 -63
  95. package/src/server/router/patterns.ts +41 -117
  96. package/src/server/router/types.ts +17 -1
  97. package/src/server/sync/drizzle/index.ts +18 -19
  98. package/src/shared/not-found.ts +1 -1
  99. package/src/shared/route-specificity.ts +34 -2
  100. package/src/shared/utils/index.ts +1 -1
@@ -5,6 +5,8 @@ import type { HeadOptions, RenderingMode } from "./client.ts";
5
5
  import { applySchemaDefaults, coerceRouteInput } from "./server/router/schemas.ts";
6
6
  import type { FurinSchema, FurinUnwrap, FurinUnwrapInput } from "./shared/elysia-contract.ts";
7
7
  import { getSchemaValidator, isTypeBoxObjectSchema } from "./shared/elysia-contract.ts";
8
+ import type { ErrorComponent } from "./shared/error.ts";
9
+ import type { NotFoundComponent } from "./shared/not-found.ts";
8
10
  import type { RemountDependency, RemountDeps } from "./shared/page-key.ts";
9
11
 
10
12
  type NoFields = NonNullable<unknown>;
@@ -344,22 +346,45 @@ function routeHandler(route: FurinRouteKey) {
344
346
  };
345
347
  }
346
348
 
349
+ interface ElysiaPathParams {
350
+ [name: string]: string | undefined;
351
+ }
352
+
353
+ /**
354
+ * Elysia names a catch-all `*`; routes read it as `_splat`, as in TanStack
355
+ * Start. A transform hook runs before validation, so params schemas see it.
356
+ */
357
+ function renameSplatParam(context: { params: ElysiaPathParams | undefined }): void {
358
+ if (context.params !== undefined && "*" in context.params) {
359
+ const { "*": splat, ...params } = context.params;
360
+ context.params = { ...params, _splat: splat };
361
+ }
362
+ }
363
+
347
364
  function registerPlain(route: FurinRouteKey) {
348
- return new Elysia().get("", routeHandler(route));
365
+ return new Elysia().get("", { transform: renameSplatParam }, routeHandler(route));
349
366
  }
350
367
 
351
368
  function registerSchema<
352
369
  ParamsSchema extends FurinSchema,
353
370
  QuerySchema extends FurinSchema | undefined,
354
371
  >(route: FurinRouteKey, paramsSchema: ParamsSchema, querySchema: QuerySchema) {
355
- return new Elysia().get("", { params: paramsSchema, query: querySchema }, routeHandler(route));
372
+ return new Elysia().get(
373
+ "",
374
+ { params: paramsSchema, query: querySchema, transform: renameSplatParam },
375
+ routeHandler(route)
376
+ );
356
377
  }
357
378
 
358
379
  function registerQuery<QuerySchema extends FurinSchema>(
359
380
  route: FurinRouteKey,
360
381
  querySchema: QuerySchema
361
382
  ) {
362
- return new Elysia().get("", { query: querySchema }, routeHandler(route));
383
+ return new Elysia().get(
384
+ "",
385
+ { query: querySchema, transform: renameSplatParam },
386
+ routeHandler(route)
387
+ );
363
388
  }
364
389
 
365
390
  function schemaValues(value: unknown): SchemaValues {
@@ -622,14 +647,16 @@ type KindCheck<
622
647
  ? ValidComponent
623
648
  : FurinTypeError<
624
649
  Terminal extends "page"
625
- ? "this route file is a layout (_route): finish it with layout()"
626
- : "this route file is a page: finish it with page(); layouts live in _route files"
650
+ ? "this route file is a layout: finish it with layout()"
651
+ : "this route file is a page: finish it with page()"
627
652
  >;
628
653
 
629
654
  interface ChainRuntime {
655
+ errorComponent: ErrorComponent | undefined;
630
656
  head: unknown;
631
657
  loader: unknown;
632
658
  metadata: RouteMetadata;
659
+ notFoundComponent: NotFoundComponent | undefined;
633
660
  paramsSchema: FurinSchema | undefined;
634
661
  querySchema: FurinSchema | undefined;
635
662
  requestLoader: unknown;
@@ -638,19 +665,33 @@ interface ChainRuntime {
638
665
  // Named stages keep compile errors readable, e.g. "Property 'staticParams'
639
666
  // does not exist on type 'SsrRouteStage<...>'".
640
667
 
668
+ /** `.error()` / `.notFound()` keep the stage they are called on. */
669
+ type BoundaryMethods = "error" | "notFound";
670
+
671
+ interface BoundaryStage<Stage> {
672
+ error: (component: ErrorComponent) => Stage;
673
+ notFound: (component: NotFoundComponent) => Stage;
674
+ }
675
+
641
676
  /** SSR routes render per request: `staticParams()` needs mode `ssg` or `isr`. */
642
- interface SsrRouteStage<State extends ChainState> extends Omit<RouteChain<State>, "staticParams"> {}
677
+ interface SsrRouteStage<State extends ChainState>
678
+ extends Omit<RouteChain<State>, "staticParams" | BoundaryMethods>,
679
+ BoundaryStage<SsrRouteStage<State>> {}
643
680
 
644
681
  /** `staticParams()` must come first and only once, before `requestLoader()`. */
645
682
  interface StaticParamsClosedStage<State extends ChainState>
646
- extends Omit<RouteChain<State>, "staticParams"> {}
683
+ extends Omit<RouteChain<State>, "staticParams" | BoundaryMethods>,
684
+ BoundaryStage<StaticParamsClosedStage<State>> {}
647
685
 
648
686
  /** After `loader()`: attach `head()` or finish with `page()`/`layout()`. */
649
687
  interface LoadedRouteStage<State extends ChainState>
650
- extends Pick<RouteChain<State>, "head" | "layout" | "page"> {}
688
+ extends Pick<RouteChain<State>, "head" | "layout" | "page">,
689
+ BoundaryStage<LoadedRouteStage<State>> {}
651
690
 
652
691
  /** `head()` metadata is page-only: a headed route can only finish with `page()`. */
653
- interface HeadedPageStage<State extends ChainState> extends Pick<RouteChain<State>, "page"> {}
692
+ interface HeadedPageStage<State extends ChainState>
693
+ extends Pick<RouteChain<State>, "page">,
694
+ BoundaryStage<HeadedPageStage<State>> {}
654
695
 
655
696
  type ConfiguredStage<State extends ChainState> = State["mode"] extends infer Mode
656
697
  ? Mode extends "ssr"
@@ -669,6 +710,8 @@ type ElysiaOfSchemas<Schemas> = Schemas extends {
669
710
 
670
711
  type RouteTerminal<State extends ChainState> = {
671
712
  __type: "FURIN_ROUTE";
713
+ errorComponent: ErrorComponent | undefined;
714
+ notFoundComponent: NotFoundComponent | undefined;
672
715
  head:
673
716
  | Head<State["params"], State["query"], State["parentData"], State["data"], State["mode"]>
674
717
  | undefined;
@@ -745,9 +788,20 @@ function schemaFields(paramsSchema: FurinSchema | undefined, querySchema: FurinS
745
788
  }
746
789
 
747
790
  function terminalFields(runtime: ChainRuntime) {
748
- const { head, loader, metadata, paramsSchema, querySchema, requestLoader } = runtime;
791
+ const {
792
+ errorComponent,
793
+ head,
794
+ loader,
795
+ metadata,
796
+ notFoundComponent,
797
+ paramsSchema,
798
+ querySchema,
799
+ requestLoader,
800
+ } = runtime;
749
801
  return {
750
802
  __type: "FURIN_ROUTE" as const,
803
+ errorComponent,
804
+ notFoundComponent,
751
805
  mode: metadata.mode,
752
806
  revalidate: metadata.revalidate,
753
807
  remountDeps: metadata.remountDeps,
@@ -767,6 +821,19 @@ class RouteChain<State extends ChainState> {
767
821
  this.runtime = runtime;
768
822
  }
769
823
 
824
+ /**
825
+ * TanStack style: renders in place of this route (in its parent's outlet)
826
+ * when it or a route below it fails, as `errorComponent` does.
827
+ */
828
+ error(component: ErrorComponent): this {
829
+ return new RouteChain<State>({ ...this.runtime, errorComponent: component }) as this;
830
+ }
831
+
832
+ /** TanStack style: renders when this route or one below it calls `notFound()`. */
833
+ notFound(component: NotFoundComponent): this {
834
+ return new RouteChain<State>({ ...this.runtime, notFoundComponent: component }) as this;
835
+ }
836
+
770
837
  requestLoader<Data extends RequestLoaderData>(
771
838
  requestLoader: RequestLoader<State["params"], State["query"], Data>
772
839
  ): StaticParamsClosedStage<WithState<State, { requestData: Data }>> {
@@ -840,9 +907,11 @@ interface ConfigOptions {
840
907
  function configure(options: RouteMetadata & ConfigOptions): unknown {
841
908
  assertStaticParamsOutsideConfig(options);
842
909
  return new RouteChain({
910
+ errorComponent: undefined,
843
911
  head: undefined,
844
912
  loader: undefined,
845
913
  metadata: options,
914
+ notFoundComponent: undefined,
846
915
  paramsSchema: options.params,
847
916
  querySchema: options.query,
848
917
  requestLoader: undefined,
@@ -850,7 +919,7 @@ function configure(options: RouteMetadata & ConfigOptions): unknown {
850
919
  }
851
920
 
852
921
  /**
853
- * Stage for `pages/root.tsx` — the document shell has no layout above it, so
922
+ * Stage for the root layout — the document shell has no layout above it, so
854
923
  * `config()` requires only `mode` (the TanStack `createRootRoute` analogue).
855
924
  */
856
925
  class UnconfiguredRootRoute {
@@ -906,10 +975,10 @@ class UnconfiguredRootRoute {
906
975
  }
907
976
 
908
977
  /**
909
- * First stage of the builder, `defineRoute("/board/[boardId]")`: `config()` is
978
+ * First stage of the builder, `defineRoute("/board/$boardId/")`: `config()` is
910
979
  * MANDATORY and declares at least `mode`. The generated `FileRoutes` entry
911
980
  * supplies the parent layout, the path params and the terminal (`layout()` for
912
- * `_route` files, `page()` otherwise), so `config()` takes no `layout` and
981
+ * layout files, `page()` otherwise), so `config()` takes no `layout` and
913
982
  * `params` only refines the path params.
914
983
  */
915
984
  class UnconfiguredFileRoute<Entry> {
@@ -967,9 +1036,9 @@ class UnconfiguredFileRoute<Entry> {
967
1036
  }
968
1037
 
969
1038
  /**
970
- * `defineRoute(id)` keys the route by its file id (the app's prefix, then the
971
- * path under `pagesDir` with brackets and groups, `/index` dropped, layouts
972
- * ending in `/_route`) and reads its parent from the generated `FileRoutes`.
1039
+ * `defineRoute(id)` keys the route by its TanStack Start id (the app's
1040
+ * prefix, then `/board/$boardId/` for an index, `/board` for a layout, in
1041
+ * both routing styles) and reads its parent from the generated `FileRoutes`.
973
1042
  * The id is type-only: the runtime chain comes from the pages tree.
974
1043
  */
975
1044
  export function defineRoute<Id extends FileRouteId>(
package/src/furin.ts CHANGED
@@ -2,6 +2,7 @@ import { dirname, resolve } from "node:path";
2
2
  import { type AnyElysia, Elysia, NotFound } from "elysia";
3
3
  import type { RequestLogger } from "evlog";
4
4
  import { FURIN_RENDER_DECORATOR, type FurinNativeRouteContext } from "./define-route.ts";
5
+ import type { RouteStyle } from "./plugin/route-manifest.ts";
5
6
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
6
7
  import type { PageCacheAdapter } from "./server/cache/page-cache.ts";
7
8
  import { setPageCacheAdapter } from "./server/cache/page-cache-state.ts";
@@ -88,6 +89,12 @@ type FurinApplication<App extends AnyElysia> =
88
89
  >
89
90
  : never;
90
91
 
92
+ /** Each style's conventional pages directory: Next.js `app/`, TanStack Start `routes/`. */
93
+ const DEFAULT_PAGES_DIRS: { [Style in RouteStyle]: string } = {
94
+ nextjs: "src/app",
95
+ tanstack: "src/routes",
96
+ };
97
+
91
98
  /** Options for the {@link furin} plugin. */
92
99
  export interface FurinOptions {
93
100
  /**
@@ -125,6 +132,7 @@ export interface FurinOptions {
125
132
  * process-local cache.
126
133
  */
127
134
  pageCache?: PageCacheAdapter;
135
+ /** Defaults to `src/app` in the `nextjs` style and `src/routes` in the `tanstack` style. */
128
136
  pagesDir?: string;
129
137
  /**
130
138
  * Full physical mount path of this app, e.g. `"/admin"`. All pages,
@@ -137,6 +145,13 @@ export interface FurinOptions {
137
145
  * two prefixes, throws.
138
146
  */
139
147
  prefix?: string;
148
+ /**
149
+ * File-routing convention of `pagesDir`: `"nextjs"` (App Router: `layout.tsx`,
150
+ * `page.tsx`, `[id]`, `error.tsx`) or `"tanstack"` (TanStack Start:
151
+ * `__root.tsx`, `route.tsx`, `$id`, flat `a.$b.tsx`). Both key
152
+ * `defineRoute(id)` with TanStack Start ids.
153
+ */
154
+ style: RouteStyle;
140
155
  /**
141
156
  * Configures Furin's sync event stream with the required adapter. The
142
157
  * optional `path` defaults to `/_furin/sync`. Omit this option or pass
@@ -220,13 +235,14 @@ async function createFurinApp(options: FurinOptions): Promise<{
220
235
  logger,
221
236
  pageCache,
222
237
  pagesDir,
238
+ style,
223
239
  sync,
224
240
  } = options;
225
241
  const prefix = normalizePrefix(options.prefix);
226
242
  const cwd = process.cwd();
227
243
  // In a deployed binary the cwd-resolved pagesDir may differ from the build
228
244
  // machine's; the compile context is found by the (stable) declared prefix.
229
- const paramPagesDir = resolve(cwd, pagesDir ?? "src/pages");
245
+ const paramPagesDir = resolve(cwd, pagesDir ?? DEFAULT_PAGES_DIRS[style]);
230
246
  const ctx = getCompileContext(paramPagesDir, prefix);
231
247
  const resolvedPagesDir = ctx?.rootPath ? dirname(ctx.rootPath) : paramPagesDir;
232
248
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
@@ -270,6 +286,7 @@ async function createFurinApp(options: FurinOptions): Promise<{
270
286
  ? await (await import("./server/dev/runtime.ts")).createDevRuntime(
271
287
  instance,
272
288
  resolvedPagesDir,
289
+ style,
273
290
  modeOptions
274
291
  )
275
292
  : await createProdRuntime(instance, ctx, clientDir, modeOptions);
@@ -322,22 +339,28 @@ const mountedPrefixes = new WeakMap<AnyElysia, Map<string, FurinInstance>>();
322
339
  *
323
340
  * ```ts
324
341
  * new Elysia()
325
- * .use(await furin({ pagesDir: "./src/pages" }))
326
- * .use(await furin({ pagesDir: "./src/admin", prefix: "/admin" }))
342
+ * .use(await furin({ style: "tanstack" }))
343
+ * .use(await furin({ pagesDir: "./src/admin", prefix: "/admin", style: "nextjs" }))
327
344
  * .listen(3000)
328
345
  * ```
329
346
  */
330
- export async function furin(options?: FurinOptions) {
347
+ export async function furin(options: FurinOptions) {
348
+ if (options.style !== "nextjs" && options.style !== "tanstack") {
349
+ throw new Error(
350
+ `[furin] furin() requires style: "nextjs" or "tanstack", received ${JSON.stringify(options.style)}.`
351
+ );
352
+ }
331
353
  const registration = {
332
- pagesDir: options?.pagesDir ?? "src/pages",
333
- prefix: normalizePrefix(options?.prefix),
354
+ pagesDir: options.pagesDir ?? DEFAULT_PAGES_DIRS[options.style],
355
+ prefix: normalizePrefix(options.prefix),
356
+ style: options.style,
334
357
  };
335
358
  if (recordFurinRegistration(registration)) {
336
359
  // The build only discovers mounts: no runtime, nothing to mount.
337
360
  return <ParentApp extends AnyElysia>(parentApp: ParentApp) =>
338
361
  parentApp as unknown as FurinApplication<ParentApp>;
339
362
  }
340
- const { app, hasSync, instance } = await createFurinApp(options ?? {});
363
+ const { app, hasSync, instance } = await createFurinApp(options);
341
364
  let mounted = false;
342
365
  return <ParentApp extends AnyElysia>(parentApp: ParentApp): FurinApplication<ParentApp> => {
343
366
  if (mounted) {
@@ -367,6 +390,7 @@ export async function furin(options?: FurinOptions) {
367
390
 
368
391
  export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
369
392
  export { HeadContent, Scripts } from "./client/document.tsx";
393
+ export type { RouteStyle } from "./plugin/route-manifest.ts";
370
394
  export type { Register } from "./routes.ts";
371
395
  export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
372
396
  export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
@@ -3,7 +3,6 @@ import { dirname, relative, resolve, sep } from "node:path";
3
3
  import { type AnyElysia, Elysia } from "elysia";
4
4
  import { type FurinNativeRouteContext, getFurinRenderer } from "../define-route.ts";
5
5
  import { detectLoaderFromPath, SCRIPT_FILE_FILTER } from "../server/lang-detect.ts";
6
- import { isRouteGroup } from "../server/router/patterns.ts";
7
6
  import { routeModuleSourceVersion } from "../server/router/source-version.ts";
8
7
  import { type RouteModule, routeModuleDependencies, validateRouteParams } from "./route-modules.ts";
9
8
  import {
@@ -14,7 +13,6 @@ import {
14
13
  type RouteTreeNode,
15
14
  routeModuleSpecifier,
16
15
  routeSnapshotSourcePaths,
17
- segmentPath,
18
16
  } from "./route-tree.ts";
19
17
 
20
18
  const DEV_ROUTE_WATCHERS_SYMBOL = Symbol.for("@teyik0/furin/dev-route-watchers");
@@ -380,28 +378,21 @@ async function composableRouteApps(route: RouteFile): Promise<DevRoutesApps | un
380
378
  }
381
379
 
382
380
  async function composeRuntimeNode(node: RouteTreeNode): Promise<DevRoutesApps> {
383
- const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
384
- const { fileRoutes } = node;
385
- const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
381
+ const { pages, prefix } = node;
382
+ const [layoutApps, pageApps, childApps] = await Promise.all([
386
383
  node.layout ? composableRouteApps(node.layout) : undefined,
387
- node.indexRoute ? composableRouteApps(node.indexRoute) : undefined,
388
- Promise.all(fileRoutes.map((route) => composableRouteApps(route))),
384
+ Promise.all(pages.map((route) => composableRouteApps(route))),
389
385
  Promise.all(node.children.map((child) => composeRuntimeNode(child))),
390
386
  ]);
391
387
  const appScope = layoutApps?.app ?? new Elysia();
392
388
  const shellScope = layoutApps?.shell ?? new Elysia();
393
389
 
394
- if (indexRouteApps) {
395
- appScope.use(new Elysia({ prefix: "" }).use(indexRouteApps.app));
396
- shellScope.use(new Elysia({ prefix: "" }).use(indexRouteApps.shell));
397
- }
398
- for (const [index, route] of fileRoutes.entries()) {
399
- const routeApps = fileRouteApps[index];
390
+ for (const [index, route] of pages.entries()) {
391
+ const routeApps = pageApps[index];
400
392
  if (routeApps) {
401
- const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
402
- appScope.use(new Elysia({ prefix: `/${segment}` }).use(routeApps.app));
393
+ appScope.use(new Elysia({ prefix: route.prefix }).use(routeApps.app));
403
394
  if (route.path !== "/*") {
404
- shellScope.use(new Elysia({ prefix: `/${segment}` }).use(routeApps.shell));
395
+ shellScope.use(new Elysia({ prefix: route.prefix }).use(routeApps.shell));
405
396
  }
406
397
  }
407
398
  }
@@ -420,7 +411,7 @@ async function composeRuntimeInstance(instance: RouteInstanceSpec): Promise<DevR
420
411
  const { registerDevPagePlugin } = await import("../server/dev-page-plugin.ts");
421
412
  registerDevPagePlugin();
422
413
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
423
- return composeRuntimeNode(buildRouteTree(instance.pagesDir, instanceId));
414
+ return composeRuntimeNode(buildRouteTree(instance, instanceId));
424
415
  }
425
416
 
426
417
  /**
@@ -1,12 +1,17 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { basename, join, relative, resolve } from "node:path";
2
+ import { relative, resolve } from "node:path";
3
3
  import type { CallExpression, Node, ObjectExpression, ObjectProperty, Program } from "yuku-parser";
4
4
  import type { DevDiagnosticStore } from "../server/dev/diagnostics.ts";
5
5
  import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
6
- import { parseDynamicRouteSegment } from "../server/router/patterns.ts";
7
6
  import { parseSource } from "../shared/parser.ts";
8
7
  import { collectDefineRouteBindings, exportedRouteChain } from "./route-chains.ts";
9
- import { fileRouteId, type RouteInstanceSpec, routeSourcePaths } from "./route-tree.ts";
8
+ import {
9
+ type ManifestRoute,
10
+ type RouteInstanceSpec,
11
+ type RouteManifest,
12
+ type RouteParam,
13
+ scanRouteManifest,
14
+ } from "./route-manifest.ts";
10
15
 
11
16
  /**
12
17
  * Static route-config checks shared by the dev server and `furin build`.
@@ -21,9 +26,7 @@ export interface RouteConfigIssue {
21
26
  message: string;
22
27
  }
23
28
 
24
- const EXTENSION_RE = /\.(?:[cm]?[jt]sx?)$/;
25
29
  const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
26
- const PATH_SEPARATOR_RE = /[\\/]/;
27
30
 
28
31
  interface Import {
29
32
  imported: string;
@@ -46,10 +49,6 @@ interface ParsedRoute {
46
49
  source: string;
47
50
  }
48
51
 
49
- function withoutExtension(path: string): string {
50
- return path.replace(EXTENSION_RE, "");
51
- }
52
-
53
52
  function propertyName(key: Node | null): string | undefined {
54
53
  if (key?.type === "Identifier") {
55
54
  return key.name;
@@ -149,11 +148,11 @@ function issueAt(file: string, parsed: ParsedRoute, node: Node, message: string)
149
148
  */
150
149
  function checkKey(
151
150
  file: string,
152
- instance: RouteInstanceSpec,
151
+ route: ManifestRoute,
153
152
  parsed: ParsedRoute
154
153
  ): RouteConfigIssue | undefined {
155
154
  const { config, head, id } = parsed.route;
156
- const expected = fileRouteId(instance, file);
155
+ const expected = route.id;
157
156
  if (!id) {
158
157
  return issueAt(
159
158
  file,
@@ -200,11 +199,11 @@ function suggestedMode(route: RouteExport, isRoot: boolean): string {
200
199
 
201
200
  function checkFactory(
202
201
  file: string,
203
- instance: RouteInstanceSpec,
202
+ manifestRoute: ManifestRoute | undefined,
204
203
  parsed: ParsedRoute
205
204
  ): RouteConfigIssue | undefined {
206
205
  const { route } = parsed;
207
- const isRoot = withoutExtension(file) === join(instance.pagesDir, "root");
206
+ const isRoot = manifestRoute === undefined;
208
207
  if (isRoot === route.isRootFactory) {
209
208
  return;
210
209
  }
@@ -214,14 +213,14 @@ function checkFactory(
214
213
  file,
215
214
  parsed,
216
215
  route.head,
217
- `root.tsx must use defineRootRoute(), which has no parent layout:\n import { defineRootRoute } from "@teyik0/furin";\n export const route = defineRootRoute().config({ mode: "${mode}" })`
216
+ `The root layout must use defineRootRoute(), which has no parent layout:\n import { defineRootRoute } from "@teyik0/furin";\n export const route = defineRootRoute().config({ mode: "${mode}" })`
218
217
  );
219
218
  }
220
219
  return issueAt(
221
220
  file,
222
221
  parsed,
223
222
  route.head,
224
- `defineRootRoute() is reserved for root.tsx. Use defineRoute with this file's id:\n import { defineRoute } from "@teyik0/furin";\n export const route = defineRoute("${fileRouteId(instance, file)}").config({ mode: "${mode}" })`
223
+ `defineRootRoute() is reserved for the root layout. Use defineRoute with this file's id:\n import { defineRoute } from "@teyik0/furin";\n export const route = defineRoute("${manifestRoute.id}").config({ mode: "${mode}" })`
225
224
  );
226
225
  }
227
226
 
@@ -269,24 +268,15 @@ function declaredParams(route: RouteExport): Set<string> | true {
269
268
  return new Set(keys.filter((key) => key !== undefined));
270
269
  }
271
270
 
272
- /** Dynamic segments of the file's path missing from `declared`. */
273
- function undeclaredSegments(
274
- file: string,
275
- pagesDir: string,
276
- declared: Set<string> | true
277
- ): { key: string; segment: string }[] {
278
- return withoutExtension(relative(pagesDir, file))
279
- .split(PATH_SEPARATOR_RE)
280
- .flatMap((segment) => {
281
- const dynamic = parseDynamicRouteSegment(segment, file);
282
- return dynamic ? [{ key: dynamic.catchAll ? "*" : dynamic.name, segment }] : [];
283
- })
284
- .filter(({ key }) => declared !== true && !declared.has(key));
271
+ /** Path params of the route missing from `declared`. */
272
+ function undeclaredParams(route: ManifestRoute, declared: Set<string> | true): RouteParam[] {
273
+ return route.params.filter(({ name }) => declared !== true && !declared.has(name));
285
274
  }
286
275
 
287
- function paramsSchema(segments: { key: string }[]): string {
288
- const fields = segments.map(
289
- ({ key }) => `${IDENTIFIER_RE.test(key) ? key : JSON.stringify(key)}: t.String()`
276
+ function paramsSchema(params: RouteParam[]): string {
277
+ const fields = params.map(
278
+ ({ name, optional }) =>
279
+ `${IDENTIFIER_RE.test(name) ? name : JSON.stringify(name)}: ${optional ? "t.Optional(t.String())" : "t.String()"}`
290
280
  );
291
281
  return `params: t.Object({ ${fields.join(", ")} })`;
292
282
  }
@@ -294,10 +284,10 @@ function paramsSchema(segments: { key: string }[]): string {
294
284
  /** Static twin of `validateRouteParams()`, which rejects the page once its module loads. */
295
285
  function checkParams(
296
286
  file: string,
297
- pagesDir: string,
287
+ route: ManifestRoute,
298
288
  parsed: ParsedRoute
299
289
  ): RouteConfigIssue | undefined {
300
- const missing = undeclaredSegments(file, pagesDir, declaredParams(parsed.route));
290
+ const missing = undeclaredParams(route, declaredParams(parsed.route));
301
291
  if (missing.length === 0) {
302
292
  return;
303
293
  }
@@ -308,43 +298,68 @@ function checkParams(
308
298
  file,
309
299
  parsed,
310
300
  parsed.route.config ?? parsed.route.head,
311
- `The URL segment${plural ? "s" : ""} ${missing.map(({ segment }) => segment).join(", ")} ${plural ? "are" : "is"} missing from this page's params schema. Each page declares every dynamic segment of its path, including those of its layouts. Add to config():${tImport}\n ${paramsSchema(missing)}`
301
+ `The path param${plural ? "s" : ""} ${missing.map(({ name }) => name).join(", ")} ${plural ? "are" : "is"} missing from this page's params schema. Each page declares every dynamic segment of its path, including those of its layouts. Add to config():${tImport}\n ${paramsSchema(missing)}`
302
+ );
303
+ }
304
+
305
+ /** Next.js-style apps declare boundaries as files, TanStack-style ones on the route. */
306
+ function checkBoundaryMethods(
307
+ file: string,
308
+ instance: RouteInstanceSpec,
309
+ parsed: ParsedRoute
310
+ ): RouteConfigIssue | undefined {
311
+ const method = ["error", "notFound"].find((name) => parsed.route.methods.has(name));
312
+ if (instance.style !== "nextjs" || method === undefined) {
313
+ return;
314
+ }
315
+ const convention = method === "error" ? "an error.tsx" : "a not-found.tsx";
316
+ return issueAt(
317
+ file,
318
+ parsed,
319
+ parsed.route.head,
320
+ `.${method}() is the TanStack style. In the nextjs style, default-export the component from ${convention} next to this route.`
312
321
  );
313
322
  }
314
323
 
315
324
  function checkRoute(
316
325
  file: string,
317
326
  instance: RouteInstanceSpec,
327
+ route: ManifestRoute | undefined,
318
328
  parsed: ParsedRoute
319
329
  ): (RouteConfigIssue | undefined)[] {
320
- const factory = checkFactory(file, instance, parsed);
330
+ const factory = checkFactory(file, route, parsed);
321
331
  if (factory) {
322
332
  return [factory];
323
333
  }
324
- const isLayout = basename(withoutExtension(file)) === "_route";
325
334
  return [
326
335
  checkConfig(file, parsed),
327
- parsed.route.isRootFactory ? undefined : checkKey(file, instance, parsed),
336
+ route === undefined ? undefined : checkKey(file, route, parsed),
328
337
  checkMode(file, parsed),
329
- parsed.route.isRootFactory || isLayout
330
- ? undefined
331
- : checkParams(file, instance.pagesDir, parsed),
338
+ route === undefined || route.kind === "layout" ? undefined : checkParams(file, route, parsed),
339
+ checkBoundaryMethods(file, instance, parsed),
332
340
  ];
333
341
  }
334
342
 
335
- function routeFiles(pagesDir: string): string[] {
336
- const root = join(pagesDir, "root.tsx");
337
- return [
338
- ...(existsSync(root) ? [root] : []),
339
- ...routeSourcePaths({ pagesDir, prefix: "" }),
340
- ].toSorted((left, right) => left.localeCompare(right));
343
+ /** The root layout (`undefined` route) and every route file, sorted. */
344
+ function routeFiles(manifest: RouteManifest): [string, ManifestRoute | undefined][] {
345
+ // Issues and scaffolded files report native paths, as the editor opens them.
346
+ const files: [string, ManifestRoute | undefined][] = manifest.routes.map((route) => [
347
+ resolve(route.sourcePath),
348
+ route,
349
+ ]);
350
+ if (existsSync(manifest.rootPath)) {
351
+ files.push([resolve(manifest.rootPath), undefined]);
352
+ }
353
+ return files.toSorted(([left], [right]) => left.localeCompare(right));
341
354
  }
342
355
 
343
- export function validateRouteConfig({ pagesDir, prefix }: RouteInstanceSpec): RouteConfigIssue[] {
344
- const instance = { pagesDir: resolve(pagesDir), prefix };
345
- return routeFiles(instance.pagesDir).flatMap((file) => {
356
+ export function validateRouteConfig(spec: RouteInstanceSpec): RouteConfigIssue[] {
357
+ const instance = { ...spec, pagesDir: resolve(spec.pagesDir) };
358
+ return routeFiles(scanRouteManifest(instance)).flatMap(([file, route]) => {
346
359
  const parsed = parseRoute(file);
347
- return parsed ? checkRoute(file, instance, parsed).filter((issue) => issue !== undefined) : [];
360
+ return parsed
361
+ ? checkRoute(file, instance, route, parsed).filter((issue) => issue !== undefined)
362
+ : [];
348
363
  });
349
364
  }
350
365
 
@@ -420,15 +435,15 @@ export const route = defineRootRoute()
420
435
  ));
421
436
  `;
422
437
 
423
- function scaffoldTemplate(file: string, instance: RouteInstanceSpec): string {
424
- if (withoutExtension(file) === join(instance.pagesDir, "root")) {
438
+ function scaffoldTemplate(route: ManifestRoute | undefined): string {
439
+ if (route === undefined) {
425
440
  return ROOT_TEMPLATE;
426
441
  }
427
- const isLayout = basename(withoutExtension(file)) === "_route";
428
- const params = undeclaredSegments(file, instance.pagesDir, new Set());
442
+ const isLayout = route.kind === "layout";
443
+ const { params } = route;
429
444
  return `import { defineRoute } from "@teyik0/furin";${params.length > 0 ? '\nimport { t } from "elysia";' : ""}
430
445
 
431
- export const route = defineRoute("${fileRouteId(instance, file)}")
446
+ export const route = defineRoute("${route.id}")
432
447
  .config({ mode: "${isLayout ? "ssr" : "ssg"}"${params.length > 0 ? `, ${paramsSchema(params)}` : ""} })
433
448
  .${isLayout ? "layout(({ children }) => children)" : "page(() => null)"};
434
449
  `;
@@ -438,14 +453,14 @@ export const route = defineRoute("${fileRouteId(instance, file)}")
438
453
  * Writes a starter route, keyed by the file's id, into route files that are
439
454
  * empty or whitespace-only, the only case where Furin writes to a source file.
440
455
  */
441
- export function scaffoldEmptyRoutes({ pagesDir, prefix }: RouteInstanceSpec): string[] {
442
- const instance = { pagesDir: resolve(pagesDir), prefix };
456
+ export function scaffoldEmptyRoutes(spec: RouteInstanceSpec): string[] {
457
+ const instance = { ...spec, pagesDir: resolve(spec.pagesDir) };
443
458
  const written: string[] = [];
444
- for (const file of routeFiles(instance.pagesDir).filter(
445
- (path) => readSource(path)?.trim() === ""
446
- )) {
447
- writeFileSync(file, scaffoldTemplate(file, instance));
448
- written.push(file);
459
+ for (const [file, route] of routeFiles(scanRouteManifest(instance))) {
460
+ if (readSource(file)?.trim() === "") {
461
+ writeFileSync(file, scaffoldTemplate(route));
462
+ written.push(file);
463
+ }
449
464
  }
450
465
  return written;
451
466
  }