@teyik0/furin 0.9.0-alpha.1 → 0.9.0-alpha.3

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 (91) hide show
  1. package/dist/adapter/runtime-build.d.ts +7 -3
  2. package/dist/adapter/vercel.js +31 -6
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/entry-template.d.ts +3 -12
  5. package/dist/build/entry-template.ts +3 -15
  6. package/dist/build/hydrate.d.ts +6 -1
  7. package/dist/build/index.d.ts +1 -1
  8. package/dist/build/index.js +597 -445
  9. package/dist/build/route-metadata.d.ts +2 -2
  10. package/dist/build/route-types.d.ts +1 -1
  11. package/dist/build/types.d.ts +10 -4
  12. package/dist/cli/index.js +626 -466
  13. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  14. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  15. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  16. package/dist/client/define-route.d.ts +14 -0
  17. package/dist/client/dev-error-overlay.ts +18 -0
  18. package/dist/client/internal/runtime-types.d.ts +8 -0
  19. package/dist/client/link.js +3 -3
  20. package/dist/client/router/link-utils.d.ts +3 -2
  21. package/dist/client/router/search/index.js +2 -2
  22. package/dist/client/router/types.d.ts +9 -3
  23. package/dist/client.js +22 -6
  24. package/dist/config.d.ts +4 -0
  25. package/dist/config.js +4 -1
  26. package/dist/define-route.d.ts +53 -12
  27. package/dist/furin.d.ts +13 -3
  28. package/dist/furin.js +771 -616
  29. package/dist/plugin/client-plugin.d.ts +1 -1
  30. package/dist/plugin/index.js +5 -4
  31. package/dist/plugin/route-config.d.ts +3 -3
  32. package/dist/plugin/route-manifest.d.ts +46 -0
  33. package/dist/plugin/route-tree.d.ts +13 -29
  34. package/dist/routes.d.ts +2 -2
  35. package/dist/server/dev/runtime.d.ts +2 -1
  36. package/dist/server/internal.d.ts +6 -0
  37. package/dist/server/internal.js +57 -76
  38. package/dist/server/registrations.d.ts +4 -2
  39. package/dist/server/router/defined-route.d.ts +4 -0
  40. package/dist/server/router/discovery.d.ts +14 -4
  41. package/dist/server/router/hmr.d.ts +12 -12
  42. package/dist/server/router/patterns.d.ts +4 -12
  43. package/dist/server/router/types.d.ts +16 -1
  44. package/dist/server/static-export.js +88 -120
  45. package/dist/server/sync/drizzle/index.d.ts +8 -10
  46. package/dist/shared/route-specificity.d.ts +10 -1
  47. package/package.json +4 -7
  48. package/src/adapter/package.ts +11 -37
  49. package/src/adapter/runtime-build.ts +5 -4
  50. package/src/adapter/static.ts +1 -1
  51. package/src/adapter/vercel.ts +2 -1
  52. package/src/build/client.ts +3 -3
  53. package/src/build/discover-pages-process.ts +1 -1
  54. package/src/build/elysia-aot.ts +2 -2
  55. package/src/build/entry-template.ts +3 -15
  56. package/src/build/hydrate.ts +14 -6
  57. package/src/build/index.ts +19 -9
  58. package/src/build/route-metadata.ts +15 -8
  59. package/src/build/route-types.ts +18 -43
  60. package/src/build/types.ts +12 -5
  61. package/src/cli/config.ts +6 -0
  62. package/src/cli/index.ts +30 -14
  63. package/src/client/define-route.ts +29 -4
  64. package/src/client/dev-error-overlay.ts +18 -0
  65. package/src/client/internal/runtime-types.ts +8 -0
  66. package/src/client/router/link-utils.ts +16 -8
  67. package/src/client/router/types.ts +40 -14
  68. package/src/config.ts +5 -0
  69. package/src/define-route.ts +85 -16
  70. package/src/furin.ts +31 -7
  71. package/src/plugin/client-plugin.ts +13 -8
  72. package/src/plugin/dev-routes.ts +8 -17
  73. package/src/plugin/route-config.ts +77 -62
  74. package/src/plugin/route-manifest.ts +437 -0
  75. package/src/plugin/route-modules.ts +6 -1
  76. package/src/plugin/route-registry.ts +11 -42
  77. package/src/plugin/route-tree.ts +71 -181
  78. package/src/routes.ts +2 -2
  79. package/src/server/dev/runtime.ts +16 -22
  80. package/src/server/dev-page-plugin.ts +5 -2
  81. package/src/server/internal.ts +4 -1
  82. package/src/server/registrations.ts +5 -2
  83. package/src/server/render/static-params.ts +2 -10
  84. package/src/server/router/defined-route.ts +8 -0
  85. package/src/server/router/discovery.ts +237 -196
  86. package/src/server/router/hmr.ts +45 -63
  87. package/src/server/router/patterns.ts +41 -117
  88. package/src/server/router/types.ts +17 -1
  89. package/src/server/sync/drizzle/index.ts +18 -19
  90. package/src/shared/route-specificity.ts +34 -2
  91. package/src/shared/utils/index.ts +1 -1
package/dist/furin.js CHANGED
@@ -58,7 +58,7 @@ function segmentSpecificity(segment) {
58
58
  }
59
59
  return segment.startsWith(":") ? 2 : 3;
60
60
  }
61
- function compareRouteSpecificity(a, b) {
61
+ function compareConcreteSpecificity(a, b) {
62
62
  const aSegments = a.split("/").filter(Boolean);
63
63
  const bSegments = b.split("/").filter(Boolean);
64
64
  const length = Math.max(aSegments.length, bSegments.length);
@@ -78,6 +78,24 @@ function compareRouteSpecificity(a, b) {
78
78
  }
79
79
  return 0;
80
80
  }
81
+ function expandOptionalSegments(pattern) {
82
+ let variants = [[]];
83
+ for (const segment of pattern.split("/").filter(Boolean)) {
84
+ if (segment.startsWith(":") && segment.endsWith("?")) {
85
+ const required = segment.slice(0, -1);
86
+ variants = variants.flatMap((variant) => [variant, [...variant, required]]);
87
+ } else {
88
+ variants = variants.map((variant) => [...variant, segment]);
89
+ }
90
+ }
91
+ return variants.map((variant) => `/${variant.join("/")}`);
92
+ }
93
+ function mostSpecificVariant(pattern) {
94
+ return expandOptionalSegments(pattern).reduce((best, variant) => compareConcreteSpecificity(variant, best) > 0 ? variant : best);
95
+ }
96
+ function compareRouteSpecificity(a, b) {
97
+ return compareConcreteSpecificity(mostSpecificVariant(a), mostSpecificVariant(b));
98
+ }
81
99
 
82
100
  // src/shared/search-params.ts
83
101
  function isObject(value) {
@@ -188,18 +206,6 @@ function findSearchDefaultsForRouteTarget(to, routes) {
188
206
  var init_search_params = () => {};
189
207
 
190
208
  // src/server/router/patterns.ts
191
- import { parse } from "path";
192
- function collectIntermediateLayoutDirs(pagePath, rootPath) {
193
- const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
194
- const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
195
- const layoutDirs = [];
196
- let dir = pageDir;
197
- while (dir.length > pagesDir.length) {
198
- layoutDirs.unshift(dir);
199
- dir = dir.slice(0, dir.lastIndexOf("/"));
200
- }
201
- return layoutDirs;
202
- }
203
209
  function resolveRouteRevalidate(page) {
204
210
  return page.revalidate ?? page._route.revalidate;
205
211
  }
@@ -239,57 +245,6 @@ function resolveMode(page, routeChain) {
239
245
  }
240
246
  return "ssr";
241
247
  }
242
- function parseDynamicRouteSegment(segment, sourcePath) {
243
- if (!(segment.startsWith("[") && segment.endsWith("]"))) {
244
- return;
245
- }
246
- const inner = segment.slice(1, -1);
247
- const catchAll = inner.startsWith("...");
248
- const name = catchAll ? inner.slice(3) : inner;
249
- if (!DYNAMIC_PARAMETER_NAME_RE.test(name)) {
250
- throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(name)} in ${JSON.stringify(sourcePath ?? segment)}. Parameter names must match ${DYNAMIC_PARAMETER_NAME_RE}.`);
251
- }
252
- return { catchAll, name };
253
- }
254
- function routeSegmentToPattern(segment) {
255
- const dynamic = parseDynamicRouteSegment(segment, undefined);
256
- if (!dynamic) {
257
- return segment;
258
- }
259
- return dynamic.catchAll ? "*" : `:${dynamic.name}`;
260
- }
261
- function isRouteGroup(segment) {
262
- return ROUTE_GROUP_RE.test(segment);
263
- }
264
- function routePatternKey(pattern) {
265
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
266
- }
267
- function filePathToPattern(path) {
268
- const parts = path.replaceAll("\\", "/").split("/");
269
- const segments = [];
270
- const lastIndex = parts.length - 1;
271
- for (let idx = 0;idx < parts.length; idx += 1) {
272
- const part = parts[idx];
273
- if (part === undefined || part.length === 0) {
274
- continue;
275
- }
276
- const isFile = idx === lastIndex;
277
- const name = isFile ? parse(part).name : part;
278
- if (!isFile && isRouteGroup(name)) {
279
- continue;
280
- }
281
- if (isFile && name === "index") {
282
- continue;
283
- }
284
- const dynamic = parseDynamicRouteSegment(name, path);
285
- if (dynamic) {
286
- segments.push(dynamic.catchAll ? "*" : `:${dynamic.name}`);
287
- } else {
288
- segments.push(name);
289
- }
290
- }
291
- return `/${segments.join("/")}`;
292
- }
293
248
  function escapeRegExp(value) {
294
249
  return value.replace(REGEX_META_CHARS_RE, "\\$&");
295
250
  }
@@ -304,11 +259,17 @@ function routePatternRegexSource(pattern, sources) {
304
259
  while (i < pattern.length && pattern[i] !== "/") {
305
260
  i += 1;
306
261
  }
307
- paramNames.push(pattern.slice(start, i));
308
- source += sources.param;
262
+ const name = pattern.slice(start, i);
263
+ if (name.endsWith("?") && source.endsWith("/")) {
264
+ paramNames.push(name.slice(0, -1));
265
+ source = `${source.slice(0, -1)}(?:/${sources.param})?`;
266
+ } else {
267
+ paramNames.push(name);
268
+ source += sources.param;
269
+ }
309
270
  } else if (pattern[i] === "*") {
310
- paramNames.push("*");
311
- source += sources.catchAll;
271
+ paramNames.push(SPLAT_PARAM);
272
+ source = source.endsWith("/") ? `${source.slice(0, -1)}(?:/${sources.catchAll})?` : source + sources.catchAll;
312
273
  i += 1;
313
274
  } else {
314
275
  const ch = pattern[i];
@@ -330,6 +291,25 @@ function buildRouteRegex(pattern) {
330
291
  regex: new RegExp(`^${source}${pattern === "/" || pattern.endsWith("/") ? "" : "/?"}$`)
331
292
  };
332
293
  }
294
+ function decodeParam(value) {
295
+ try {
296
+ return decodeURIComponent(value);
297
+ } catch {
298
+ return value;
299
+ }
300
+ }
301
+ function matchedParams(paramNames, match) {
302
+ const params = {};
303
+ for (const [index, name] of paramNames.entries()) {
304
+ const value = match[index + 1];
305
+ if (value !== undefined) {
306
+ params[name] = decodeParam(value);
307
+ } else if (name === SPLAT_PARAM) {
308
+ params[name] = "";
309
+ }
310
+ }
311
+ return params;
312
+ }
333
313
  function buildRouteMatcher(routes) {
334
314
  const compiled = routes.map((route) => {
335
315
  const { regex, paramNames } = buildRouteRegex(route.pattern);
@@ -341,27 +321,13 @@ function buildRouteMatcher(routes) {
341
321
  if (!match) {
342
322
  continue;
343
323
  }
344
- const params = {};
345
- for (let i = 0;i < candidate.paramNames.length; i += 1) {
346
- const name = candidate.paramNames[i];
347
- if (name !== undefined) {
348
- try {
349
- params[name] = decodeURIComponent(match[i + 1] ?? "");
350
- } catch {
351
- params[name] = match[i + 1] ?? "";
352
- }
353
- }
354
- }
355
- return { params, route: candidate.route };
324
+ return { params: matchedParams(candidate.paramNames, match), route: candidate.route };
356
325
  }
357
326
  return null;
358
327
  };
359
328
  }
360
- var DYNAMIC_PARAMETER_NAME_RE, ROUTE_GROUP_RE, DYNAMIC_ROUTE_SEGMENT_RE, REGEX_META_CHARS_RE;
329
+ var SPLAT_PARAM = "_splat", REGEX_META_CHARS_RE;
361
330
  var init_patterns = __esm(() => {
362
- DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
363
- ROUTE_GROUP_RE = /^\([^()]+\)$/;
364
- DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
365
331
  REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/g;
366
332
  });
367
333
 
@@ -654,14 +620,20 @@ function routeHandler(route) {
654
620
  return renderer(context, route);
655
621
  };
656
622
  }
623
+ function renameSplatParam(context) {
624
+ if (context.params !== undefined && "*" in context.params) {
625
+ const { "*": splat, ...params } = context.params;
626
+ context.params = { ...params, _splat: splat };
627
+ }
628
+ }
657
629
  function registerPlain(route) {
658
- return new Elysia().get("", routeHandler(route));
630
+ return new Elysia().get("", { transform: renameSplatParam }, routeHandler(route));
659
631
  }
660
632
  function registerSchema(route, paramsSchema, querySchema) {
661
- return new Elysia().get("", { params: paramsSchema, query: querySchema }, routeHandler(route));
633
+ return new Elysia().get("", { params: paramsSchema, query: querySchema, transform: renameSplatParam }, routeHandler(route));
662
634
  }
663
635
  function registerQuery(route, querySchema) {
664
- return new Elysia().get("", { query: querySchema }, routeHandler(route));
636
+ return new Elysia().get("", { query: querySchema, transform: renameSplatParam }, routeHandler(route));
665
637
  }
666
638
  function schemaValues(value) {
667
639
  return value !== null && typeof value === "object" ? value : {};
@@ -738,9 +710,20 @@ function schemaFields(paramsSchema, querySchema) {
738
710
  return querySchema === undefined ? {} : { schemas: { query: querySchema } };
739
711
  }
740
712
  function terminalFields(runtime) {
741
- const { head, loader, metadata, paramsSchema, querySchema, requestLoader } = runtime;
713
+ const {
714
+ errorComponent,
715
+ head,
716
+ loader,
717
+ metadata,
718
+ notFoundComponent,
719
+ paramsSchema,
720
+ querySchema,
721
+ requestLoader
722
+ } = runtime;
742
723
  return {
743
724
  __type: "FURIN_ROUTE",
725
+ errorComponent,
726
+ notFoundComponent,
744
727
  mode: metadata.mode,
745
728
  revalidate: metadata.revalidate,
746
729
  remountDeps: metadata.remountDeps,
@@ -758,6 +741,12 @@ class RouteChain {
758
741
  constructor(runtime) {
759
742
  this.runtime = runtime;
760
743
  }
744
+ error(component) {
745
+ return new RouteChain({ ...this.runtime, errorComponent: component });
746
+ }
747
+ notFound(component) {
748
+ return new RouteChain({ ...this.runtime, notFoundComponent: component });
749
+ }
761
750
  requestLoader(requestLoader) {
762
751
  return new RouteChain({
763
752
  ...this.runtime,
@@ -805,9 +794,11 @@ class RouteChain {
805
794
  function configure(options) {
806
795
  assertStaticParamsOutsideConfig(options);
807
796
  return new RouteChain({
797
+ errorComponent: undefined,
808
798
  head: undefined,
809
799
  loader: undefined,
810
800
  metadata: options,
801
+ notFoundComponent: undefined,
811
802
  paramsSchema: options.params,
812
803
  querySchema: options.query,
813
804
  requestLoader: undefined
@@ -4903,11 +4894,12 @@ function navigationHrefPolicy(href, currentOrigin) {
4903
4894
  return url.origin === currentOrigin ? "internal" : "external";
4904
4895
  }
4905
4896
  function applyLinkParams(to, params) {
4906
- if (!params) {
4907
- return to;
4897
+ const values = params ?? {};
4898
+ let url = to.replaceAll(/\/:([a-zA-Z0-9_]+)\?(?=\/|$)/g, (_match, name) => values[name] === undefined || values[name] === "" ? "" : `/${encodeURIComponent(String(values[name]))}`).replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in values) ? encodeURIComponent(String(values[name])) : match);
4899
+ if (url === "") {
4900
+ url = "/";
4908
4901
  }
4909
- let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
4910
- const wildcard = params["*"];
4902
+ const wildcard = values._splat;
4911
4903
  if (wildcard !== undefined && url.includes("/*")) {
4912
4904
  const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
4913
4905
  url = url.replace("/*", () => `/${encodedWildcard}`);
@@ -10325,7 +10317,7 @@ function validateRouteChain(chain, root, pagePath) {
10325
10317
  const hasRoot = chain.some((r) => r === root);
10326
10318
  if (!hasRoot) {
10327
10319
  const location = pagePath ? `in ${pagePath}` : "";
10328
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + "Its route chain must end at the root.tsx layout.");
10320
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + "Its route chain must end at the root layout.");
10329
10321
  }
10330
10322
  for (const route of chain) {
10331
10323
  if (hasCycle(route)) {
@@ -12868,7 +12860,7 @@ function memoizedBinarySearch(haystack, needle, state, key) {
12868
12860
  state.lastNeedle = needle;
12869
12861
  return state.lastIndex = binarySearch(haystack, needle, low, high);
12870
12862
  }
12871
- function parse2(map) {
12863
+ function parse(map) {
12872
12864
  return typeof map === "string" ? JSON.parse(map) : map;
12873
12865
  }
12874
12866
  function cast(map) {
@@ -12916,7 +12908,7 @@ var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_IND
12916
12908
  const isString = typeof map === "string";
12917
12909
  if (!isString && map._decodedMemo)
12918
12910
  return map;
12919
- const parsed = parse2(map);
12911
+ const parsed = parse(map);
12920
12912
  const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
12921
12913
  this.version = version;
12922
12914
  this.file = file;
@@ -14775,7 +14767,6 @@ var init_buffered_render = __esm(() => {
14775
14767
  });
14776
14768
 
14777
14769
  // src/server/render/static-params.ts
14778
- import { dirname as dirname2, relative as relative4 } from "path";
14779
14770
  function collectStaticParamsStages(route) {
14780
14771
  const stages = [];
14781
14772
  for (const [index, entry] of route.routeChain.entries()) {
@@ -14789,17 +14780,11 @@ function collectStaticParamsStages(route) {
14789
14780
  return stages;
14790
14781
  }
14791
14782
  function ancestorPattern(route, ancestors) {
14792
- const rootSourcePath = route.routeChain[0]?.sourcePath;
14793
14783
  const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
14794
- if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
14795
- return route.pattern;
14796
- }
14797
- const pagesDir = dirname2(rootSourcePath);
14798
- const ancestorDir = dirname2(ancestorSourcePath);
14799
- if (ancestorDir === pagesDir) {
14784
+ if (ancestors.length <= 1) {
14800
14785
  return "/";
14801
14786
  }
14802
- return filePathToPattern(`${relative4(pagesDir, ancestorDir)}/index.tsx`);
14787
+ return route.layouts.find(({ path }) => path === ancestorSourcePath)?.pattern ?? route.pattern;
14803
14788
  }
14804
14789
  function createBuildContext(pattern, params, origin) {
14805
14790
  const path = resolvePath(pattern, params);
@@ -14885,7 +14870,6 @@ async function resolveStaticParams(route, origin) {
14885
14870
  }
14886
14871
  var STATIC_PARAMS_CONCURRENCY = 4;
14887
14872
  var init_static_params = __esm(() => {
14888
- init_patterns();
14889
14873
  init_assemble();
14890
14874
  init_loaders();
14891
14875
  });
@@ -15119,176 +15103,280 @@ var init_internal = __esm(() => {
15119
15103
  _compileContexts = new Map;
15120
15104
  });
15121
15105
 
15122
- // src/plugin/route-tree.ts
15106
+ // src/plugin/route-manifest.ts
15123
15107
  import { existsSync as existsSync3, readdirSync } from "fs";
15124
- import { extname as extname2, join as join3, relative as relative6, resolve as resolve6 } from "path";
15125
- function instanceKey(instance) {
15126
- return `${resolve6(instance.pagesDir)}\x00${instance.prefix}`;
15108
+ import { extname as extname2 } from "path";
15109
+ function child(directory, name) {
15110
+ return `${directory}/${name}`;
15127
15111
  }
15128
- function routeModuleSpecifier(instance) {
15129
- return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
15112
+ function sortedEntries(directory) {
15113
+ return readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
15130
15114
  }
15131
- function scanRouteFiles(directory, directorySegments, files) {
15132
- const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
15133
- for (const entry of entries) {
15134
- if (entry.isDirectory()) {
15135
- if (entry.name.startsWith("_")) {
15136
- continue;
15137
- }
15138
- scanRouteFiles(join3(directory, entry.name), [...directorySegments, entry.name], files);
15139
- continue;
15140
- }
15141
- const extension = extname2(entry.name);
15142
- if (!ROUTE_EXTENSION.test(extension) || entry.name.endsWith(".d.ts")) {
15143
- continue;
15144
- }
15145
- const base = entry.name.slice(0, -extension.length);
15146
- const sourcePath = join3(directory, entry.name);
15147
- for (const segment of [...directorySegments, base]) {
15148
- parseDynamicRouteSegment(segment, sourcePath);
15115
+ function moduleBase(name) {
15116
+ if (name.endsWith(".d.ts") || !ROUTE_EXTENSION.test(name)) {
15117
+ return;
15118
+ }
15119
+ return name.slice(0, -extname2(name).length);
15120
+ }
15121
+ function findModule(directory, base) {
15122
+ return SOURCE_EXTENSIONS.map((extension) => child(directory, `${base}${extension}`)).find((path) => existsSync3(path));
15123
+ }
15124
+ function paramName(name, raw, sourcePath) {
15125
+ if (!PARAM_NAME.test(name)) {
15126
+ throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(raw)} in ${JSON.stringify(sourcePath)}. Parameter names must match ${PARAM_NAME}.`);
15127
+ }
15128
+ return name;
15129
+ }
15130
+ function splitFlatName(base) {
15131
+ const tokens = [];
15132
+ let current = "";
15133
+ let escaped = false;
15134
+ for (const character of base) {
15135
+ if (character === "[") {
15136
+ escaped = true;
15137
+ } else if (character === "]") {
15138
+ escaped = false;
15149
15139
  }
15150
- if (ROUTE_CONVENTIONS.has(base)) {
15140
+ if (character === "." && !escaped) {
15141
+ tokens.push(current);
15142
+ current = "";
15151
15143
  continue;
15152
15144
  }
15153
- if (base.startsWith("_") && base !== "_route") {
15154
- continue;
15145
+ current += character;
15146
+ }
15147
+ tokens.push(current);
15148
+ return tokens;
15149
+ }
15150
+ function tanstackSegment(raw, sourcePath) {
15151
+ if (raw.startsWith("(") && raw.endsWith(")")) {
15152
+ return { raw, type: "group" };
15153
+ }
15154
+ if (raw === "$") {
15155
+ return { raw, type: "splat" };
15156
+ }
15157
+ if (raw.startsWith("{-$") && raw.endsWith("}")) {
15158
+ return {
15159
+ name: paramName(raw.slice(3, -1), raw, sourcePath),
15160
+ optional: true,
15161
+ raw,
15162
+ type: "param"
15163
+ };
15164
+ }
15165
+ if (raw.startsWith("$")) {
15166
+ return { name: paramName(raw.slice(1), raw, sourcePath), optional: false, raw, type: "param" };
15167
+ }
15168
+ if (raw.startsWith("_")) {
15169
+ return { raw, type: "pathless" };
15170
+ }
15171
+ const value = (raw.endsWith("_") ? raw.slice(0, -1) : raw).replace(BRACKET_ESCAPE, "$1");
15172
+ return { raw, type: "static", value };
15173
+ }
15174
+ function tanstackCandidate(base, segments, sourcePath) {
15175
+ const tokens = splitFlatName(base);
15176
+ const last = tokens.at(-1);
15177
+ const index = last === "index";
15178
+ const routeFile = last === "route";
15179
+ const own = (index || routeFile ? tokens.slice(0, -1) : tokens).map((token) => tanstackSegment(token, sourcePath));
15180
+ const routeSegments = [...segments, ...own];
15181
+ if (routeFile && routeSegments.length === 0) {
15182
+ throw new Error(`[furin] ${sourcePath}: a top-level route.tsx has no path to wrap. The root layout lives in __root.tsx.`);
15183
+ }
15184
+ return {
15185
+ forcedLayout: routeFile || routeSegments.at(-1)?.type === "pathless",
15186
+ index,
15187
+ segments: routeSegments,
15188
+ sourcePath
15189
+ };
15190
+ }
15191
+ function scanTanstack(pagesDir) {
15192
+ const candidates = [];
15193
+ const walk = (directory, segments) => {
15194
+ for (const entry of sortedEntries(directory)) {
15195
+ if (entry.name.startsWith("-")) {
15196
+ continue;
15197
+ }
15198
+ const sourcePath = child(directory, entry.name);
15199
+ if (entry.isDirectory()) {
15200
+ walk(sourcePath, [...segments, tanstackSegment(entry.name, sourcePath)]);
15201
+ continue;
15202
+ }
15203
+ const base = moduleBase(entry.name);
15204
+ if (base !== undefined && !(segments.length === 0 && base === "__root")) {
15205
+ candidates.push(tanstackCandidate(base, segments, sourcePath));
15206
+ }
15155
15207
  }
15156
- files.push({
15157
- base,
15158
- directorySegments,
15208
+ };
15209
+ walk(pagesDir, []);
15210
+ return {
15211
+ boundaries: [],
15212
+ candidates,
15213
+ rootPath: findModule(pagesDir, "__root") ?? child(pagesDir, "__root.tsx")
15214
+ };
15215
+ }
15216
+ function nextSegment(name, sourcePath) {
15217
+ if (name.startsWith("(") && name.endsWith(")")) {
15218
+ return { raw: name, type: "group" };
15219
+ }
15220
+ const catchAll = name.match(NEXT_CATCH_ALL);
15221
+ if (catchAll?.[1] !== undefined) {
15222
+ paramName(catchAll[1], name, sourcePath);
15223
+ return { raw: "$", type: "splat" };
15224
+ }
15225
+ if (name.startsWith("[") && name.endsWith("]")) {
15226
+ const name_ = paramName(name.slice(1, -1), name, sourcePath);
15227
+ return { name: name_, optional: false, raw: `$${name_}`, type: "param" };
15228
+ }
15229
+ return { raw: name, type: "static", value: name };
15230
+ }
15231
+ function addNextFile(state, base, segments, sourcePath) {
15232
+ if (base === "route") {
15233
+ throw new Error(`[furin] ${sourcePath}: route handlers are not supported. Declare API routes on your Elysia app instead.`);
15234
+ }
15235
+ if (base === "layout" && segments.at(-1)?.type === "splat") {
15236
+ throw new Error(`[furin] ${sourcePath}: a layout cannot share a catch-all folder with its page: move it to the parent folder.`);
15237
+ }
15238
+ if (base === "page" || base === "layout" && segments.length > 0) {
15239
+ state.candidates.push({
15240
+ forcedLayout: base === "layout",
15241
+ index: base === "page" && segments.at(-1)?.type !== "splat",
15242
+ segments,
15159
15243
  sourcePath
15160
15244
  });
15245
+ } else if (base === "layout") {
15246
+ state.rootPath ??= sourcePath;
15247
+ } else if (base === "error") {
15248
+ state.boundary.errorPath ??= sourcePath;
15249
+ } else if (base === "not-found") {
15250
+ state.boundary.notFoundPath ??= sourcePath;
15161
15251
  }
15162
15252
  }
15163
- function fileRouteId({ pagesDir, prefix }, sourcePath) {
15164
- const path = relative6(pagesDir, sourcePath).replaceAll("\\", "/").replace(ROUTE_EXTENSION, "");
15165
- return `${prefix}/${path}`.replace(INDEX_SUFFIX, "") || "/";
15166
- }
15167
- function segmentPath(segment) {
15168
- return routeSegmentToPattern(segment);
15253
+ function scanNext(pagesDir) {
15254
+ const candidates = [];
15255
+ const boundaries = [];
15256
+ let rootPath;
15257
+ const walk = (directory, segments) => {
15258
+ const boundary = { directory, errorPath: undefined, notFoundPath: undefined };
15259
+ const state = { boundary, candidates, rootPath };
15260
+ for (const entry of sortedEntries(directory)) {
15261
+ const sourcePath = child(directory, entry.name);
15262
+ if (!entry.isDirectory()) {
15263
+ addNextFile(state, moduleBase(entry.name), segments, sourcePath);
15264
+ } else if (!entry.name.startsWith("_")) {
15265
+ walk(sourcePath, [...segments, nextSegment(entry.name, sourcePath)]);
15266
+ }
15267
+ }
15268
+ rootPath ??= state.rootPath;
15269
+ if (boundary.errorPath || boundary.notFoundPath) {
15270
+ boundaries.push(boundary);
15271
+ }
15272
+ };
15273
+ walk(pagesDir, []);
15274
+ boundaries.sort((left, right) => left.directory.length - right.directory.length);
15275
+ return { boundaries, candidates, rootPath: rootPath ?? child(pagesDir, "layout.tsx") };
15276
+ }
15277
+ function segmentKey(segments) {
15278
+ return segments.map((segment) => segment.raw).join("/");
15279
+ }
15280
+ function segmentPattern(segment) {
15281
+ switch (segment.type) {
15282
+ case "group":
15283
+ case "pathless":
15284
+ return;
15285
+ case "param":
15286
+ return `:${segment.name}${segment.optional ? "?" : ""}`;
15287
+ case "splat":
15288
+ return "*";
15289
+ default:
15290
+ return segment.value;
15291
+ }
15169
15292
  }
15170
- function routeId(instanceId, path) {
15171
- const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
15172
- return `_route_${instanceId}_${encodedPath}`;
15293
+ function urlPattern(segments) {
15294
+ return `/${segments.flatMap((segment) => segmentPattern(segment) ?? []).join("/")}`;
15173
15295
  }
15174
- function scanRouteManifest(pagesDir) {
15175
- const scannedFiles = [];
15176
- scanRouteFiles(pagesDir, [], scannedFiles);
15177
- const seenPatterns = new Map;
15178
- return scannedFiles.map((file) => {
15179
- if (file.base === "_route") {
15180
- return { ...file, pattern: undefined };
15181
- }
15182
- const relativePath = relative6(pagesDir, file.sourcePath).replaceAll("\\", "/");
15183
- const pattern = filePathToPattern(relativePath);
15184
- const patternKey = routePatternKey(pattern);
15185
- const previousPath = seenPatterns.get(patternKey);
15186
- if (previousPath !== undefined) {
15187
- throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
15188
- }
15189
- seenPatterns.set(patternKey, relativePath);
15190
- return { ...file, pattern };
15296
+ function routeParams(segments) {
15297
+ return segments.flatMap((segment) => {
15298
+ if (segment.type === "param") {
15299
+ return [{ name: segment.name, optional: segment.optional }];
15300
+ }
15301
+ return segment.type === "splat" ? [{ name: "_splat", optional: false }] : [];
15191
15302
  });
15192
15303
  }
15193
- function buildRouteTree(pagesDir, instanceId) {
15194
- const nodes = new Map;
15195
- const ensureNode = (segments) => {
15196
- const key = segments.join("/");
15197
- const existing = nodes.get(key);
15198
- if (existing) {
15199
- return existing;
15200
- }
15201
- const node = {
15202
- children: [],
15203
- fileRoutes: [],
15204
- indexRoute: undefined,
15205
- layout: undefined,
15206
- name: segments.at(-1) ?? ""
15207
- };
15208
- nodes.set(key, node);
15209
- if (segments.length > 0) {
15210
- ensureNode(segments.slice(0, -1)).children.push(node);
15211
- }
15212
- return node;
15213
- };
15214
- const root = ensureNode([]);
15215
- for (const file of scanRouteManifest(pagesDir)) {
15216
- const node = ensureNode(file.directorySegments);
15217
- if (file.pattern === undefined) {
15218
- const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
15219
- node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
15220
- continue;
15221
- }
15222
- const route = {
15223
- id: routeId(instanceId, file.pattern),
15224
- path: file.pattern,
15225
- sourcePath: file.sourcePath
15226
- };
15227
- if (file.base === "index") {
15228
- node.indexRoute = route;
15229
- } else {
15230
- node.fileRoutes.push(route);
15231
- }
15304
+ function assertSplatLast(candidate) {
15305
+ const splat = candidate.segments.findIndex((segment) => segment.type === "splat");
15306
+ if (splat !== -1 && splat < candidate.segments.length - 1) {
15307
+ throw new Error(`[furin] ${candidate.sourcePath}: a catch-all segment must be the last segment of its path.`);
15232
15308
  }
15233
- return root;
15234
15309
  }
15235
- function collectRouteFiles(root) {
15236
- const files = [];
15237
- const nodes = [root];
15238
- while (nodes.length > 0) {
15239
- const node = nodes.pop();
15240
- if (!node) {
15241
- continue;
15242
- }
15243
- if (node.layout) {
15244
- files.push(node.layout);
15245
- }
15246
- if (node.indexRoute) {
15247
- files.push(node.indexRoute);
15310
+ function patternKeys(pattern) {
15311
+ const keys = expandOptionalSegments(pattern).map((variant) => variant.replace(PARAM_SEGMENT, "$1:param"));
15312
+ return [...new Set(keys)];
15313
+ }
15314
+ function claimPatterns(seenPatterns, pattern, sourcePath, relativePath) {
15315
+ for (const patternKey of patternKeys(pattern)) {
15316
+ const previous = seenPatterns.get(patternKey);
15317
+ if (previous !== undefined) {
15318
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${relativePath(previous)}" and "${relativePath(sourcePath)}".`);
15248
15319
  }
15249
- files.push(...node.fileRoutes);
15250
- nodes.push(...node.children);
15320
+ seenPatterns.set(patternKey, sourcePath);
15251
15321
  }
15252
- return files;
15253
- }
15254
- function routeSourcePaths(instance) {
15255
- const instanceId = Bun.hash(instanceKey(instance)).toString(16);
15256
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve6(sourcePath)).toSorted((left, right) => left.localeCompare(right));
15257
15322
  }
15258
- function conventionSourcePaths(directory) {
15259
- const paths = [];
15260
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
15261
- if (entry.isDirectory()) {
15262
- if (!entry.name.startsWith("_")) {
15263
- paths.push(...conventionSourcePaths(join3(directory, entry.name)));
15264
- }
15265
- continue;
15266
- }
15267
- const extension = extname2(entry.name);
15268
- if (!ROUTE_EXTENSION.test(extension) || entry.name.endsWith(".d.ts")) {
15269
- continue;
15323
+ function buildManifest(scan, pagesDir, prefix) {
15324
+ const relativePath = (path) => path.slice(pagesDir.length + 1);
15325
+ const { candidates } = scan;
15326
+ const keys = candidates.map((candidate) => segmentKey(candidate.segments));
15327
+ const hasDescendant = (key, self2) => candidates.some((other, index) => other !== self2 && (keys[index]?.startsWith(`${key}/`) === true || other.index && keys[index] === key));
15328
+ const layouts = new Map;
15329
+ const kinds = candidates.map((candidate, index) => {
15330
+ assertSplatLast(candidate);
15331
+ const key = keys[index] ?? "";
15332
+ const isLayout = !candidate.index && (candidate.forcedLayout || hasDescendant(key, candidate));
15333
+ if (!isLayout) {
15334
+ return "page";
15270
15335
  }
15271
- const base = entry.name.slice(0, -extension.length);
15272
- if (base === "error" || base === "not-found") {
15273
- paths.push(resolve6(directory, entry.name));
15336
+ const existing = layouts.get(key);
15337
+ if (existing !== undefined) {
15338
+ throw new Error(`[furin] Two layouts wrap "/${key}": "${relativePath(existing)}" and "${relativePath(candidate.sourcePath)}".`);
15274
15339
  }
15275
- }
15276
- return paths;
15340
+ layouts.set(key, candidate.sourcePath);
15341
+ return "layout";
15342
+ });
15343
+ const seenIds = new Map;
15344
+ const seenPatterns = new Map;
15345
+ const routes = candidates.map((candidate, index) => {
15346
+ const kind = kinds[index] ?? "page";
15347
+ const { segments, sourcePath } = candidate;
15348
+ const key = keys[index] ?? "";
15349
+ let parentPath = candidate.index ? layouts.get(key) : undefined;
15350
+ for (let depth = segments.length - 1;parentPath === undefined && depth > 0; depth -= 1) {
15351
+ parentPath = layouts.get(segmentKey(segments.slice(0, depth)));
15352
+ }
15353
+ const path = `/${key}${candidate.index && key !== "" ? "/" : ""}`;
15354
+ const id = prefix === "" ? path : `${prefix}${path}`;
15355
+ const previousId = seenIds.get(id);
15356
+ if (previousId !== undefined) {
15357
+ throw new Error(`[furin] Duplicate route id "${id}" from "${relativePath(previousId)}" and "${relativePath(sourcePath)}".`);
15358
+ }
15359
+ seenIds.set(id, sourcePath);
15360
+ const pattern = urlPattern(segments);
15361
+ if (kind === "page") {
15362
+ claimPatterns(seenPatterns, pattern, sourcePath, relativePath);
15363
+ }
15364
+ return { id, kind, params: routeParams(segments), parentPath, pattern, sourcePath };
15365
+ });
15366
+ return { boundaries: scan.boundaries, rootPath: scan.rootPath, routes };
15277
15367
  }
15278
- function routeSnapshotSourcePaths(instance) {
15279
- const rootPath = resolve6(instance.pagesDir, "root.tsx");
15280
- return [
15281
- ...existsSync3(rootPath) ? [rootPath] : [],
15282
- ...routeSourcePaths(instance),
15283
- ...conventionSourcePaths(instance.pagesDir)
15284
- ].toSorted((left, right) => left.localeCompare(right));
15368
+ function scanRouteManifest({ pagesDir, prefix, style }) {
15369
+ const directory = pagesDir.replaceAll("\\", "/");
15370
+ return buildManifest(style === "nextjs" ? scanNext(directory) : scanTanstack(directory), directory, prefix);
15285
15371
  }
15286
- var ROUTE_EXTENSION, ROUTE_CONVENTIONS, INDEX_SUFFIX;
15287
- var init_route_tree = __esm(() => {
15288
- init_patterns();
15372
+ var ROUTE_EXTENSION, PARAM_NAME, BRACKET_ESCAPE, SOURCE_EXTENSIONS, PARAM_SEGMENT, NEXT_CATCH_ALL;
15373
+ var init_route_manifest = __esm(() => {
15289
15374
  ROUTE_EXTENSION = /\.(?:jsx?|tsx?)$/;
15290
- ROUTE_CONVENTIONS = new Set(["error", "not-found", "root"]);
15291
- INDEX_SUFFIX = /\/index$/;
15375
+ PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
15376
+ BRACKET_ESCAPE = /\[([^\]]*)\]/g;
15377
+ SOURCE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
15378
+ PARAM_SEGMENT = /(^|\/):[^/]+/g;
15379
+ NEXT_CATCH_ALL = /^\[\[?\.\.\.([^\]]+)\]\]?$/;
15292
15380
  });
15293
15381
 
15294
15382
  // src/server/router/defined-route.ts
@@ -15306,9 +15394,11 @@ function adaptDefinedLayout(route, parent, sourcePath) {
15306
15394
  const component = route.component;
15307
15395
  return {
15308
15396
  __type: "FURIN_ROUTE",
15397
+ errorComponent: route.errorComponent,
15309
15398
  layout: component,
15310
15399
  loader: route.loader,
15311
15400
  mode: route.mode,
15401
+ notFoundComponent: route.notFoundComponent,
15312
15402
  params: route.schemas?.params,
15313
15403
  ...parent ? { parent } : {},
15314
15404
  query: route.schemas?.query,
@@ -15333,9 +15423,11 @@ function adaptDefinedPage(route, parent) {
15333
15423
  requestLoader: route.requestLoader
15334
15424
  },
15335
15425
  component,
15426
+ errorComponent: route.errorComponent,
15336
15427
  head,
15337
15428
  loader: route.loader,
15338
15429
  mode: route.mode,
15430
+ notFoundComponent: route.notFoundComponent,
15339
15431
  revalidate: route.revalidate,
15340
15432
  staticParams: route.staticParams,
15341
15433
  tags: copyTags(route.tags)
@@ -15373,7 +15465,7 @@ function collectRouteTags(routeChain, page) {
15373
15465
  function loadProdRoutes(ctx) {
15374
15466
  const rootExport = ctx.modules[ctx.rootPath]?.route;
15375
15467
  if (!isDefinedRouteTerminal(rootExport) || typeof rootExport.layout !== "function") {
15376
- throw new Error("[furin] root.tsx: defineRootRoute().layout() not found in CompileContext.");
15468
+ throw new Error(`[furin] ${ctx.rootPath}: defineRootRoute().layout() not found in CompileContext.`);
15377
15469
  }
15378
15470
  const rootRoute = adaptDefinedLayout(rootExport, undefined, ctx.rootPath);
15379
15471
  function resolveModuleComponent(modPath) {
@@ -15383,26 +15475,28 @@ function loadProdRoutes(ctx) {
15383
15475
  return ctx.modules[modPath]?.default;
15384
15476
  }
15385
15477
  const root = {
15386
- error: resolveModuleComponent(ctx.rootConventions?.errorPath),
15387
- notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
15478
+ error: rootRoute.errorComponent ?? resolveModuleComponent(ctx.rootConventions?.errorPath),
15479
+ notFound: rootRoute.notFoundComponent ?? resolveModuleComponent(ctx.rootConventions?.notFoundPath),
15388
15480
  path: ctx.rootPath,
15389
15481
  route: rootRoute
15390
15482
  };
15391
15483
  const routes = [];
15392
15484
  for (const { pattern, path, mode } of ctx.routes) {
15393
- const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, path, root, ctx);
15485
+ const meta = ctx.routeMetadata?.[path];
15486
+ const layouts = meta?.layouts ?? [];
15487
+ const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, layouts, root, ctx);
15394
15488
  if (!page) {
15395
15489
  throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
15396
15490
  }
15397
15491
  const routeChain = collectRouteChainFromRoute(page._route);
15398
15492
  validateRouteChain(routeChain, root.route, path);
15399
- const meta = ctx.routeMetadata?.[path];
15400
- const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
15401
- ...b,
15402
- error: resolveModuleComponent(b.errorPath),
15403
- notFound: resolveModuleComponent(b.notFoundPath)
15493
+ const boundaries = (meta?.segmentBoundaries ?? []).map((boundary) => ({
15494
+ ...boundary,
15495
+ error: boundary.fromRoute ? routeBoundaryComponent(ctx, boundary.errorPath, "errorComponent") : resolveModuleComponent(boundary.errorPath),
15496
+ notFound: boundary.fromRoute ? routeBoundaryComponent(ctx, boundary.notFoundPath, "notFoundComponent") : resolveModuleComponent(boundary.notFoundPath)
15404
15497
  }));
15405
15498
  routes.push({
15499
+ layouts,
15406
15500
  mode,
15407
15501
  page,
15408
15502
  path,
@@ -15416,45 +15510,30 @@ function loadProdRoutes(ctx) {
15416
15510
  }
15417
15511
  return { root, routes };
15418
15512
  }
15419
- function resolveCompiledRuntimePage(module, path, root, context) {
15513
+ function routeBoundaryComponent(ctx, modulePath, field) {
15514
+ const route = modulePath ? ctx.modules[modulePath]?.route : undefined;
15515
+ return isDefinedRouteTerminal(route) ? route[field] : undefined;
15516
+ }
15517
+ function resolveCompiledRuntimePage(module, layouts, root, context) {
15420
15518
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
15421
15519
  return;
15422
15520
  }
15423
- const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
15424
- const parent = resolveCompiledLayoutParent(path, pagesDir, root.route, context);
15521
+ let parent = root.route;
15522
+ for (const { path } of layouts) {
15523
+ const layout = context.modules[path]?.route;
15524
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15525
+ throw invalidNestedLayoutError(path);
15526
+ }
15527
+ parent = adaptDefinedLayout(layout, parent, path);
15528
+ }
15425
15529
  return adaptDefinedPage(module.route, parent);
15426
15530
  }
15427
15531
  function invalidNestedLayoutError(layoutPath) {
15428
- return new Error(`[furin] ${layoutPath}: _route.tsx must export \`route = defineRoute(id).config({ mode }).layout(({ children }) => ...)\`, with the file's id. For example, in blog/_route.tsx:
15429
- export const route = defineRoute("/blog/_route")
15532
+ return new Error(`[furin] ${layoutPath}: a layout file must export \`route = defineRoute(id).config({ mode }).layout(({ children }) => ...)\`, with the file's id. For example, in board/route.tsx:
15533
+ export const route = defineRoute("/board")
15430
15534
  .config({ mode: "ssr" })
15431
15535
  .layout(({ children }) => <section>{children}</section>);`);
15432
15536
  }
15433
- function resolveCompiledLayoutParent(pagePath, pagesDir, rootRoute, context) {
15434
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
15435
- if (pageDirectory.length <= pagesDir.length) {
15436
- return rootRoute;
15437
- }
15438
- const segments = pageDirectory.slice(pagesDir.length + 1).split("/");
15439
- let directory = pagesDir;
15440
- let parent = rootRoute;
15441
- for (const segment of segments) {
15442
- directory = `${directory}/${segment}`;
15443
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15444
- const layoutModule = context.modules[candidate];
15445
- if (!layoutModule) {
15446
- continue;
15447
- }
15448
- const layout = layoutModule.route;
15449
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15450
- throw invalidNestedLayoutError(candidate);
15451
- }
15452
- parent = adaptDefinedLayout(layout, parent, candidate);
15453
- break;
15454
- }
15455
- }
15456
- return parent;
15457
- }
15458
15537
  function toPosixPath(path) {
15459
15538
  return path.replaceAll("\\", "/");
15460
15539
  }
@@ -15463,36 +15542,60 @@ function routeRelativePath(pagesDir, absolutePath) {
15463
15542
  const path = toPosixPath(absolutePath);
15464
15543
  return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
15465
15544
  }
15466
- async function scanPages(pagesDir) {
15467
- const dir = toPosixPath(pagesDir);
15468
- const root = await scanRootLayout(dir);
15469
- const routes = await scanPageFiles(dir, root);
15545
+ function manifestLayouts(manifest, route) {
15546
+ const byPath = new Map(manifest.routes.map((entry) => [entry.sourcePath, entry]));
15547
+ const layouts = [];
15548
+ for (let parent = route.parentPath;parent !== undefined; ) {
15549
+ const layout = byPath.get(parent);
15550
+ if (!layout) {
15551
+ break;
15552
+ }
15553
+ layouts.unshift({ path: layout.sourcePath, pattern: layout.pattern });
15554
+ parent = layout.parentPath;
15555
+ }
15556
+ return layouts;
15557
+ }
15558
+ async function scanPages(instance) {
15559
+ const pagesDir = toPosixPath(instance.pagesDir);
15560
+ const manifest = scanRouteManifest({ ...instance, pagesDir });
15561
+ const root = await scanRootLayout(manifest, pagesDir, instance.style);
15562
+ const routes = await scanPageFiles(manifest, pagesDir, instance.style, root);
15470
15563
  if (routes.some((route) => route.routeChain.some((entry) => entry.requestLoader))) {
15471
15564
  await annotateScannedRequestKeys(routes);
15472
15565
  }
15473
15566
  return { root, routes };
15474
15567
  }
15475
- async function scanRootLayout(pagesDir) {
15476
- const rootPath = `${pagesDir}/root.tsx`;
15568
+ async function scanRootLayout(manifest, pagesDir, style) {
15569
+ const { rootPath } = manifest;
15570
+ const rootFile = ROOT_FILE_NAMES[style];
15477
15571
  const ctx = getCompileContext();
15478
15572
  if (!(existsSync4(rootPath) || ctx?.modules[rootPath])) {
15479
- throw new Error(`[furin] root.tsx: not found in ${pagesDir}. Every pages directory needs a root layout:
15573
+ throw new Error(`[furin] ${rootFile}: not found in ${pagesDir}. Every pages directory needs a root layout:
15480
15574
  ${ROOT_EXAMPLE}`);
15481
15575
  }
15482
15576
  const mod = ctx?.modules[rootPath] ?? await (isDevelopment() ? import(`${rootPath}?furin-server&t=${routeModuleSourceVersion(rootPath)}`) : import(rootPath));
15483
15577
  const rootExport = mod.route;
15484
15578
  if (!isDefinedRouteTerminal(rootExport)) {
15485
- throw new Error(`[furin] ${rootPath}: root.tsx must export \`route = defineRootRoute().config({ mode }).layout(...)\`:
15579
+ throw new Error(`[furin] ${rootPath}: ${rootFile} must export \`route = defineRootRoute().config({ mode }).layout(...)\`:
15486
15580
  ${ROOT_EXAMPLE}`);
15487
15581
  }
15488
15582
  if (!rootExport.layout) {
15489
- throw new Error(`[furin] ${rootPath}: root.tsx: defineRootRoute() must end with .layout(({ children }) => ...):
15583
+ throw new Error(`[furin] ${rootPath}: ${rootFile}: defineRootRoute() must end with .layout(({ children }) => ...):
15490
15584
  ${ROOT_EXAMPLE}`);
15491
15585
  }
15492
15586
  const rootRoute = adaptDefinedLayout(rootExport, undefined, rootPath);
15587
+ if (style === "tanstack") {
15588
+ return {
15589
+ error: rootRoute.errorComponent,
15590
+ notFound: rootRoute.notFoundComponent,
15591
+ path: rootPath,
15592
+ route: rootRoute
15593
+ };
15594
+ }
15595
+ const rootBoundary = manifest.boundaries.find((boundary) => boundary.directory === pagesDir);
15493
15596
  const [notFoundEntry, errorEntry] = await Promise.all([
15494
- loadConventionComponent(pagesDir, "not-found"),
15495
- loadConventionComponent(pagesDir, "error")
15597
+ loadConventionComponent(rootBoundary?.notFoundPath, "not-found"),
15598
+ loadConventionComponent(rootBoundary?.errorPath, "error")
15496
15599
  ]);
15497
15600
  return {
15498
15601
  error: errorEntry?.component,
@@ -15503,91 +15606,100 @@ ${ROOT_EXAMPLE}`);
15503
15606
  route: rootRoute
15504
15607
  };
15505
15608
  }
15506
- function getSourceModuleCandidates(dir, name) {
15507
- return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
15508
- }
15509
- async function loadConventionComponent(dir, name) {
15609
+ async function loadConventionComponent(filePath, name) {
15610
+ if (filePath === undefined) {
15611
+ return;
15612
+ }
15510
15613
  const ctx = getCompileContext();
15511
- for (const filePath of getSourceModuleCandidates(dir, name)) {
15512
- if (existsSync4(filePath) || ctx?.modules[filePath]) {
15513
- const moduleSpecifier = isDevelopment() && existsSync4(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15514
- const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15515
- if (mod.default) {
15516
- return { component: mod.default, path: filePath };
15517
- }
15518
- const exportNames = Object.keys(mod).join(", ") || "none";
15519
- throw new Error(`[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:
15520
- ${CONVENTION_EXAMPLES[name]}`);
15521
- }
15614
+ const moduleSpecifier = isDevelopment() && existsSync4(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15615
+ const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15616
+ if (mod.default) {
15617
+ return { component: mod.default, path: filePath };
15522
15618
  }
15619
+ const exportNames = Object.keys(mod).join(", ") || "none";
15620
+ throw new Error(`[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:
15621
+ ${CONVENTION_EXAMPLES[name]}`);
15523
15622
  }
15524
- async function scanPageFiles(pagesDir, root) {
15623
+ async function scanPageFiles(manifest, pagesDir, style, root) {
15525
15624
  const routes = [];
15526
- const notFoundCache = new Map;
15527
- const errorCache = new Map;
15528
- for (const { pattern, sourcePath } of scanRouteManifest(pagesDir)) {
15529
- if (pattern === undefined) {
15625
+ const boundaryCache = new Map;
15626
+ for (const manifestRoute of manifest.routes) {
15627
+ if (manifestRoute.kind !== "page") {
15530
15628
  continue;
15531
15629
  }
15532
- const absolutePath = toPosixPath(sourcePath);
15630
+ const { pattern } = manifestRoute;
15631
+ const absolutePath = manifestRoute.sourcePath;
15533
15632
  const relativePath = routeRelativePath(pagesDir, absolutePath);
15534
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
15633
+ const layouts = manifestLayouts(manifest, manifestRoute);
15634
+ const directoryBoundaries = style === "nextjs" ? await collectSegmentBoundaries(absolutePath, manifest.boundaries, boundaryCache) : [];
15535
15635
  if (isDevelopment()) {
15536
- const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
15537
- devRoute.segmentBoundaries = alignSegmentBoundaryDepths(segmentBoundaries, devRoute.routeChain);
15636
+ const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, layouts);
15637
+ devRoute.segmentBoundaries = style === "nextjs" ? alignSegmentBoundaryDepths(directoryBoundaries, devRoute.routeChain) : routeDefinedBoundaries(root, devRoute.routeChain, devRoute.page, absolutePath);
15538
15638
  routes.push(devRoute);
15539
15639
  continue;
15540
15640
  }
15541
15641
  const ctx = getCompileContext();
15542
15642
  const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
15543
- const page = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
15643
+ const page = await resolveRuntimePage(pageMod, layouts, root.route);
15544
15644
  if (!page) {
15545
15645
  throw new Error(`[furin] ${relativePath}: no valid defineRoute(id).page() export found`);
15546
15646
  }
15547
15647
  const routeChain = collectRouteChainFromRoute(page._route);
15548
15648
  validateRouteChain(routeChain, root.route, relativePath);
15549
15649
  routes.push({
15650
+ layouts,
15550
15651
  mode: resolveMode(page, routeChain),
15551
15652
  page,
15552
15653
  path: absolutePath,
15553
15654
  pattern,
15554
15655
  routeChain,
15555
- segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
15656
+ segmentBoundaries: style === "nextjs" ? alignSegmentBoundaryDepths(directoryBoundaries, routeChain) : routeDefinedBoundaries(root, routeChain, page, absolutePath),
15556
15657
  tags: collectRouteTags(routeChain, page)
15557
15658
  });
15558
15659
  }
15559
15660
  return routes;
15560
15661
  }
15561
- async function resolveRuntimePage(module, absolutePath, pagesDir, rootRoute) {
15662
+ function routeDefinedBoundaries(root, routeChain, page, pagePath) {
15663
+ const entries = [
15664
+ { depth: 0, path: root.path, route: routeChain[0] ?? root.route },
15665
+ ...routeChain.slice(1, -1).map((route, index) => ({ depth: index, path: route.sourcePath, route })),
15666
+ { depth: Math.max(routeChain.length - 2, 0), path: pagePath, route: page }
15667
+ ];
15668
+ const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
15669
+ return entries.flatMap(({ depth, path, route }) => {
15670
+ const { errorComponent, notFoundComponent } = route;
15671
+ if (path === undefined || !(errorComponent || notFoundComponent)) {
15672
+ return [];
15673
+ }
15674
+ return [
15675
+ {
15676
+ depth,
15677
+ error: errorComponent,
15678
+ errorPath: errorComponent ? path : undefined,
15679
+ fromRoute: true,
15680
+ notFound: notFoundComponent,
15681
+ notFoundPath: notFoundComponent ? path : undefined,
15682
+ path: path === root.path ? pagesDir : path
15683
+ }
15684
+ ];
15685
+ });
15686
+ }
15687
+ async function resolveRuntimePage(module, layouts, rootRoute) {
15562
15688
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
15563
15689
  return;
15564
15690
  }
15565
- const parent = await resolveDefinedLayoutParent(absolutePath, pagesDir, rootRoute);
15691
+ const parent = await resolveDefinedLayoutParent(layouts, rootRoute);
15566
15692
  return adaptDefinedPage(module.route, parent);
15567
15693
  }
15568
- async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15569
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
15570
- if (pageDirectory.length <= pagesDir.length) {
15571
- return rootRoute;
15572
- }
15573
- const relativeDirectory = pageDirectory.slice(pagesDir.length + 1);
15574
- const segments = relativeDirectory.split("/");
15575
- let directory = pagesDir;
15694
+ async function resolveDefinedLayoutParent(layouts, rootRoute) {
15576
15695
  let parent = rootRoute;
15577
- for (const segment of segments) {
15578
- directory = `${directory}/${segment}`;
15579
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15580
- if (!existsSync4(candidate)) {
15581
- continue;
15582
- }
15583
- const layoutModule = await (isDevelopment() ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
15584
- const layout = layoutModule.route;
15585
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15586
- throw invalidNestedLayoutError(candidate);
15587
- }
15588
- parent = adaptDefinedLayout(layout, parent, candidate);
15589
- break;
15696
+ for (const { path } of layouts) {
15697
+ const layoutModule = await (isDevelopment() ? import(`${path}?furin-server&t=${routeModuleSourceVersion(path)}`) : import(path));
15698
+ const layout = layoutModule.route;
15699
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15700
+ throw invalidNestedLayoutError(path);
15590
15701
  }
15702
+ parent = adaptDefinedLayout(layout, parent, path);
15591
15703
  }
15592
15704
  return parent;
15593
15705
  }
@@ -15606,50 +15718,35 @@ function alignSegmentBoundaryDepths(boundaries, routeChain) {
15606
15718
  return { ...boundary, depth };
15607
15719
  });
15608
15720
  }
15609
- async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
15721
+ async function collectSegmentBoundaries(pageAbsolutePath, boundaries, cache) {
15610
15722
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
15611
- const dirs = [pagesDir];
15612
- if (pageDir.length > pagesDir.length) {
15613
- const relativeTail = pageDir.slice(pagesDir.length + 1);
15614
- const parts = relativeTail.split("/");
15615
- let acc = pagesDir;
15616
- for (const part of parts) {
15617
- acc = `${acc}/${part}`;
15618
- dirs.push(acc);
15619
- }
15620
- }
15621
- const boundaries = [];
15622
- for (let depth = 0;depth < dirs.length; depth += 1) {
15623
- const dir = dirs[depth];
15624
- const [errorEntry, notFoundEntry] = await Promise.all([
15625
- errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
15626
- errorCache.set(dir, r);
15627
- return r;
15628
- }),
15629
- notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
15630
- notFoundCache.set(dir, r);
15631
- return r;
15632
- })
15633
- ]);
15634
- if (errorEntry || notFoundEntry) {
15635
- boundaries.push({
15636
- depth,
15637
- error: errorEntry?.component,
15638
- errorPath: errorEntry?.path,
15639
- notFound: notFoundEntry?.component,
15640
- notFoundPath: notFoundEntry?.path,
15641
- path: dir
15642
- });
15643
- }
15644
- }
15645
- return boundaries;
15723
+ const enclosing = boundaries.filter(({ directory }) => pageDir === directory || pageDir.startsWith(`${directory}/`));
15724
+ return await Promise.all(enclosing.map((boundary) => {
15725
+ const cached = cache.get(boundary.directory);
15726
+ if (cached) {
15727
+ return cached;
15728
+ }
15729
+ const loaded = Promise.all([
15730
+ loadConventionComponent(boundary.errorPath, "error"),
15731
+ loadConventionComponent(boundary.notFoundPath, "not-found")
15732
+ ]).then(([errorEntry, notFoundEntry]) => ({
15733
+ depth: 0,
15734
+ error: errorEntry?.component,
15735
+ errorPath: errorEntry?.path,
15736
+ notFound: notFoundEntry?.component,
15737
+ notFoundPath: notFoundEntry?.path,
15738
+ path: boundary.directory
15739
+ }));
15740
+ cache.set(boundary.directory, loaded);
15741
+ return loaded;
15742
+ }));
15646
15743
  }
15647
- async function buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir) {
15744
+ async function buildDevRoute(absolutePath, relativePath, pattern, root, layouts) {
15648
15745
  let page;
15649
15746
  let routeChain = [];
15650
15747
  try {
15651
15748
  const pageMod = await import(`${absolutePath}?furin-server&t=${routeModuleSourceVersion(absolutePath)}`);
15652
- const resolvedPage = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
15749
+ const resolvedPage = await resolveRuntimePage(pageMod, layouts, root.route);
15653
15750
  if (resolvedPage) {
15654
15751
  page = resolvedPage;
15655
15752
  routeChain = collectRouteChainFromRoute(page._route);
@@ -15662,6 +15759,7 @@ async function buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir
15662
15759
  component: () => null
15663
15760
  };
15664
15761
  return {
15762
+ layouts,
15665
15763
  mode: page ? resolveMode(page, routeChain) : "ssr",
15666
15764
  page: page ?? devStubPage,
15667
15765
  path: absolutePath,
@@ -15678,9 +15776,9 @@ var ROOT_EXAMPLE = ` export const route = defineRootRoute()
15678
15776
  <head><HeadContent /></head>
15679
15777
  <body>{children}<Scripts /></body>
15680
15778
  </html>
15681
- ));`, CONVENTION_EXAMPLES, SOURCE_MODULE_EXTENSIONS;
15779
+ ));`, CONVENTION_EXAMPLES, ROOT_FILE_NAMES;
15682
15780
  var init_discovery = __esm(() => {
15683
- init_route_tree();
15781
+ init_route_manifest();
15684
15782
  init_instance();
15685
15783
  init_internal();
15686
15784
  init_patterns();
@@ -15693,7 +15791,10 @@ var init_discovery = __esm(() => {
15693
15791
  return <h1>Page not found</h1>;
15694
15792
  }`
15695
15793
  };
15696
- SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
15794
+ ROOT_FILE_NAMES = {
15795
+ nextjs: "layout.tsx",
15796
+ tanstack: "__root.tsx"
15797
+ };
15697
15798
  });
15698
15799
 
15699
15800
  // src/server/render/not-found.ts
@@ -16888,17 +16989,15 @@ async function importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx) {
16888
16989
  throw err;
16889
16990
  }
16890
16991
  }
16891
- async function importFreshLayoutRouteModule(layoutDir, resolveImport, ctx) {
16892
- for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
16893
- const freshMod = await importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx);
16894
- if (!freshMod) {
16895
- continue;
16896
- }
16897
- if (!(isDefinedRouteTerminal(freshMod.route) && typeof freshMod.route.layout === "function")) {
16898
- throw invalidExportFailure(invalidNestedLayoutError(layoutPath), layoutPath);
16899
- }
16900
- return freshMod;
16992
+ async function importFreshLayoutRouteModule(layoutPath, resolveImport, ctx) {
16993
+ const freshMod = await importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx);
16994
+ if (!freshMod) {
16995
+ return;
16996
+ }
16997
+ if (!(isDefinedRouteTerminal(freshMod.route) && typeof freshMod.route.layout === "function")) {
16998
+ throw invalidExportFailure(invalidNestedLayoutError(layoutPath), layoutPath);
16901
16999
  }
17000
+ return freshMod;
16902
17001
  }
16903
17002
  function invalidExportFailure(error, file) {
16904
17003
  Reflect.set(error, "furinPosition", { column: 1, file, line: 1 });
@@ -16911,9 +17010,11 @@ function patchRouteEntryFromFreshModule(entry, freshMod) {
16911
17010
  }
16912
17011
  if (isDefinedRouteTerminal(freshRoute) && typeof freshRoute.layout === "function") {
16913
17012
  const adapted = adaptDefinedLayout(freshRoute, entry.parent);
17013
+ entry.errorComponent = adapted.errorComponent;
16914
17014
  entry.layout = adapted.layout;
16915
17015
  entry.loader = adapted.loader;
16916
17016
  entry.mode = adapted.mode;
17017
+ entry.notFoundComponent = adapted.notFoundComponent;
16917
17018
  entry.params = adapted.params;
16918
17019
  entry.query = adapted.query;
16919
17020
  entry.requestLoader = adapted.requestLoader;
@@ -16922,21 +17023,14 @@ function patchRouteEntryFromFreshModule(entry, freshMod) {
16922
17023
  entry.tags = adapted.tags;
16923
17024
  }
16924
17025
  }
16925
- async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
17026
+ async function refreshLayoutChain(chain, layoutPaths, importFn) {
16926
17027
  const resolveImport = importFn ?? routeModuleImport;
16927
17028
  const ctx = getCompileContext();
16928
- const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
16929
- const freshMods = await Promise.all(layoutDirs.map((layoutDir) => importFreshLayoutRouteModule(layoutDir, resolveImport, ctx)));
16930
- let chainIdx = 1;
16931
- for (const freshMod of freshMods) {
16932
- if (chainIdx >= chain.length) {
16933
- break;
16934
- }
16935
- if (!freshMod) {
16936
- continue;
17029
+ const freshMods = await Promise.all(layoutPaths.map((layoutPath) => importFreshLayoutRouteModule(layoutPath, resolveImport, ctx)));
17030
+ for (const [index, freshMod] of freshMods.entries()) {
17031
+ if (freshMod) {
17032
+ patchRouteEntryFromFreshModule(chain[index + 1], freshMod);
16937
17033
  }
16938
- patchRouteEntryFromFreshModule(chain[chainIdx], freshMod);
16939
- chainIdx += 1;
16940
17034
  }
16941
17035
  }
16942
17036
  function rebuildDevRoute(base, page, chain) {
@@ -16963,7 +17057,7 @@ async function resolveCurrentDevRoute(route, root) {
16963
17057
  let chain;
16964
17058
  if (isDefinedRouteTerminal(pageMod.route) && typeof pageMod.route.page === "function") {
16965
17059
  const currentChain = route.routeChain;
16966
- await refreshLayoutChain(currentChain, route.path, root.path, undefined);
17060
+ await refreshLayoutChain(currentChain, route.layouts.map(({ path }) => path), undefined);
16967
17061
  const parent = currentChain.at(-2) ?? currentRoot.route;
16968
17062
  const adaptedPage = adaptDefinedPage(pageMod.route, parent);
16969
17063
  page = adaptedPage;
@@ -17016,7 +17110,7 @@ async function loadCachedDevLoaderData(route, ctx, root, mode, purpose) {
17016
17110
  const result = purpose === "document" ? await runDevLoaders(route, loaderCtx) : await runPublicLoaders(route, loaderCtx);
17017
17111
  if (result.type === "data") {
17018
17112
  const entry = {
17019
- dependencies: computeRouteDependencies(route.path, root.path),
17113
+ dependencies: computeRouteDependencies(route.path, root.path, route.layouts.map(({ path }) => path)),
17020
17114
  generatedAt: Date.now(),
17021
17115
  headers: result.headers,
17022
17116
  loaderData: result.syncData,
@@ -17028,15 +17122,8 @@ async function loadCachedDevLoaderData(route, ctx, root, mode, purpose) {
17028
17122
  }
17029
17123
  return result;
17030
17124
  }
17031
- function computeRouteDependencies(pagePath, rootPath) {
17032
- const deps = [pagePath, rootPath];
17033
- for (const dir of collectIntermediateLayoutDirs(pagePath, rootPath)) {
17034
- for (const candidate of getSourceModuleCandidates(dir, "_route")) {
17035
- if (existsSync6(candidate)) {
17036
- deps.push(candidate);
17037
- }
17038
- }
17039
- }
17125
+ function computeRouteDependencies(pagePath, rootPath, layoutPaths) {
17126
+ const deps = [pagePath, rootPath, ...layoutPaths.filter((path) => existsSync6(path))];
17040
17127
  const graph = devGraph(undefined);
17041
17128
  return [...new Set(deps.flatMap((path) => graph.sourceDependencies(path)))].filter(existsSync6);
17042
17129
  }
@@ -17128,7 +17215,7 @@ var init_hmr = __esm(() => {
17128
17215
 
17129
17216
  // src/plugin/preflight.ts
17130
17217
  import { existsSync as existsSync7, readFileSync as readFileSync4 } from "fs";
17131
- import { join as join5 } from "path";
17218
+ import { join as join4 } from "path";
17132
17219
  function staticPlugins(bunfig) {
17133
17220
  if (typeof bunfig !== "object" || bunfig === null || !("serve" in bunfig)) {
17134
17221
  return [];
@@ -17144,7 +17231,7 @@ function staticPlugins(bunfig) {
17144
17231
  return staticConfig.plugins.filter((plugin) => typeof plugin === "string");
17145
17232
  }
17146
17233
  function stripPluginPreflightWarning(projectRoot) {
17147
- const bunfigPath = join5(projectRoot, "bunfig.toml");
17234
+ const bunfigPath = join4(projectRoot, "bunfig.toml");
17148
17235
  const hasBunfig = existsSync7(bunfigPath);
17149
17236
  const plugins = hasBunfig ? staticPlugins(Bun.TOML.parse(readFileSync4(bunfigPath, "utf8"))) : [];
17150
17237
  if (plugins.includes(STRIP_PLUGIN)) {
@@ -18777,9 +18864,9 @@ var init_dist2 = __esm(() => {
18777
18864
  });
18778
18865
 
18779
18866
  // src/shared/parser.ts
18780
- import { parse as parse3 } from "yuku-parser";
18867
+ import { parse as parse2 } from "yuku-parser";
18781
18868
  function parseSource(code, lang) {
18782
- return parse3(code, { lang, sourceType: "module" });
18869
+ return parse2(code, { lang, sourceType: "module" });
18783
18870
  }
18784
18871
  var init_parser = () => {};
18785
18872
 
@@ -20537,7 +20624,7 @@ var init_transform_dev_page = __esm(() => {
20537
20624
 
20538
20625
  // src/plugin/transform-client-module.ts
20539
20626
  import { realpathSync as realpathSync2 } from "fs";
20540
- import { dirname as dirname5 } from "path";
20627
+ import { dirname as dirname4 } from "path";
20541
20628
  function clientModuleKey(modulePath) {
20542
20629
  const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
20543
20630
  return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
@@ -20590,7 +20677,7 @@ function rewriteClientModules(module, environment) {
20590
20677
  }
20591
20678
  let key;
20592
20679
  try {
20593
- key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname5(filename))));
20680
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname4(filename))));
20594
20681
  } catch (error) {
20595
20682
  throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
20596
20683
  }
@@ -21031,7 +21118,7 @@ var init_transform_isomorphic = __esm(() => {
21031
21118
  });
21032
21119
 
21033
21120
  // src/server/dev/error.ts
21034
- import { relative as relative7 } from "path";
21121
+ import { relative as relative5 } from "path";
21035
21122
  function errorMessage2(error) {
21036
21123
  if (error instanceof Error) {
21037
21124
  return error.message;
@@ -21082,7 +21169,7 @@ function createDevErrorPayload(error, context) {
21082
21169
  };
21083
21170
  }
21084
21171
  function displaySourcePath(path) {
21085
- const projected = relative7(process.cwd(), path).replaceAll("\\", "/");
21172
+ const projected = relative5(process.cwd(), path).replaceAll("\\", "/");
21086
21173
  return projected.startsWith("../") ? path : projected;
21087
21174
  }
21088
21175
  function publishDevError(graph, error, context) {
@@ -21129,7 +21216,7 @@ var init_server_only_module = __esm(() => {
21129
21216
  });
21130
21217
 
21131
21218
  // src/server/dev/rewrite-module-specifiers.ts
21132
- import { dirname as dirname6, resolve as resolve7 } from "path";
21219
+ import { dirname as dirname5, resolve as resolve6 } from "path";
21133
21220
  function sourcePosition2(source, byteOffset) {
21134
21221
  const bytes = new TextEncoder().encode(source);
21135
21222
  const prefix = new TextDecoder().decode(bytes.slice(0, byteOffset));
@@ -21150,7 +21237,7 @@ function relativeSpecifier(node) {
21150
21237
  return isStringLiteral(node.source) ? node.source : undefined;
21151
21238
  }
21152
21239
  function resolvedSpecifier(specifier, directory, versioned) {
21153
- const path = versioned ? Bun.resolveSync(specifier, directory) : resolve7(directory, specifier);
21240
+ const path = versioned ? Bun.resolveSync(specifier, directory) : resolve6(directory, specifier);
21154
21241
  const normalized = path.replaceAll("\\", "/");
21155
21242
  return versioned && SCRIPT_FILE_FILTER.test(normalized) && !isServerOnlyModule(path) ? `${normalized}?furin-server&t=${routeModuleSourceVersion(normalized)}` : normalized;
21156
21243
  }
@@ -21162,7 +21249,7 @@ function rewriteModuleSpecifiers(input) {
21162
21249
  Reflect.set(error, "position", sourcePosition2(input.code, parseError.start));
21163
21250
  throw error;
21164
21251
  }
21165
- const directory = dirname6(input.filePath);
21252
+ const directory = dirname5(input.filePath);
21166
21253
  const output = new MagicString(input.code);
21167
21254
  walkAST(program, (node) => {
21168
21255
  const literal = relativeSpecifier(node);
@@ -21184,7 +21271,7 @@ var init_rewrite_module_specifiers = __esm(() => {
21184
21271
  });
21185
21272
 
21186
21273
  // src/server/dev-page-imports.ts
21187
- import { dirname as dirname7, isAbsolute as isAbsolute4, resolve as resolve8 } from "path";
21274
+ import { dirname as dirname6, isAbsolute as isAbsolute4, resolve as resolve7 } from "path";
21188
21275
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
21189
21276
  function toImportSpecifier(filePath) {
21190
21277
  return filePath.replaceAll("\\", "/");
@@ -21211,7 +21298,7 @@ function pinJsxRuntime(source, loader) {
21211
21298
  if (!runtime || loader === "ts") {
21212
21299
  return source;
21213
21300
  }
21214
- const pragma = `/** @jsxImportSource ${pathToFileURL(dirname7(runtime)).href} */ `;
21301
+ const pragma = `/** @jsxImportSource ${pathToFileURL(dirname6(runtime)).href} */ `;
21215
21302
  const shebangEnd = source.startsWith("#!") ? source.indexOf(`
21216
21303
  `) + 1 : 0;
21217
21304
  return shebangEnd > 0 ? `${source.slice(0, shebangEnd)}${pragma}${source.slice(shebangEnd)}` : `${pragma}${source}`;
@@ -21277,7 +21364,7 @@ var init_dev_page_imports = __esm(() => {
21277
21364
 
21278
21365
  // src/server/dev-page-plugin.ts
21279
21366
  import { statSync as statSync4 } from "fs";
21280
- import { dirname as dirname8, isAbsolute as isAbsolute5 } from "path";
21367
+ import { dirname as dirname7, isAbsolute as isAbsolute5 } from "path";
21281
21368
  function getSourceLoader(filePath) {
21282
21369
  return SCRIPT_FILE_FILTER.test(filePath) ? detectLoaderFromPath(filePath) : null;
21283
21370
  }
@@ -21346,11 +21433,12 @@ function transformDevSource(raw, filePath, options) {
21346
21433
  for (const graph of developmentGraphs()) {
21347
21434
  graph.clearSourceErrors(filePath);
21348
21435
  }
21436
+ const source = raw.startsWith("#!") ? `//${raw.slice(2)}` : raw;
21349
21437
  try {
21350
21438
  if (!options.renderFragment) {
21351
- recordDevImports(raw, filePath);
21439
+ recordDevImports(source, filePath);
21352
21440
  }
21353
- const server = parseModule(raw, filePath);
21441
+ const server = parseModule(source, filePath);
21354
21442
  for (const statement of server.program.body) {
21355
21443
  if (statement.type === "ImportDeclaration" && statement.specifiers.length === 0 && CSS_IMPORT.test(statement.source.value)) {
21356
21444
  removeRange(server, statement.start, statement.end);
@@ -21361,7 +21449,7 @@ function transformDevSource(raw, filePath, options) {
21361
21449
  const serverSource = split?.contract ?? isomorphicSource;
21362
21450
  let result = options.rewriteRelativeImports ? rewriteRelativeImportsWithVersion(serverSource, filePath, true) : serverSource;
21363
21451
  if (options.rewriteBareImports) {
21364
- result = rewriteBareImports(result, dirname8(filePath), loader);
21452
+ result = rewriteBareImports(result, dirname7(filePath), loader);
21365
21453
  }
21366
21454
  result = rewriteSingletonImports(result, loader);
21367
21455
  return pinJsxRuntime(result, loader);
@@ -21498,9 +21586,9 @@ var init_dev_page_plugin = __esm(() => {
21498
21586
 
21499
21587
  // src/plugin/route-modules.ts
21500
21588
  import { existsSync as existsSync8, readFileSync as readFileSync6, realpathSync as realpathSync3, statSync as statSync5 } from "fs";
21501
- import { dirname as dirname9, isAbsolute as isAbsolute6, join as join6, relative as relative8, sep as sep2 } from "path";
21589
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join5, relative as relative6, sep as sep2 } from "path";
21502
21590
  function validateRouteParams(path, schemas) {
21503
- const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
21591
+ const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? SPLAT_PARAM : segment.slice(1).replace(OPTIONAL_MARK, ""));
21504
21592
  if (pathParams.length === 0) {
21505
21593
  return;
21506
21594
  }
@@ -21520,18 +21608,18 @@ function routeModuleCache() {
21520
21608
  return cache;
21521
21609
  }
21522
21610
  function findPackageRoot(sourcePath) {
21523
- const fallback = dirname9(sourcePath);
21611
+ const fallback = dirname8(sourcePath);
21524
21612
  let directory = fallback;
21525
- while (dirname9(directory) !== directory) {
21526
- if (existsSync8(join6(directory, "package.json"))) {
21613
+ while (dirname8(directory) !== directory) {
21614
+ if (existsSync8(join5(directory, "package.json"))) {
21527
21615
  return directory;
21528
21616
  }
21529
- directory = dirname9(directory);
21617
+ directory = dirname8(directory);
21530
21618
  }
21531
- return existsSync8(join6(directory, "package.json")) ? directory : fallback;
21619
+ return existsSync8(join5(directory, "package.json")) ? directory : fallback;
21532
21620
  }
21533
21621
  function isWithinDirectory(path, directory) {
21534
- const relativePath = relative8(directory, path);
21622
+ const relativePath = relative6(directory, path);
21535
21623
  return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute6(relativePath));
21536
21624
  }
21537
21625
  function isFurinPackageImport(specifier) {
@@ -21549,8 +21637,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
21549
21637
  continue;
21550
21638
  }
21551
21639
  try {
21552
- const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname9(dependencyPath)));
21553
- if (isAbsolute6(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative8(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
21640
+ const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname8(dependencyPath)));
21641
+ if (isAbsolute6(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative6(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
21554
21642
  resolvedImports.push(resolvedImport);
21555
21643
  }
21556
21644
  } catch {}
@@ -21582,19 +21670,99 @@ function collectRouteModuleDependencies(sourcePath) {
21582
21670
  function routeModuleDependencies(sourcePath) {
21583
21671
  return routeModuleCache().get(sourcePath)?.dependencies ?? collectRouteModuleDependencies(sourcePath);
21584
21672
  }
21585
- var ROUTE_MODULE_CACHE_SYMBOL;
21673
+ var ROUTE_MODULE_CACHE_SYMBOL, OPTIONAL_MARK;
21586
21674
  var init_route_modules = __esm(() => {
21587
21675
  init_lang_detect();
21676
+ init_patterns();
21588
21677
  ROUTE_MODULE_CACHE_SYMBOL = Symbol.for("@teyik0/furin/route-module-cache");
21678
+ OPTIONAL_MARK = /\?$/;
21679
+ });
21680
+
21681
+ // src/plugin/route-tree.ts
21682
+ import { existsSync as existsSync9 } from "fs";
21683
+ import { resolve as resolve8 } from "path";
21684
+ function instanceKey(instance) {
21685
+ return `${resolve8(instance.pagesDir)}\x00${instance.prefix}`;
21686
+ }
21687
+ function routeModuleSpecifier(instance) {
21688
+ return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
21689
+ }
21690
+ function routeId(instanceId, id) {
21691
+ const encodedId = Array.from(new TextEncoder().encode(id), (byte) => byte.toString(16).padStart(2, "0")).join("");
21692
+ return `_route_${instanceId}_${encodedId}`;
21693
+ }
21694
+ function relativePrefix(pattern, parentPattern) {
21695
+ const own = pattern === "/" ? "" : pattern;
21696
+ const parent = parentPattern === "/" ? "" : parentPattern;
21697
+ if (!own.startsWith(parent)) {
21698
+ throw new Error(`[furin] Route pattern "${pattern}" does not extend its layout's "${parentPattern}".`);
21699
+ }
21700
+ return own.slice(parent.length);
21701
+ }
21702
+ function buildRouteTree(instance, instanceId) {
21703
+ const { routes } = scanRouteManifest(instance);
21704
+ const byPath = new Map(routes.map((route) => [route.sourcePath, route]));
21705
+ const root = { children: [], layout: undefined, pages: [], prefix: "" };
21706
+ const nodes = new Map([[undefined, root]]);
21707
+ const parentPattern = (route) => route.parentPath === undefined ? "/" : byPath.get(route.parentPath)?.pattern ?? "/";
21708
+ const ensureNode = (sourcePath) => {
21709
+ const existing = nodes.get(sourcePath);
21710
+ if (existing) {
21711
+ return existing;
21712
+ }
21713
+ const layout = sourcePath === undefined ? undefined : byPath.get(sourcePath);
21714
+ if (!layout) {
21715
+ return root;
21716
+ }
21717
+ const prefix = relativePrefix(layout.pattern, parentPattern(layout));
21718
+ const node = {
21719
+ children: [],
21720
+ layout: {
21721
+ id: routeId(instanceId, layout.id),
21722
+ path: "",
21723
+ prefix,
21724
+ sourcePath: resolve8(layout.sourcePath)
21725
+ },
21726
+ pages: [],
21727
+ prefix
21728
+ };
21729
+ nodes.set(sourcePath, node);
21730
+ ensureNode(layout.parentPath).children.push(node);
21731
+ return node;
21732
+ };
21733
+ for (const route of routes) {
21734
+ if (route.kind === "layout") {
21735
+ ensureNode(route.sourcePath);
21736
+ continue;
21737
+ }
21738
+ ensureNode(route.parentPath).pages.push({
21739
+ id: routeId(instanceId, route.id),
21740
+ path: route.pattern,
21741
+ prefix: relativePrefix(route.pattern, parentPattern(route)),
21742
+ sourcePath: resolve8(route.sourcePath)
21743
+ });
21744
+ }
21745
+ return root;
21746
+ }
21747
+ function routeSnapshotSourcePaths(instance) {
21748
+ const { boundaries, rootPath, routes } = scanRouteManifest(instance);
21749
+ return [
21750
+ ...existsSync9(rootPath) ? [rootPath] : [],
21751
+ ...routes.map(({ sourcePath }) => sourcePath),
21752
+ ...boundaries.flatMap(({ errorPath, notFoundPath }) => [errorPath, notFoundPath].filter((path) => path !== undefined))
21753
+ ].map((path) => resolve8(path)).toSorted((left, right) => left.localeCompare(right));
21754
+ }
21755
+ var init_route_tree = __esm(() => {
21756
+ init_route_manifest();
21589
21757
  });
21590
21758
 
21591
21759
  // src/plugin/dev-routes.ts
21592
- import { existsSync as existsSync9, readFileSync as readFileSync7, statSync as statSync6, watch } from "fs";
21593
- import { dirname as dirname10, relative as relative9, resolve as resolve9, sep as sep3 } from "path";
21760
+ import { existsSync as existsSync10, readFileSync as readFileSync7, statSync as statSync6, watch } from "fs";
21761
+ import { dirname as dirname9, relative as relative7, resolve as resolve9, sep as sep3 } from "path";
21594
21762
  import { Elysia as Elysia16 } from "elysia";
21595
21763
  function routeTopologySource(instance) {
21596
21764
  const pagesDir = resolve9(instance.pagesDir);
21597
- const paths = routeSnapshotSourcePaths(instance).map((path) => relative9(pagesDir, path).replaceAll("\\", "/"));
21765
+ const paths = routeSnapshotSourcePaths(instance).map((path) => relative7(pagesDir, path).replaceAll("\\", "/"));
21598
21766
  return `${JSON.stringify(paths)}
21599
21767
  `;
21600
21768
  }
@@ -21703,7 +21871,7 @@ function reportChangedSourceError(state, directory, filename) {
21703
21871
  return;
21704
21872
  }
21705
21873
  const sourcePath = resolve9(directory, String(filename));
21706
- if (!(SCRIPT_FILE_FILTER.test(sourcePath) && existsSync9(sourcePath))) {
21874
+ if (!(SCRIPT_FILE_FILTER.test(sourcePath) && existsSync10(sourcePath))) {
21707
21875
  return;
21708
21876
  }
21709
21877
  try {
@@ -21721,7 +21889,7 @@ function replaceSourceWatchers(state) {
21721
21889
  const directories = new Set;
21722
21890
  for (const path of routeDependencyPaths(state.instance)) {
21723
21891
  if (!(path === pagesDir || path.startsWith(`${pagesDir}${sep3}`))) {
21724
- directories.add(dirname10(path));
21892
+ directories.add(dirname9(path));
21725
21893
  }
21726
21894
  }
21727
21895
  const watchDirectory = (directory, recursive) => {
@@ -21873,27 +22041,20 @@ async function composableRouteApps(route) {
21873
22041
  };
21874
22042
  }
21875
22043
  async function composeRuntimeNode(node) {
21876
- const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
21877
- const { fileRoutes } = node;
21878
- const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
22044
+ const { pages, prefix } = node;
22045
+ const [layoutApps, pageApps, childApps] = await Promise.all([
21879
22046
  node.layout ? composableRouteApps(node.layout) : undefined,
21880
- node.indexRoute ? composableRouteApps(node.indexRoute) : undefined,
21881
- Promise.all(fileRoutes.map((route) => composableRouteApps(route))),
22047
+ Promise.all(pages.map((route) => composableRouteApps(route))),
21882
22048
  Promise.all(node.children.map((child) => composeRuntimeNode(child)))
21883
22049
  ]);
21884
22050
  const appScope = layoutApps?.app ?? new Elysia16;
21885
22051
  const shellScope = layoutApps?.shell ?? new Elysia16;
21886
- if (indexRouteApps) {
21887
- appScope.use(new Elysia16({ prefix: "" }).use(indexRouteApps.app));
21888
- shellScope.use(new Elysia16({ prefix: "" }).use(indexRouteApps.shell));
21889
- }
21890
- for (const [index, route] of fileRoutes.entries()) {
21891
- const routeApps = fileRouteApps[index];
22052
+ for (const [index, route] of pages.entries()) {
22053
+ const routeApps = pageApps[index];
21892
22054
  if (routeApps) {
21893
- const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
21894
- appScope.use(new Elysia16({ prefix: `/${segment}` }).use(routeApps.app));
22055
+ appScope.use(new Elysia16({ prefix: route.prefix }).use(routeApps.app));
21895
22056
  if (route.path !== "/*") {
21896
- shellScope.use(new Elysia16({ prefix: `/${segment}` }).use(routeApps.shell));
22057
+ shellScope.use(new Elysia16({ prefix: route.prefix }).use(routeApps.shell));
21897
22058
  }
21898
22059
  }
21899
22060
  }
@@ -21910,7 +22071,7 @@ async function composeRuntimeInstance(instance) {
21910
22071
  await Promise.resolve().then(() => init_dev_page_plugin());
21911
22072
  registerDevPagePlugin();
21912
22073
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
21913
- return composeRuntimeNode(buildRouteTree(instance.pagesDir, instanceId));
22074
+ return composeRuntimeNode(buildRouteTree(instance, instanceId));
21914
22075
  }
21915
22076
  function registerDevRoutesPlugin(instances) {
21916
22077
  for (const instance of instances) {
@@ -21939,7 +22100,6 @@ var DEV_ROUTE_WATCHERS_SYMBOL, DEV_ROUTE_WATCHER_OWNERS_SYMBOL, DEV_ROUTE_RECONC
21939
22100
  var init_dev_routes = __esm(() => {
21940
22101
  init_define_route();
21941
22102
  init_lang_detect();
21942
- init_patterns();
21943
22103
  init_source_version();
21944
22104
  init_route_modules();
21945
22105
  init_route_tree();
@@ -21949,11 +22109,8 @@ var init_dev_routes = __esm(() => {
21949
22109
  });
21950
22110
 
21951
22111
  // src/plugin/route-config.ts
21952
- import { existsSync as existsSync10, readFileSync as readFileSync8, writeFileSync } from "fs";
21953
- import { basename as basename3, join as join7, relative as relative10, resolve as resolve10 } from "path";
21954
- function withoutExtension(path) {
21955
- return path.replace(EXTENSION_RE, "");
21956
- }
22112
+ import { existsSync as existsSync11, readFileSync as readFileSync8, writeFileSync } from "fs";
22113
+ import { relative as relative8, resolve as resolve10 } from "path";
21957
22114
  function propertyName(key) {
21958
22115
  if (key?.type === "Identifier") {
21959
22116
  return key.name;
@@ -22034,9 +22191,9 @@ function position2(source, offset) {
22034
22191
  function issueAt(file, parsed, node, message) {
22035
22192
  return { file, ...position2(parsed.source, node.start), message };
22036
22193
  }
22037
- function checkKey(file, instance, parsed) {
22194
+ function checkKey(file, route, parsed) {
22038
22195
  const { config, head, id } = parsed.route;
22039
- const expected = fileRouteId(instance, file);
22196
+ const expected = route.id;
22040
22197
  if (!id) {
22041
22198
  return issueAt(file, parsed, head, `defineRoute() must name this file. Its id is "${expected}":
22042
22199
  defineRoute("${expected}")`);
@@ -22065,21 +22222,21 @@ function suggestedMode(route, isRoot) {
22065
22222
  }
22066
22223
  return route.methods.has("loader") || route.methods.has("requestLoader") ? "ssr" : "ssg";
22067
22224
  }
22068
- function checkFactory(file, instance, parsed) {
22225
+ function checkFactory(file, manifestRoute, parsed) {
22069
22226
  const { route } = parsed;
22070
- const isRoot = withoutExtension(file) === join7(instance.pagesDir, "root");
22227
+ const isRoot = manifestRoute === undefined;
22071
22228
  if (isRoot === route.isRootFactory) {
22072
22229
  return;
22073
22230
  }
22074
22231
  const mode = suggestedMode(route, isRoot);
22075
22232
  if (isRoot) {
22076
- return issueAt(file, parsed, route.head, `root.tsx must use defineRootRoute(), which has no parent layout:
22233
+ return issueAt(file, parsed, route.head, `The root layout must use defineRootRoute(), which has no parent layout:
22077
22234
  import { defineRootRoute } from "@teyik0/furin";
22078
22235
  export const route = defineRootRoute().config({ mode: "${mode}" })`);
22079
22236
  }
22080
- return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for root.tsx. Use defineRoute with this file's id:
22237
+ return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for the root layout. Use defineRoute with this file's id:
22081
22238
  import { defineRoute } from "@teyik0/furin";
22082
- export const route = defineRoute("${fileRouteId(instance, file)}").config({ mode: "${mode}" })`);
22239
+ export const route = defineRoute("${manifestRoute.id}").config({ mode: "${mode}" })`);
22083
22240
  }
22084
22241
  function checkConfig(file, parsed) {
22085
22242
  const { route } = parsed;
@@ -22110,56 +22267,64 @@ function declaredParams(route) {
22110
22267
  }
22111
22268
  return new Set(keys.filter((key) => key !== undefined));
22112
22269
  }
22113
- function undeclaredSegments(file, pagesDir, declared) {
22114
- return withoutExtension(relative10(pagesDir, file)).split(PATH_SEPARATOR_RE).flatMap((segment) => {
22115
- const dynamic = parseDynamicRouteSegment(segment, file);
22116
- return dynamic ? [{ key: dynamic.catchAll ? "*" : dynamic.name, segment }] : [];
22117
- }).filter(({ key }) => declared !== true && !declared.has(key));
22270
+ function undeclaredParams(route, declared) {
22271
+ return route.params.filter(({ name }) => declared !== true && !declared.has(name));
22118
22272
  }
22119
- function paramsSchema(segments) {
22120
- const fields = segments.map(({ key }) => `${IDENTIFIER_RE.test(key) ? key : JSON.stringify(key)}: t.String()`);
22273
+ function paramsSchema(params) {
22274
+ const fields = params.map(({ name, optional }) => `${IDENTIFIER_RE.test(name) ? name : JSON.stringify(name)}: ${optional ? "t.Optional(t.String())" : "t.String()"}`);
22121
22275
  return `params: t.Object({ ${fields.join(", ")} })`;
22122
22276
  }
22123
- function checkParams(file, pagesDir, parsed) {
22124
- const missing = undeclaredSegments(file, pagesDir, declaredParams(parsed.route));
22277
+ function checkParams(file, route, parsed) {
22278
+ const missing = undeclaredParams(route, declaredParams(parsed.route));
22125
22279
  if (missing.length === 0) {
22126
22280
  return;
22127
22281
  }
22128
22282
  const plural = missing.length > 1;
22129
22283
  const tImport = parsed.imports.get("t")?.specifier === "elysia" ? "" : `
22130
22284
  import { t } from "elysia";`;
22131
- return issueAt(file, parsed, parsed.route.config ?? parsed.route.head, `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}
22285
+ return issueAt(file, parsed, parsed.route.config ?? parsed.route.head, `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}
22132
22286
  ${paramsSchema(missing)}`);
22133
22287
  }
22134
- function checkRoute(file, instance, parsed) {
22135
- const factory = checkFactory(file, instance, parsed);
22288
+ function checkBoundaryMethods(file, instance, parsed) {
22289
+ const method = ["error", "notFound"].find((name) => parsed.route.methods.has(name));
22290
+ if (instance.style !== "nextjs" || method === undefined) {
22291
+ return;
22292
+ }
22293
+ const convention = method === "error" ? "an error.tsx" : "a not-found.tsx";
22294
+ return issueAt(file, parsed, parsed.route.head, `.${method}() is the TanStack style. In the nextjs style, default-export the component from ${convention} next to this route.`);
22295
+ }
22296
+ function checkRoute(file, instance, route, parsed) {
22297
+ const factory = checkFactory(file, route, parsed);
22136
22298
  if (factory) {
22137
22299
  return [factory];
22138
22300
  }
22139
- const isLayout = basename3(withoutExtension(file)) === "_route";
22140
22301
  return [
22141
22302
  checkConfig(file, parsed),
22142
- parsed.route.isRootFactory ? undefined : checkKey(file, instance, parsed),
22303
+ route === undefined ? undefined : checkKey(file, route, parsed),
22143
22304
  checkMode(file, parsed),
22144
- parsed.route.isRootFactory || isLayout ? undefined : checkParams(file, instance.pagesDir, parsed)
22305
+ route === undefined || route.kind === "layout" ? undefined : checkParams(file, route, parsed),
22306
+ checkBoundaryMethods(file, instance, parsed)
22145
22307
  ];
22146
22308
  }
22147
- function routeFiles(pagesDir) {
22148
- const root = join7(pagesDir, "root.tsx");
22149
- return [
22150
- ...existsSync10(root) ? [root] : [],
22151
- ...routeSourcePaths({ pagesDir, prefix: "" })
22152
- ].toSorted((left, right) => left.localeCompare(right));
22309
+ function routeFiles(manifest) {
22310
+ const files = manifest.routes.map((route) => [
22311
+ resolve10(route.sourcePath),
22312
+ route
22313
+ ]);
22314
+ if (existsSync11(manifest.rootPath)) {
22315
+ files.push([resolve10(manifest.rootPath), undefined]);
22316
+ }
22317
+ return files.toSorted(([left], [right]) => left.localeCompare(right));
22153
22318
  }
22154
- function validateRouteConfig({ pagesDir, prefix }) {
22155
- const instance = { pagesDir: resolve10(pagesDir), prefix };
22156
- return routeFiles(instance.pagesDir).flatMap((file) => {
22319
+ function validateRouteConfig(spec) {
22320
+ const instance = { ...spec, pagesDir: resolve10(spec.pagesDir) };
22321
+ return routeFiles(scanRouteManifest(instance)).flatMap(([file, route]) => {
22157
22322
  const parsed = parseRoute(file);
22158
- return parsed ? checkRoute(file, instance, parsed).filter((issue) => issue !== undefined) : [];
22323
+ return parsed ? checkRoute(file, instance, route, parsed).filter((issue) => issue !== undefined) : [];
22159
22324
  });
22160
22325
  }
22161
22326
  function displayPath2(file) {
22162
- const projected = relative10(process.cwd(), file).replaceAll("\\", "/");
22327
+ const projected = relative8(process.cwd(), file).replaceAll("\\", "/");
22163
22328
  return projected.startsWith("../") ? file : projected;
22164
22329
  }
22165
22330
  function formatRouteConfigIssue(issue) {
@@ -22192,30 +22357,32 @@ function createRouteConfigReporter(instance, store) {
22192
22357
  });
22193
22358
  };
22194
22359
  }
22195
- function scaffoldTemplate(file, instance) {
22196
- if (withoutExtension(file) === join7(instance.pagesDir, "root")) {
22360
+ function scaffoldTemplate(route) {
22361
+ if (route === undefined) {
22197
22362
  return ROOT_TEMPLATE;
22198
22363
  }
22199
- const isLayout = basename3(withoutExtension(file)) === "_route";
22200
- const params = undeclaredSegments(file, instance.pagesDir, new Set);
22364
+ const isLayout = route.kind === "layout";
22365
+ const { params } = route;
22201
22366
  return `import { defineRoute } from "@teyik0/furin";${params.length > 0 ? `
22202
22367
  import { t } from "elysia";` : ""}
22203
22368
 
22204
- export const route = defineRoute("${fileRouteId(instance, file)}")
22369
+ export const route = defineRoute("${route.id}")
22205
22370
  .config({ mode: "${isLayout ? "ssr" : "ssg"}"${params.length > 0 ? `, ${paramsSchema(params)}` : ""} })
22206
22371
  .${isLayout ? "layout(({ children }) => children)" : "page(() => null)"};
22207
22372
  `;
22208
22373
  }
22209
- function scaffoldEmptyRoutes({ pagesDir, prefix }) {
22210
- const instance = { pagesDir: resolve10(pagesDir), prefix };
22374
+ function scaffoldEmptyRoutes(spec) {
22375
+ const instance = { ...spec, pagesDir: resolve10(spec.pagesDir) };
22211
22376
  const written = [];
22212
- for (const file of routeFiles(instance.pagesDir).filter((path) => readSource(path)?.trim() === "")) {
22213
- writeFileSync(file, scaffoldTemplate(file, instance));
22214
- written.push(file);
22377
+ for (const [file, route] of routeFiles(scanRouteManifest(instance))) {
22378
+ if (readSource(file)?.trim() === "") {
22379
+ writeFileSync(file, scaffoldTemplate(route));
22380
+ written.push(file);
22381
+ }
22215
22382
  }
22216
22383
  return written;
22217
22384
  }
22218
- var EXTENSION_RE, IDENTIFIER_RE, PATH_SEPARATOR_RE, ROUTE_CONFIG_DIAGNOSTIC = "route config", ROOT_TEMPLATE = `import { defineRootRoute, HeadContent, Scripts } from "@teyik0/furin";
22385
+ var IDENTIFIER_RE, ROUTE_CONFIG_DIAGNOSTIC = "route config", ROOT_TEMPLATE = `import { defineRootRoute, HeadContent, Scripts } from "@teyik0/furin";
22219
22386
 
22220
22387
  export const route = defineRootRoute()
22221
22388
  .config({ mode: "ssr" })
@@ -22233,13 +22400,10 @@ export const route = defineRootRoute()
22233
22400
  `;
22234
22401
  var init_route_config = __esm(() => {
22235
22402
  init_lang_detect();
22236
- init_patterns();
22237
22403
  init_parser();
22238
22404
  init_route_chains();
22239
- init_route_tree();
22240
- EXTENSION_RE = /\.(?:[cm]?[jt]sx?)$/;
22405
+ init_route_manifest();
22241
22406
  IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
22242
- PATH_SEPARATOR_RE = /[\\/]/;
22243
22407
  });
22244
22408
 
22245
22409
  // src/build/route-metadata.ts
@@ -22274,13 +22438,13 @@ var init_route_metadata = __esm(() => {
22274
22438
  });
22275
22439
 
22276
22440
  // src/rsc/build/paths.ts
22277
- import { dirname as dirname11, join as join8 } from "path";
22441
+ import { dirname as dirname10, join as join6 } from "path";
22278
22442
  import { fileURLToPath as fileURLToPath4 } from "url";
22279
22443
  var SOURCE_DIR, CLIENT_REFERENCE_RUNTIME_PATH, BUNDLED_CLIENT_CODEC_PATH;
22280
22444
  var init_paths = __esm(() => {
22281
- SOURCE_DIR = dirname11(fileURLToPath4(import.meta.resolve("@teyik0/furin/rsc")));
22282
- CLIENT_REFERENCE_RUNTIME_PATH = join8(SOURCE_DIR, "rsc/client-references.ts");
22283
- BUNDLED_CLIENT_CODEC_PATH = join8(SOURCE_DIR, "rsc/bundled-client-codec.ts");
22445
+ SOURCE_DIR = dirname10(fileURLToPath4(import.meta.resolve("@teyik0/furin/rsc")));
22446
+ CLIENT_REFERENCE_RUNTIME_PATH = join6(SOURCE_DIR, "rsc/client-references.ts");
22447
+ BUNDLED_CLIENT_CODEC_PATH = join6(SOURCE_DIR, "rsc/bundled-client-codec.ts");
22284
22448
  });
22285
22449
 
22286
22450
  // src/shared/route-map.ts
@@ -22310,8 +22474,8 @@ ${body}
22310
22474
  }
22311
22475
 
22312
22476
  // src/build/route-types.ts
22313
- import { existsSync as existsSync11, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync2 } from "fs";
22314
- import { extname as extname3, join as join9, relative as relative11, resolve as resolve11 } from "path";
22477
+ import { existsSync as existsSync12, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync2 } from "fs";
22478
+ import { extname as extname3, join as join7, relative as relative9, resolve as resolve11 } from "path";
22315
22479
  function tagKeyToPropertyName(tag) {
22316
22480
  return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
22317
22481
  }
@@ -22322,38 +22486,19 @@ function tagToStringLiteral(tag) {
22322
22486
  function importSpecifier(path, projectRoot) {
22323
22487
  const extension = extname3(path);
22324
22488
  const sourcePath = extension ? path.slice(0, -extension.length) : path;
22325
- const relativePath = relative11(projectRoot, sourcePath).replaceAll("\\", "/");
22489
+ const relativePath = relative9(projectRoot, sourcePath).replaceAll("\\", "/");
22326
22490
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
22327
22491
  }
22328
- function fileRouteEntries({ pagesDir, prefix }, projectRoot) {
22329
- const pages = resolve11(pagesDir);
22330
- const files = routeSourcePaths({ pagesDir: pages, prefix }).map((path) => {
22331
- const relativePath = relative11(pages, path).replaceAll("\\", "/");
22332
- const segments = relativePath.split("/");
22333
- const base = (segments.pop() ?? "").slice(0, -extname3(path).length);
22334
- return { base, path, relativePath, segments };
22335
- });
22336
- const layouts = new Map(files.filter(({ base }) => base === "_route").map((file) => [file.segments.join("/"), file.path]));
22337
- return files.map(({ base, path, relativePath, segments }) => {
22338
- const isLayout = base === "_route";
22339
- let parent = join9(pages, "root.tsx");
22340
- for (let depth = isLayout ? segments.length - 1 : segments.length;depth > 0; depth -= 1) {
22341
- const layout = layouts.get(segments.slice(0, depth).join("/"));
22342
- if (layout) {
22343
- parent = layout;
22344
- break;
22345
- }
22346
- }
22347
- const pathParams = [...segments, base].flatMap((segment) => {
22348
- const dynamic = parseDynamicRouteSegment(segment, path);
22349
- return dynamic ? [dynamic.catchAll ? '"*": string' : `${dynamic.name}: string`] : [];
22350
- });
22351
- const id = fileRouteId({ pagesDir: pages, prefix }, path);
22352
- const pattern = filePathToPattern(isLayout ? segments.concat("index").join("/") : relativePath);
22492
+ function fileRouteEntries(instance, projectRoot) {
22493
+ const { prefix } = instance;
22494
+ const manifest = scanRouteManifest({ ...instance, pagesDir: resolve11(instance.pagesDir) });
22495
+ return manifest.routes.map(({ id, kind, params, parentPath, pattern }) => {
22496
+ const parent = parentPath ?? manifest.rootPath;
22497
+ const pathParams = params.map(({ name, optional }) => `${name}${optional ? "?" : ""}: string`);
22353
22498
  return {
22354
22499
  id,
22355
22500
  lines: ` ${JSON.stringify(id)}: {
22356
- kind: "${isLayout ? "layout" : "page"}";
22501
+ kind: "${kind}";
22357
22502
  pattern: ${JSON.stringify(`${prefix}${pattern === "/" ? "" : pattern}` || "/")};
22358
22503
  parent: typeof import(${JSON.stringify(importSpecifier(parent, projectRoot))}).route;
22359
22504
  pathParams: {${pathParams.length > 0 ? ` ${pathParams.join("; ")} ` : ""}};
@@ -22392,8 +22537,8 @@ import "@teyik0/furin/routes";
22392
22537
 
22393
22538
  ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapDeclaration(entries)}${tagBlock}
22394
22539
  `;
22395
- const typesPath = join9(projectRoot, "furin-env.d.ts");
22396
- const existing = existsSync11(typesPath) ? readFileSync9(typesPath, "utf8") : "";
22540
+ const typesPath = join7(projectRoot, "furin-env.d.ts");
22541
+ const existing = existsSync12(typesPath) ? readFileSync9(typesPath, "utf8") : "";
22397
22542
  if (content === existing) {
22398
22543
  return false;
22399
22544
  }
@@ -22403,8 +22548,7 @@ ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapD
22403
22548
  return true;
22404
22549
  }
22405
22550
  var init_route_types = __esm(() => {
22406
- init_route_tree();
22407
- init_patterns();
22551
+ init_route_manifest();
22408
22552
  });
22409
22553
 
22410
22554
  // src/build/shared.ts
@@ -22419,8 +22563,8 @@ var init_shared2 = __esm(() => {
22419
22563
  });
22420
22564
 
22421
22565
  // src/build/hydrate.ts
22422
- import { existsSync as existsSync12, mkdirSync, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
22423
- import { dirname as dirname12, join as join10 } from "path";
22566
+ import { existsSync as existsSync13, mkdirSync, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
22567
+ import { join as join8 } from "path";
22424
22568
  function generateClientReferenceEntry(boundaries) {
22425
22569
  if (boundaries.length === 0) {
22426
22570
  return "";
@@ -22472,11 +22616,13 @@ function hydrateEntry(routes, rootLayout, basePath, clientLogging, modulePathKey
22472
22616
  continue;
22473
22617
  }
22474
22618
  const parts = [`depth: ${seg.depth}`];
22619
+ const errorExport = seg.fromRoute ? "route.errorComponent" : "default";
22620
+ const notFoundExport = seg.fromRoute ? "route.notFoundComponent" : "default";
22475
22621
  if (errorIdent) {
22476
- parts.push(`error: ${errorIdent}.default`);
22622
+ parts.push(`error: ${errorIdent}.${errorExport}`);
22477
22623
  }
22478
22624
  if (notFoundIdent) {
22479
- parts.push(`notFound: ${notFoundIdent}.default`);
22625
+ parts.push(`notFound: ${notFoundIdent}.${notFoundExport}`);
22480
22626
  }
22481
22627
  if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
22482
22628
  parts.push("isRoot: false");
@@ -22741,6 +22887,7 @@ if (__deferred && __deferred._chunks) {
22741
22887
  // with the server (stale deploy) or the server returned something we
22742
22888
  // don't know how to hydrate. Bail loudly; the page stays static.
22743
22889
  log.error({ action: "hydrate_no_match", pathname });
22890
+ if (import.meta.hot) throw new Error(\`[furin] No client route matches \${pathname}; the page stays static.\`);
22744
22891
  return;
22745
22892
  }
22746
22893
  app = createElement(DocumentProvider, { value: documentState }, app);
@@ -22807,6 +22954,7 @@ if (__deferred && __deferred._chunks) {
22807
22954
  log.info({ action: "hydrate_complete", pathname });
22808
22955
  })().catch((err: unknown) => {
22809
22956
  log.error({ action: "hydrate_failed", pathname, error: String(err) });
22957
+ if (import.meta.hot) console.error("[furin] Hydration failed:", err);
22810
22958
  window.dispatchEvent(
22811
22959
  new CustomEvent("furin:client-error", { detail: { error: err, phase: "hydrate" } })
22812
22960
  );
@@ -22819,8 +22967,8 @@ function releaseDevRouteTypes(projectRoot, prefix) {
22819
22967
  function writeDevRouteTypes(projectRoot, prefix, app) {
22820
22968
  const apps = devRouteTypesApps.get(projectRoot) ?? new Map;
22821
22969
  devRouteTypesApps.set(projectRoot, apps.set(prefix, app));
22822
- const live = [...apps].filter(([, { pagesDir }]) => existsSync12(pagesDir));
22823
- return writeRouteTypes(live.find(([appPrefix]) => appPrefix === "")?.[1].routes ?? [], projectRoot, live.map(([appPrefix, { pagesDir }]) => ({ pagesDir, prefix: appPrefix })));
22970
+ const live = [...apps].filter(([, { pagesDir }]) => existsSync13(pagesDir));
22971
+ return writeRouteTypes(live.find(([appPrefix]) => appPrefix === "")?.[1].routes ?? [], projectRoot, live.map(([appPrefix, { pagesDir, style }]) => ({ pagesDir, prefix: appPrefix, style })));
22824
22972
  }
22825
22973
  function writeDevFiles(routes, {
22826
22974
  outDir,
@@ -22828,30 +22976,31 @@ function writeDevFiles(routes, {
22828
22976
  basePath,
22829
22977
  clientLogging,
22830
22978
  clientBoundaries,
22979
+ pages,
22831
22980
  prefix
22832
22981
  }, projectRoot, serverSourceVersion) {
22833
- if (!existsSync12(outDir)) {
22982
+ if (!existsSync13(outDir)) {
22834
22983
  mkdirSync(outDir, { recursive: true });
22835
22984
  }
22836
22985
  const serverVersion = serverSourceVersion === undefined ? "" : `
22837
22986
  if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};
22838
22987
  `;
22839
22988
  const hydrateCode = generateClientReferenceEntry(clientBoundaries ?? []) + generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
22840
- const hydratePath = join10(outDir, "_hydrate.tsx");
22841
- const existingHydrate = existsSync12(hydratePath) ? readFileSync10(hydratePath, "utf8") : "";
22989
+ const hydratePath = join8(outDir, "_hydrate.tsx");
22990
+ const existingHydrate = existsSync13(hydratePath) ? readFileSync10(hydratePath, "utf8") : "";
22842
22991
  let changed = false;
22843
22992
  if (hydrateCode !== existingHydrate) {
22844
22993
  writeFileSync3(hydratePath, hydrateCode);
22845
22994
  changed = true;
22846
22995
  }
22847
22996
  const indexHtml = generateIndexHtml();
22848
- const indexPath = join10(outDir, "index.html");
22849
- const existingIndex = existsSync12(indexPath) ? readFileSync10(indexPath, "utf8") : "";
22997
+ const indexPath = join8(outDir, "index.html");
22998
+ const existingIndex = existsSync13(indexPath) ? readFileSync10(indexPath, "utf8") : "";
22850
22999
  if (indexHtml !== existingIndex) {
22851
23000
  writeFileSync3(indexPath, indexHtml);
22852
23001
  changed = true;
22853
23002
  }
22854
- changed = writeDevRouteTypes(projectRoot, prefix, { pagesDir: dirname12(rootLayout), routes }) || changed;
23003
+ changed = writeDevRouteTypes(projectRoot, prefix, { ...pages, routes }) || changed;
22855
23004
  if (changed) {
22856
23005
  console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
22857
23006
  }
@@ -23144,7 +23293,7 @@ var init_discover = __esm(() => {
23144
23293
 
23145
23294
  // src/plugin/hmr-dependencies.ts
23146
23295
  import { readFileSync as readFileSync11 } from "fs";
23147
- import { dirname as dirname13, isAbsolute as isAbsolute7, resolve as resolve12 } from "path";
23296
+ import { dirname as dirname11, isAbsolute as isAbsolute7, resolve as resolve12 } from "path";
23148
23297
  function hmrDependencySignature(imports, filename) {
23149
23298
  const routePath = resolve12(filename);
23150
23299
  const visited = new Set;
@@ -23153,7 +23302,7 @@ function hmrDependencySignature(imports, filename) {
23153
23302
  if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
23154
23303
  return true;
23155
23304
  }
23156
- const path = Bun.resolveSync(specifier, dirname13(importer));
23305
+ const path = Bun.resolveSync(specifier, dirname11(importer));
23157
23306
  if (path === routePath) {
23158
23307
  return false;
23159
23308
  }
@@ -23320,21 +23469,18 @@ var exports_runtime = {};
23320
23469
  __export(exports_runtime, {
23321
23470
  createDevRuntime: () => createDevRuntime
23322
23471
  });
23323
- import { existsSync as existsSync13, readFileSync as readFileSync12 } from "fs";
23324
- import { basename as basename4, dirname as dirname14, join as join11, resolve as resolve13 } from "path";
23472
+ import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs";
23473
+ import { join as join9, resolve as resolve13 } from "path";
23325
23474
  import { staticPlugin as staticPlugin2 } from "@elysia/static";
23326
23475
  import { Elysia as Elysia17, file as file2 } from "elysia";
23327
- function wrapsRoute(sourcePath, routePath) {
23328
- if (!LAYOUT_FILE_RE.test(basename4(sourcePath))) {
23329
- return false;
23330
- }
23331
- const directory = dirname14(sourcePath).replaceAll("\\", "/");
23332
- return routePath.replaceAll("\\", "/").startsWith(`${directory}/`);
23476
+ function wrapsRoute(sourcePath, route) {
23477
+ const normalized = sourcePath.replaceAll("\\", "/");
23478
+ return route.layouts.some(({ path }) => path.replaceAll("\\", "/") === normalized);
23333
23479
  }
23334
23480
  function repairedDevelopmentRoutes(snapshot, changedSources, graph) {
23335
23481
  const patterns = new Set;
23336
23482
  for (const route of snapshot.routes) {
23337
- if (changedSources.some((sourcePath) => route.path === sourcePath || snapshot.root.path === sourcePath || graph.dependsOn(route.path, sourcePath) || wrapsRoute(sourcePath, route.path))) {
23483
+ if (changedSources.some((sourcePath) => route.path === sourcePath || snapshot.root.path === sourcePath || graph.dependsOn(route.path, sourcePath) || wrapsRoute(sourcePath, route))) {
23338
23484
  patterns.add(route.pattern);
23339
23485
  }
23340
23486
  }
@@ -23354,9 +23500,9 @@ function ownerAddsRouteHooks(app, owner) {
23354
23500
  const mounted = anchor && owner.routes.find((route) => route.method === anchor.method && route.handler === anchor.handler && route.path.endsWith(anchor.path));
23355
23501
  return mounted !== undefined && handlerPhaseHookCount(mounted.hooks) !== handlerPhaseHookCount(anchor?.hooks);
23356
23502
  }
23357
- async function loadDevelopmentRoutes(resolvedPagesDir) {
23503
+ async function loadDevelopmentRoutes(routeInstance) {
23358
23504
  await Promise.resolve().then(() => init_discovery());
23359
- return scanPages(resolvedPagesDir);
23505
+ return scanPages(routeInstance);
23360
23506
  }
23361
23507
  function createDevelopmentRouteSnapshot(instance, root, routes) {
23362
23508
  const searchRoutes = createSearchRouteMetadata(routes);
@@ -23367,7 +23513,7 @@ function createDevelopmentRouteSnapshot(instance, root, routes) {
23367
23513
  routes
23368
23514
  };
23369
23515
  }
23370
- async function createDevRuntime(instance, resolvedPagesDir, options) {
23516
+ async function createDevRuntime(instance, resolvedPagesDir, style, options) {
23371
23517
  const { prefix, syncPath } = instance;
23372
23518
  const { clientLogging, sync } = options;
23373
23519
  const cwd = process.cwd();
@@ -23383,7 +23529,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23383
23529
  registerDevPagePlugin();
23384
23530
  await Promise.resolve().then(() => init_dev_routes());
23385
23531
  await Promise.resolve().then(() => init_route_tree());
23386
- const routeInstance = { pagesDir: resolvedPagesDir, prefix };
23532
+ const routeInstance = { pagesDir: resolvedPagesDir, prefix, style };
23387
23533
  registerDevRoutesPlugin([routeInstance]);
23388
23534
  await Promise.resolve().then(() => init_route_config());
23389
23535
  const reportRouteConfig = createRouteConfigReporter(routeInstance, devDiagnosticStore(instance));
@@ -23391,7 +23537,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23391
23537
  const graph = devGraph(instance);
23392
23538
  const { nativeRoutesApp, root, routes } = await withInstance(instance, async () => {
23393
23539
  const { furinShell } = await import(routeModuleSpecifier(routeInstance));
23394
- const loaded = await loadDevelopmentRoutes(resolvedPagesDir);
23540
+ const loaded = await loadDevelopmentRoutes(routeInstance);
23395
23541
  return { nativeRoutesApp: furinShell, ...loaded };
23396
23542
  });
23397
23543
  const initialSnapshot = createDevelopmentRouteSnapshot(instance, root, routes);
@@ -23472,6 +23618,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23472
23618
  clientLogging: clientLogging ?? false,
23473
23619
  clientBoundaries,
23474
23620
  outDir: furinDir,
23621
+ pages: { pagesDir: resolvedPagesDir, style },
23475
23622
  publicPath: `${prefix}/_client/`,
23476
23623
  prefix,
23477
23624
  rootLayout: snapshot.root.path
@@ -23480,13 +23627,13 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23480
23627
  await writeCurrentDevFiles(initialSnapshot, []);
23481
23628
  graph.commit(initialSnapshot);
23482
23629
  reportRouteConfig();
23483
- const hmrEntry = (await import(join11(furinDir, "index.html"))).default;
23630
+ const hmrEntry = (await import(join9(furinDir, "index.html"))).default;
23484
23631
  const refreshDevelopmentRoutes = (changedSources) => withInstance(instance, async () => {
23485
23632
  invalidateStampedRouteModules();
23486
23633
  try {
23487
23634
  const previousSnapshot = currentSnapshot();
23488
23635
  const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
23489
- const next = await loadDevelopmentRoutes(resolvedPagesDir);
23636
+ const next = await loadDevelopmentRoutes(routeInstance);
23490
23637
  const nextRoutes = next.routes.map((route) => route.routeChain.length > 0 ? route : {
23491
23638
  ...route,
23492
23639
  tags: previousSnapshot.routes.find((previous) => previous.path === route.path)?.tags
@@ -23510,7 +23657,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23510
23657
  }
23511
23658
  } catch (error) {
23512
23659
  publishDevDiagnostic(error, {
23513
- entryPath: join11(resolvedPagesDir, "root.tsx"),
23660
+ entryPath: currentSnapshot().root.path,
23514
23661
  phase: "import",
23515
23662
  route: "*"
23516
23663
  });
@@ -23518,7 +23665,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23518
23665
  }
23519
23666
  });
23520
23667
  const publicDir = resolve13(cwd, "public");
23521
- const publicExists = existsSync13(publicDir);
23668
+ const publicExists = existsSync14(publicDir);
23522
23669
  const publicAssets = publicExists ? await staticPlugin2({ assets: publicDir, prefix: "/public" }) : new Elysia17;
23523
23670
  const browserEvents = (await Promise.resolve().then(() => (init_plugin2(), exports_plugin))).createBrowserEventsPlugin({
23524
23671
  development: instance.development,
@@ -23539,7 +23686,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23539
23686
  reportRouteConfig();
23540
23687
  },
23541
23688
  onSourceError: (error, sourcePath) => {
23542
- const route = currentSnapshot().routes.find((candidate) => graph.dependsOn(candidate.path, sourcePath) || wrapsRoute(sourcePath, candidate.path));
23689
+ const route = currentSnapshot().routes.find((candidate) => graph.dependsOn(candidate.path, sourcePath) || wrapsRoute(sourcePath, candidate));
23543
23690
  withInstance(instance, () => publishDevDiagnostic(error, {
23544
23691
  entryPath: route ? route.path : sourcePath,
23545
23692
  phase: "transform",
@@ -23561,12 +23708,12 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23561
23708
  routeTopologyWatcher?.close();
23562
23709
  routeTopologyWatcher = undefined;
23563
23710
  watcherOwner = undefined;
23564
- }).get("/_bun_hmr_entry/index.html", hmrEntry).get("/_bun_hmr_entry", hmrEntry).use(options.requestHooks).use(publicAssets).get("/favicon.ico", publicExists ? file2(join11(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(browserEvents).use(createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
23711
+ }).get("/_bun_hmr_entry/index.html", hmrEntry).get("/_bun_hmr_entry", hmrEntry).use(options.requestHooks).use(publicAssets).get("/favicon.ico", publicExists ? file2(join9(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(browserEvents).use(createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
23565
23712
  await routeTopologyWatcher?.refresh();
23566
23713
  })).use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
23567
23714
  };
23568
23715
  }
23569
- var LAYOUT_FILE_RE, HANDLER_PHASE_HOOKS;
23716
+ var HANDLER_PHASE_HOOKS;
23570
23717
  var init_runtime2 = __esm(() => {
23571
23718
  init_prefix();
23572
23719
  init_dev_loader();
@@ -23576,13 +23723,12 @@ var init_runtime2 = __esm(() => {
23576
23723
  init_hmr();
23577
23724
  init_patterns();
23578
23725
  init_schemas();
23579
- LAYOUT_FILE_RE = /^_route\.[cm]?[jt]sx?$/;
23580
23726
  HANDLER_PHASE_HOOKS = ["transform", "beforeHandle", "afterHandle"];
23581
23727
  });
23582
23728
 
23583
23729
  // src/furin.ts
23584
23730
  init_define_route();
23585
- import { dirname as dirname15, resolve as resolve14 } from "path";
23731
+ import { dirname as dirname12, resolve as resolve14 } from "path";
23586
23732
  import { Elysia as Elysia18, NotFound as NotFound2 } from "elysia";
23587
23733
 
23588
23734
  // src/server/cache/invalidation.ts
@@ -23798,13 +23944,13 @@ function createLoggerPlugin(instance, logger, clientLogging) {
23798
23944
 
23799
23945
  // src/server/prod/runtime.ts
23800
23946
  import { existsSync as existsSync5 } from "fs";
23801
- import { join as join4 } from "path";
23947
+ import { join as join3 } from "path";
23802
23948
  import { Elysia as Elysia12 } from "elysia";
23803
23949
 
23804
23950
  // src/server/assets/client-dir.ts
23805
23951
  init_prefix();
23806
23952
  import { existsSync } from "fs";
23807
- import { basename as basename2, delimiter, dirname as dirname3, join, resolve as resolve4 } from "path";
23953
+ import { basename as basename2, delimiter, dirname as dirname2, join, resolve as resolve4 } from "path";
23808
23954
  import { fileURLToPath as fileURLToPath2 } from "url";
23809
23955
  function resolveClientDirFromArgv(prefix) {
23810
23956
  const dirName = clientDirNameForPrefix(prefix);
@@ -23816,7 +23962,7 @@ function resolveClientDirFromEnv(dirName) {
23816
23962
  return null;
23817
23963
  }
23818
23964
  const base = envClientDir.startsWith("/") ? envClientDir : resolve4(process.cwd(), envClientDir);
23819
- return dirName === "client" ? base : join(dirname3(base), dirName);
23965
+ return dirName === "client" ? base : join(dirname2(base), dirName);
23820
23966
  }
23821
23967
  function resolveClientDirFromModuleUrl(dirName) {
23822
23968
  try {
@@ -23828,7 +23974,7 @@ function resolveClientDirFromModuleUrl(dirName) {
23828
23974
  if (modulePath.includes("/$bunfs/")) {
23829
23975
  return null;
23830
23976
  }
23831
- const moduleClientDir = join(dirname3(modulePath), dirName);
23977
+ const moduleClientDir = join(dirname2(modulePath), dirName);
23832
23978
  if (existsSync(join(moduleClientDir, "index.html"))) {
23833
23979
  return moduleClientDir;
23834
23980
  }
@@ -23860,7 +24006,7 @@ function resolveClientDirFromCandidate(candidate, dirName) {
23860
24006
  }
23861
24007
  const absolute = candidate.startsWith("/") ? candidate : resolve4(process.cwd(), candidate);
23862
24008
  if (existsSync(absolute)) {
23863
- const clientDir = join(dirname3(absolute), dirName);
24009
+ const clientDir = join(dirname2(absolute), dirName);
23864
24010
  if (existsSync(join(clientDir, "index.html"))) {
23865
24011
  return clientDir;
23866
24012
  }
@@ -23875,7 +24021,7 @@ function resolveClientDirFromPath(candidate, dirName) {
23875
24021
  for (const dir of pathEntries) {
23876
24022
  const fullPath = join(dir, candidate);
23877
24023
  if (existsSync(fullPath)) {
23878
- const clientDir = join(dirname3(fullPath), dirName);
24024
+ const clientDir = join(dirname2(fullPath), dirName);
23879
24025
  if (existsSync(join(clientDir, "index.html"))) {
23880
24026
  return clientDir;
23881
24027
  }
@@ -23893,12 +24039,12 @@ function resolveFallbackClientDir(dirName) {
23893
24039
 
23894
24040
  // src/server/assets/production.ts
23895
24041
  import { existsSync as existsSync2 } from "fs";
23896
- import { dirname as dirname4, isAbsolute as isAbsolute3, join as join2, relative as relative5, resolve as resolve5, sep } from "path";
24042
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join2, relative as relative4, resolve as resolve5, sep } from "path";
23897
24043
  import { staticPlugin } from "@elysia/static";
23898
24044
  import { Elysia as Elysia11, file } from "elysia";
23899
24045
  function resolveEmbeddedAssetPath(directory, requestPath) {
23900
24046
  const assetPath = resolve5(directory, requestPath);
23901
- const pathFromDirectory = relative5(directory, assetPath);
24047
+ const pathFromDirectory = relative4(directory, assetPath);
23902
24048
  if (pathFromDirectory === "" || pathFromDirectory === ".." || pathFromDirectory.startsWith(`..${sep}`) || isAbsolute3(pathFromDirectory)) {
23903
24049
  return null;
23904
24050
  }
@@ -23950,7 +24096,7 @@ async function createProductionAssetsPlugin(ctx, embedded, clientDir) {
23950
24096
  if (embedded) {
23951
24097
  return createEmbeddedAssetsPlugin(embedded);
23952
24098
  }
23953
- const publicDir = join2(dirname4(clientDir), "public");
24099
+ const publicDir = join2(dirname3(clientDir), "public");
23954
24100
  const publicAssets = existsSync2(publicDir) ? new Elysia11().get("/favicon.ico", file(join2(publicDir, "favicon.ico"))).use(await staticPlugin({ assets: publicDir, prefix: "/public" })) : new Elysia11;
23955
24101
  return publicAssets.use(await staticPlugin({
23956
24102
  assets: clientDir,
@@ -23995,7 +24141,7 @@ async function createProductionBrowserEventsPlugin(sync, websocket, development)
23995
24141
  }
23996
24142
  async function setupProdTemplate(embedded, clientDir, instance) {
23997
24143
  if (embedded) {
23998
- const templatePath = join4(embedded.clientDir, "index.html");
24144
+ const templatePath = join3(embedded.clientDir, "index.html");
23999
24145
  if (!existsSync5(templatePath)) {
24000
24146
  throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
24001
24147
  }
@@ -24003,7 +24149,7 @@ async function setupProdTemplate(embedded, clientDir, instance) {
24003
24149
  setProductionTemplateContent(html, instance);
24004
24150
  return;
24005
24151
  }
24006
- const templatePath = join4(clientDir, "index.html");
24152
+ const templatePath = join3(clientDir, "index.html");
24007
24153
  if (!existsSync5(templatePath)) {
24008
24154
  throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
24009
24155
  }
@@ -25449,6 +25595,10 @@ function AwaitInner({ resolve, children }) {
25449
25595
  // src/furin.ts
25450
25596
  init_defer();
25451
25597
  init_not_found();
25598
+ var DEFAULT_PAGES_DIRS = {
25599
+ nextjs: "src/app",
25600
+ tanstack: "src/routes"
25601
+ };
25452
25602
  function configurePageCache(instance, ctx, pageCache) {
25453
25603
  if (pageCache !== undefined && ctx?.adapter?.capabilities.publicCache === "platform") {
25454
25604
  throw new Error(`[furin] pageCache cannot be configured with the ${JSON.stringify(ctx.adapter.name)} adapter: its platform caches public SSG, ISR, and PPR pages.`);
@@ -25492,13 +25642,14 @@ async function createFurinApp(options) {
25492
25642
  logger,
25493
25643
  pageCache,
25494
25644
  pagesDir,
25645
+ style,
25495
25646
  sync
25496
25647
  } = options;
25497
25648
  const prefix = normalizePrefix(options.prefix);
25498
25649
  const cwd = process.cwd();
25499
- const paramPagesDir = resolve14(cwd, pagesDir ?? "src/pages");
25650
+ const paramPagesDir = resolve14(cwd, pagesDir ?? DEFAULT_PAGES_DIRS[style]);
25500
25651
  const ctx = getCompileContext(paramPagesDir, prefix);
25501
- const resolvedPagesDir = ctx?.rootPath ? dirname15(ctx.rootPath) : paramPagesDir;
25652
+ const resolvedPagesDir = ctx?.rootPath ? dirname12(ctx.rootPath) : paramPagesDir;
25502
25653
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
25503
25654
  const instance = createInstance(prefix, normalizedPagesDir);
25504
25655
  instance.syncPath = resolveSyncPath(sync);
@@ -25521,7 +25672,7 @@ async function createFurinApp(options) {
25521
25672
  }),
25522
25673
  sync: sync || undefined
25523
25674
  };
25524
- const mode = development ? await (await Promise.resolve().then(() => (init_runtime2(), exports_runtime))).createDevRuntime(instance, resolvedPagesDir, modeOptions) : await createProdRuntime(instance, ctx, clientDir, modeOptions);
25675
+ const mode = development ? await (await Promise.resolve().then(() => (init_runtime2(), exports_runtime))).createDevRuntime(instance, resolvedPagesDir, style, modeOptions) : await createProdRuntime(instance, ctx, clientDir, modeOptions);
25525
25676
  const app = new Elysia18({
25526
25677
  name: `furin-${prefix}-${normalizedPagesDir}`,
25527
25678
  prefix: prefix || undefined,
@@ -25540,14 +25691,18 @@ async function createFurinApp(options) {
25540
25691
  }
25541
25692
  var mountedPrefixes = new WeakMap;
25542
25693
  async function furin(options) {
25694
+ if (options.style !== "nextjs" && options.style !== "tanstack") {
25695
+ throw new Error(`[furin] furin() requires style: "nextjs" or "tanstack", received ${JSON.stringify(options.style)}.`);
25696
+ }
25543
25697
  const registration = {
25544
- pagesDir: options?.pagesDir ?? "src/pages",
25545
- prefix: normalizePrefix(options?.prefix)
25698
+ pagesDir: options.pagesDir ?? DEFAULT_PAGES_DIRS[options.style],
25699
+ prefix: normalizePrefix(options.prefix),
25700
+ style: options.style
25546
25701
  };
25547
25702
  if (recordFurinRegistration(registration)) {
25548
25703
  return (parentApp) => parentApp;
25549
25704
  }
25550
- const { app, hasSync, instance } = await createFurinApp(options ?? {});
25705
+ const { app, hasSync, instance } = await createFurinApp(options);
25551
25706
  let mounted = false;
25552
25707
  return (parentApp) => {
25553
25708
  if (mounted) {