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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) 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 +565 -401
  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 +594 -422
  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/internal/runtime-types.d.ts +8 -0
  18. package/dist/client/link.js +3 -3
  19. package/dist/client/router/link-utils.d.ts +3 -2
  20. package/dist/client/router/search/index.js +2 -2
  21. package/dist/client/router/types.d.ts +9 -3
  22. package/dist/client.js +22 -6
  23. package/dist/config.d.ts +4 -0
  24. package/dist/config.js +4 -1
  25. package/dist/define-route.d.ts +53 -12
  26. package/dist/furin.d.ts +13 -3
  27. package/dist/furin.js +766 -614
  28. package/dist/plugin/route-config.d.ts +3 -3
  29. package/dist/plugin/route-manifest.d.ts +46 -0
  30. package/dist/plugin/route-tree.d.ts +13 -29
  31. package/dist/routes.d.ts +2 -2
  32. package/dist/server/dev/runtime.d.ts +2 -1
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +57 -76
  35. package/dist/server/registrations.d.ts +4 -2
  36. package/dist/server/router/defined-route.d.ts +4 -0
  37. package/dist/server/router/discovery.d.ts +14 -4
  38. package/dist/server/router/hmr.d.ts +12 -12
  39. package/dist/server/router/patterns.d.ts +4 -12
  40. package/dist/server/router/types.d.ts +16 -1
  41. package/dist/server/static-export.js +88 -120
  42. package/dist/server/sync/drizzle/index.d.ts +8 -10
  43. package/dist/shared/route-specificity.d.ts +10 -1
  44. package/package.json +3 -6
  45. package/src/adapter/package.ts +11 -37
  46. package/src/adapter/runtime-build.ts +5 -4
  47. package/src/adapter/static.ts +1 -1
  48. package/src/adapter/vercel.ts +2 -1
  49. package/src/build/client.ts +3 -3
  50. package/src/build/discover-pages-process.ts +1 -1
  51. package/src/build/elysia-aot.ts +2 -2
  52. package/src/build/entry-template.ts +3 -15
  53. package/src/build/hydrate.ts +12 -6
  54. package/src/build/index.ts +19 -9
  55. package/src/build/route-metadata.ts +15 -8
  56. package/src/build/route-types.ts +18 -43
  57. package/src/build/types.ts +12 -5
  58. package/src/cli/config.ts +6 -0
  59. package/src/cli/index.ts +30 -14
  60. package/src/client/define-route.ts +29 -4
  61. package/src/client/internal/runtime-types.ts +8 -0
  62. package/src/client/router/link-utils.ts +16 -8
  63. package/src/client/router/types.ts +40 -14
  64. package/src/config.ts +5 -0
  65. package/src/define-route.ts +85 -16
  66. package/src/furin.ts +31 -7
  67. package/src/plugin/dev-routes.ts +8 -17
  68. package/src/plugin/route-config.ts +77 -62
  69. package/src/plugin/route-manifest.ts +437 -0
  70. package/src/plugin/route-modules.ts +6 -1
  71. package/src/plugin/route-registry.ts +7 -21
  72. package/src/plugin/route-tree.ts +71 -181
  73. package/src/routes.ts +2 -2
  74. package/src/server/dev/runtime.ts +16 -22
  75. package/src/server/internal.ts +4 -1
  76. package/src/server/registrations.ts +5 -2
  77. package/src/server/render/static-params.ts +2 -10
  78. package/src/server/router/defined-route.ts +8 -0
  79. package/src/server/router/discovery.ts +237 -196
  80. package/src/server/router/hmr.ts +45 -63
  81. package/src/server/router/patterns.ts +41 -117
  82. package/src/server/router/types.ts +17 -1
  83. package/src/server/sync/drizzle/index.ts +18 -19
  84. package/src/shared/route-specificity.ts +34 -2
  85. package/src/shared/utils/index.ts +1 -1
package/dist/cli/index.js CHANGED
@@ -8,11 +8,11 @@ import { parseArgs as parseArgs2 } from "util";
8
8
 
9
9
  // src/build/index.ts
10
10
  import { existsSync as existsSync18, writeFileSync as writeFileSync13 } from "fs";
11
- import { join as join23, relative as relative16, resolve as resolve13 } from "path";
11
+ import { join as join21, relative as relative15, resolve as resolve13 } from "path";
12
12
 
13
13
  // src/adapter/build.ts
14
14
  import { existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
15
- import { basename as basename5, extname as extname3, join as join15, relative as relative10 } from "path";
15
+ import { basename as basename5, extname as extname3, join as join14, relative as relative9 } from "path";
16
16
 
17
17
  // src/build/bun-build.ts
18
18
  var PRODUCTION_DEFINE = { "process.env.NODE_ENV": JSON.stringify("production") };
@@ -191,7 +191,7 @@ function segmentSpecificity(segment) {
191
191
  }
192
192
  return segment.startsWith(":") ? 2 : 3;
193
193
  }
194
- function compareRouteSpecificity(a, b) {
194
+ function compareConcreteSpecificity(a, b) {
195
195
  const aSegments = a.split("/").filter(Boolean);
196
196
  const bSegments = b.split("/").filter(Boolean);
197
197
  const length = Math.max(aSegments.length, bSegments.length);
@@ -211,6 +211,24 @@ function compareRouteSpecificity(a, b) {
211
211
  }
212
212
  return 0;
213
213
  }
214
+ function expandOptionalSegments(pattern) {
215
+ let variants = [[]];
216
+ for (const segment of pattern.split("/").filter(Boolean)) {
217
+ if (segment.startsWith(":") && segment.endsWith("?")) {
218
+ const required = segment.slice(0, -1);
219
+ variants = variants.flatMap((variant) => [variant, [...variant, required]]);
220
+ } else {
221
+ variants = variants.map((variant) => [...variant, segment]);
222
+ }
223
+ }
224
+ return variants.map((variant) => `/${variant.join("/")}`);
225
+ }
226
+ function mostSpecificVariant(pattern) {
227
+ return expandOptionalSegments(pattern).reduce((best, variant) => compareConcreteSpecificity(variant, best) > 0 ? variant : best);
228
+ }
229
+ function compareRouteSpecificity(a, b) {
230
+ return compareConcreteSpecificity(mostSpecificVariant(a), mostSpecificVariant(b));
231
+ }
214
232
 
215
233
  // src/shared/search-params.ts
216
234
  function isObject(value) {
@@ -359,7 +377,6 @@ function normalizePrefix(prefix) {
359
377
  }
360
378
 
361
379
  // src/server/router/patterns.ts
362
- import { parse } from "path";
363
380
  function resolveRouteRevalidate(page) {
364
381
  return page.revalidate ?? page._route.revalidate;
365
382
  }
@@ -379,60 +396,7 @@ function resolveDocumentRevalidate(route) {
379
396
  }
380
397
  return Math.min(...intervals);
381
398
  }
382
- var DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
383
- function parseDynamicRouteSegment(segment, sourcePath) {
384
- if (!(segment.startsWith("[") && segment.endsWith("]"))) {
385
- return;
386
- }
387
- const inner = segment.slice(1, -1);
388
- const catchAll = inner.startsWith("...");
389
- const name = catchAll ? inner.slice(3) : inner;
390
- if (!DYNAMIC_PARAMETER_NAME_RE.test(name)) {
391
- throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(name)} in ${JSON.stringify(sourcePath ?? segment)}. Parameter names must match ${DYNAMIC_PARAMETER_NAME_RE}.`);
392
- }
393
- return { catchAll, name };
394
- }
395
- function routeSegmentToPattern(segment) {
396
- const dynamic = parseDynamicRouteSegment(segment, undefined);
397
- if (!dynamic) {
398
- return segment;
399
- }
400
- return dynamic.catchAll ? "*" : `:${dynamic.name}`;
401
- }
402
- var ROUTE_GROUP_RE = /^\([^()]+\)$/;
403
- function isRouteGroup(segment) {
404
- return ROUTE_GROUP_RE.test(segment);
405
- }
406
- var DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
407
- function routePatternKey(pattern) {
408
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
409
- }
410
- function filePathToPattern(path) {
411
- const parts = path.replaceAll("\\", "/").split("/");
412
- const segments = [];
413
- const lastIndex = parts.length - 1;
414
- for (let idx = 0;idx < parts.length; idx += 1) {
415
- const part = parts[idx];
416
- if (part === undefined || part.length === 0) {
417
- continue;
418
- }
419
- const isFile = idx === lastIndex;
420
- const name = isFile ? parse(part).name : part;
421
- if (!isFile && isRouteGroup(name)) {
422
- continue;
423
- }
424
- if (isFile && name === "index") {
425
- continue;
426
- }
427
- const dynamic = parseDynamicRouteSegment(name, path);
428
- if (dynamic) {
429
- segments.push(dynamic.catchAll ? "*" : `:${dynamic.name}`);
430
- } else {
431
- segments.push(name);
432
- }
433
- }
434
- return `/${segments.join("/")}`;
435
- }
399
+ var SPLAT_PARAM = "_splat";
436
400
  var REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/g;
437
401
  function escapeRegExp(value) {
438
402
  return value.replace(REGEX_META_CHARS_RE, "\\$&");
@@ -448,11 +412,17 @@ function routePatternRegexSource(pattern, sources) {
448
412
  while (i < pattern.length && pattern[i] !== "/") {
449
413
  i += 1;
450
414
  }
451
- paramNames.push(pattern.slice(start, i));
452
- source += sources.param;
415
+ const name = pattern.slice(start, i);
416
+ if (name.endsWith("?") && source.endsWith("/")) {
417
+ paramNames.push(name.slice(0, -1));
418
+ source = `${source.slice(0, -1)}(?:/${sources.param})?`;
419
+ } else {
420
+ paramNames.push(name);
421
+ source += sources.param;
422
+ }
453
423
  } else if (pattern[i] === "*") {
454
- paramNames.push("*");
455
- source += sources.catchAll;
424
+ paramNames.push(SPLAT_PARAM);
425
+ source = source.endsWith("/") ? `${source.slice(0, -1)}(?:/${sources.catchAll})?` : source + sources.catchAll;
456
426
  i += 1;
457
427
  } else {
458
428
  const ch = pattern[i];
@@ -1775,18 +1745,19 @@ function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
1775
1745
 
1776
1746
  // src/build/server-app-entry.ts
1777
1747
  import { writeFileSync as writeFileSync2 } from "fs";
1778
- import { join as join7 } from "path";
1748
+ import { join as join6 } from "path";
1779
1749
 
1780
1750
  // src/plugin/route-registry.ts
1781
- import { dirname as dirname5, join as join6, resolve as resolve2 } from "path";
1751
+ import { dirname as dirname5, join as join5, resolve as resolve2 } from "path";
1782
1752
 
1783
1753
  // src/plugin/route-modules.ts
1784
1754
  import { existsSync as existsSync5, readFileSync, realpathSync, statSync } from "fs";
1785
1755
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join4, relative as relative3, sep } from "path";
1786
1756
  import { pathToFileURL } from "url";
1787
1757
  var ROUTE_MODULE_CACHE_SYMBOL = Symbol.for("@teyik0/furin/route-module-cache");
1758
+ var OPTIONAL_MARK = /\?$/;
1788
1759
  function validateRouteParams(path, schemas) {
1789
- const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
1760
+ const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? SPLAT_PARAM : segment.slice(1).replace(OPTIONAL_MARK, ""));
1790
1761
  if (pathParams.length === 0) {
1791
1762
  return;
1792
1763
  }
@@ -1902,118 +1873,342 @@ async function validateRouteModules(routeFiles) {
1902
1873
  }
1903
1874
 
1904
1875
  // src/plugin/route-tree.ts
1876
+ import { resolve } from "path";
1877
+
1878
+ // src/plugin/route-manifest.ts
1905
1879
  import { existsSync as existsSync6, readdirSync } from "fs";
1906
- import { extname, join as join5, relative as relative4, resolve } from "path";
1880
+ import { extname } from "path";
1907
1881
  var ROUTE_EXTENSION = /\.(?:jsx?|tsx?)$/;
1908
- var ROUTE_CONVENTIONS = new Set(["error", "not-found", "root"]);
1909
- function instanceKey(instance) {
1910
- return `${resolve(instance.pagesDir)}\x00${instance.prefix}`;
1882
+ var PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
1883
+ var BRACKET_ESCAPE = /\[([^\]]*)\]/g;
1884
+ var SOURCE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
1885
+ var PARAM_SEGMENT = /(^|\/):[^/]+/g;
1886
+ var NEXT_CATCH_ALL = /^\[\[?\.\.\.([^\]]+)\]\]?$/;
1887
+ function child(directory, name) {
1888
+ return `${directory}/${name}`;
1889
+ }
1890
+ function sortedEntries(directory) {
1891
+ return readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
1892
+ }
1893
+ function moduleBase(name) {
1894
+ if (name.endsWith(".d.ts") || !ROUTE_EXTENSION.test(name)) {
1895
+ return;
1896
+ }
1897
+ return name.slice(0, -extname(name).length);
1911
1898
  }
1912
- function routeModuleSpecifier(instance) {
1913
- return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
1899
+ function findModule(directory, base) {
1900
+ return SOURCE_EXTENSIONS.map((extension) => child(directory, `${base}${extension}`)).find((path) => existsSync6(path));
1914
1901
  }
1915
- function scanRouteFiles(directory, directorySegments, files) {
1916
- const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
1917
- for (const entry of entries) {
1918
- if (entry.isDirectory()) {
1919
- if (entry.name.startsWith("_")) {
1920
- continue;
1921
- }
1922
- scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
1923
- continue;
1924
- }
1925
- const extension = extname(entry.name);
1926
- if (!ROUTE_EXTENSION.test(extension) || entry.name.endsWith(".d.ts")) {
1927
- continue;
1928
- }
1929
- const base = entry.name.slice(0, -extension.length);
1930
- const sourcePath = join5(directory, entry.name);
1931
- for (const segment of [...directorySegments, base]) {
1932
- parseDynamicRouteSegment(segment, sourcePath);
1933
- }
1934
- if (ROUTE_CONVENTIONS.has(base)) {
1902
+ function paramName(name, raw, sourcePath) {
1903
+ if (!PARAM_NAME.test(name)) {
1904
+ throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(raw)} in ${JSON.stringify(sourcePath)}. Parameter names must match ${PARAM_NAME}.`);
1905
+ }
1906
+ return name;
1907
+ }
1908
+ function splitFlatName(base) {
1909
+ const tokens = [];
1910
+ let current = "";
1911
+ let escaped = false;
1912
+ for (const character of base) {
1913
+ if (character === "[") {
1914
+ escaped = true;
1915
+ } else if (character === "]") {
1916
+ escaped = false;
1917
+ }
1918
+ if (character === "." && !escaped) {
1919
+ tokens.push(current);
1920
+ current = "";
1935
1921
  continue;
1936
1922
  }
1937
- if (base.startsWith("_") && base !== "_route") {
1938
- continue;
1923
+ current += character;
1924
+ }
1925
+ tokens.push(current);
1926
+ return tokens;
1927
+ }
1928
+ function tanstackSegment(raw, sourcePath) {
1929
+ if (raw.startsWith("(") && raw.endsWith(")")) {
1930
+ return { raw, type: "group" };
1931
+ }
1932
+ if (raw === "$") {
1933
+ return { raw, type: "splat" };
1934
+ }
1935
+ if (raw.startsWith("{-$") && raw.endsWith("}")) {
1936
+ return {
1937
+ name: paramName(raw.slice(3, -1), raw, sourcePath),
1938
+ optional: true,
1939
+ raw,
1940
+ type: "param"
1941
+ };
1942
+ }
1943
+ if (raw.startsWith("$")) {
1944
+ return { name: paramName(raw.slice(1), raw, sourcePath), optional: false, raw, type: "param" };
1945
+ }
1946
+ if (raw.startsWith("_")) {
1947
+ return { raw, type: "pathless" };
1948
+ }
1949
+ const value = (raw.endsWith("_") ? raw.slice(0, -1) : raw).replace(BRACKET_ESCAPE, "$1");
1950
+ return { raw, type: "static", value };
1951
+ }
1952
+ function tanstackCandidate(base, segments, sourcePath) {
1953
+ const tokens = splitFlatName(base);
1954
+ const last = tokens.at(-1);
1955
+ const index = last === "index";
1956
+ const routeFile = last === "route";
1957
+ const own = (index || routeFile ? tokens.slice(0, -1) : tokens).map((token) => tanstackSegment(token, sourcePath));
1958
+ const routeSegments = [...segments, ...own];
1959
+ if (routeFile && routeSegments.length === 0) {
1960
+ throw new Error(`[furin] ${sourcePath}: a top-level route.tsx has no path to wrap. The root layout lives in __root.tsx.`);
1961
+ }
1962
+ return {
1963
+ forcedLayout: routeFile || routeSegments.at(-1)?.type === "pathless",
1964
+ index,
1965
+ segments: routeSegments,
1966
+ sourcePath
1967
+ };
1968
+ }
1969
+ function scanTanstack(pagesDir) {
1970
+ const candidates = [];
1971
+ const walk = (directory, segments) => {
1972
+ for (const entry of sortedEntries(directory)) {
1973
+ if (entry.name.startsWith("-")) {
1974
+ continue;
1975
+ }
1976
+ const sourcePath = child(directory, entry.name);
1977
+ if (entry.isDirectory()) {
1978
+ walk(sourcePath, [...segments, tanstackSegment(entry.name, sourcePath)]);
1979
+ continue;
1980
+ }
1981
+ const base = moduleBase(entry.name);
1982
+ if (base !== undefined && !(segments.length === 0 && base === "__root")) {
1983
+ candidates.push(tanstackCandidate(base, segments, sourcePath));
1984
+ }
1939
1985
  }
1940
- files.push({
1941
- base,
1942
- directorySegments,
1986
+ };
1987
+ walk(pagesDir, []);
1988
+ return {
1989
+ boundaries: [],
1990
+ candidates,
1991
+ rootPath: findModule(pagesDir, "__root") ?? child(pagesDir, "__root.tsx")
1992
+ };
1993
+ }
1994
+ function nextSegment(name, sourcePath) {
1995
+ if (name.startsWith("(") && name.endsWith(")")) {
1996
+ return { raw: name, type: "group" };
1997
+ }
1998
+ const catchAll = name.match(NEXT_CATCH_ALL);
1999
+ if (catchAll?.[1] !== undefined) {
2000
+ paramName(catchAll[1], name, sourcePath);
2001
+ return { raw: "$", type: "splat" };
2002
+ }
2003
+ if (name.startsWith("[") && name.endsWith("]")) {
2004
+ const name_ = paramName(name.slice(1, -1), name, sourcePath);
2005
+ return { name: name_, optional: false, raw: `$${name_}`, type: "param" };
2006
+ }
2007
+ return { raw: name, type: "static", value: name };
2008
+ }
2009
+ function addNextFile(state, base, segments, sourcePath) {
2010
+ if (base === "route") {
2011
+ throw new Error(`[furin] ${sourcePath}: route handlers are not supported. Declare API routes on your Elysia app instead.`);
2012
+ }
2013
+ if (base === "layout" && segments.at(-1)?.type === "splat") {
2014
+ throw new Error(`[furin] ${sourcePath}: a layout cannot share a catch-all folder with its page: move it to the parent folder.`);
2015
+ }
2016
+ if (base === "page" || base === "layout" && segments.length > 0) {
2017
+ state.candidates.push({
2018
+ forcedLayout: base === "layout",
2019
+ index: base === "page" && segments.at(-1)?.type !== "splat",
2020
+ segments,
1943
2021
  sourcePath
1944
2022
  });
2023
+ } else if (base === "layout") {
2024
+ state.rootPath ??= sourcePath;
2025
+ } else if (base === "error") {
2026
+ state.boundary.errorPath ??= sourcePath;
2027
+ } else if (base === "not-found") {
2028
+ state.boundary.notFoundPath ??= sourcePath;
1945
2029
  }
1946
2030
  }
1947
- var INDEX_SUFFIX = /\/index$/;
1948
- function fileRouteId({ pagesDir, prefix }, sourcePath) {
1949
- const path = relative4(pagesDir, sourcePath).replaceAll("\\", "/").replace(ROUTE_EXTENSION, "");
1950
- return `${prefix}/${path}`.replace(INDEX_SUFFIX, "") || "/";
2031
+ function scanNext(pagesDir) {
2032
+ const candidates = [];
2033
+ const boundaries = [];
2034
+ let rootPath;
2035
+ const walk = (directory, segments) => {
2036
+ const boundary = { directory, errorPath: undefined, notFoundPath: undefined };
2037
+ const state = { boundary, candidates, rootPath };
2038
+ for (const entry of sortedEntries(directory)) {
2039
+ const sourcePath = child(directory, entry.name);
2040
+ if (!entry.isDirectory()) {
2041
+ addNextFile(state, moduleBase(entry.name), segments, sourcePath);
2042
+ } else if (!entry.name.startsWith("_")) {
2043
+ walk(sourcePath, [...segments, nextSegment(entry.name, sourcePath)]);
2044
+ }
2045
+ }
2046
+ rootPath ??= state.rootPath;
2047
+ if (boundary.errorPath || boundary.notFoundPath) {
2048
+ boundaries.push(boundary);
2049
+ }
2050
+ };
2051
+ walk(pagesDir, []);
2052
+ boundaries.sort((left, right) => left.directory.length - right.directory.length);
2053
+ return { boundaries, candidates, rootPath: rootPath ?? child(pagesDir, "layout.tsx") };
2054
+ }
2055
+ function segmentKey(segments) {
2056
+ return segments.map((segment) => segment.raw).join("/");
2057
+ }
2058
+ function segmentPattern(segment) {
2059
+ switch (segment.type) {
2060
+ case "group":
2061
+ case "pathless":
2062
+ return;
2063
+ case "param":
2064
+ return `:${segment.name}${segment.optional ? "?" : ""}`;
2065
+ case "splat":
2066
+ return "*";
2067
+ default:
2068
+ return segment.value;
2069
+ }
1951
2070
  }
1952
- function segmentPath(segment) {
1953
- return routeSegmentToPattern(segment);
2071
+ function urlPattern(segments) {
2072
+ return `/${segments.flatMap((segment) => segmentPattern(segment) ?? []).join("/")}`;
1954
2073
  }
1955
- function routeId(instanceId, path) {
1956
- const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
1957
- return `_route_${instanceId}_${encodedPath}`;
2074
+ function routeParams(segments) {
2075
+ return segments.flatMap((segment) => {
2076
+ if (segment.type === "param") {
2077
+ return [{ name: segment.name, optional: segment.optional }];
2078
+ }
2079
+ return segment.type === "splat" ? [{ name: "_splat", optional: false }] : [];
2080
+ });
1958
2081
  }
1959
- function scanRouteManifest(pagesDir) {
1960
- const scannedFiles = [];
1961
- scanRouteFiles(pagesDir, [], scannedFiles);
2082
+ function assertSplatLast(candidate) {
2083
+ const splat = candidate.segments.findIndex((segment) => segment.type === "splat");
2084
+ if (splat !== -1 && splat < candidate.segments.length - 1) {
2085
+ throw new Error(`[furin] ${candidate.sourcePath}: a catch-all segment must be the last segment of its path.`);
2086
+ }
2087
+ }
2088
+ function patternKeys(pattern) {
2089
+ const keys = expandOptionalSegments(pattern).map((variant) => variant.replace(PARAM_SEGMENT, "$1:param"));
2090
+ return [...new Set(keys)];
2091
+ }
2092
+ function claimPatterns(seenPatterns, pattern, sourcePath, relativePath) {
2093
+ for (const patternKey of patternKeys(pattern)) {
2094
+ const previous = seenPatterns.get(patternKey);
2095
+ if (previous !== undefined) {
2096
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${relativePath(previous)}" and "${relativePath(sourcePath)}".`);
2097
+ }
2098
+ seenPatterns.set(patternKey, sourcePath);
2099
+ }
2100
+ }
2101
+ function buildManifest(scan, pagesDir, prefix) {
2102
+ const relativePath = (path) => path.slice(pagesDir.length + 1);
2103
+ const { candidates } = scan;
2104
+ const keys = candidates.map((candidate) => segmentKey(candidate.segments));
2105
+ const hasDescendant = (key, self2) => candidates.some((other, index) => other !== self2 && (keys[index]?.startsWith(`${key}/`) === true || other.index && keys[index] === key));
2106
+ const layouts = new Map;
2107
+ const kinds = candidates.map((candidate, index) => {
2108
+ assertSplatLast(candidate);
2109
+ const key = keys[index] ?? "";
2110
+ const isLayout = !candidate.index && (candidate.forcedLayout || hasDescendant(key, candidate));
2111
+ if (!isLayout) {
2112
+ return "page";
2113
+ }
2114
+ const existing = layouts.get(key);
2115
+ if (existing !== undefined) {
2116
+ throw new Error(`[furin] Two layouts wrap "/${key}": "${relativePath(existing)}" and "${relativePath(candidate.sourcePath)}".`);
2117
+ }
2118
+ layouts.set(key, candidate.sourcePath);
2119
+ return "layout";
2120
+ });
2121
+ const seenIds = new Map;
1962
2122
  const seenPatterns = new Map;
1963
- return scannedFiles.map((file) => {
1964
- if (file.base === "_route") {
1965
- return { ...file, pattern: undefined };
1966
- }
1967
- const relativePath = relative4(pagesDir, file.sourcePath).replaceAll("\\", "/");
1968
- const pattern = filePathToPattern(relativePath);
1969
- const patternKey = routePatternKey(pattern);
1970
- const previousPath = seenPatterns.get(patternKey);
1971
- if (previousPath !== undefined) {
1972
- throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
1973
- }
1974
- seenPatterns.set(patternKey, relativePath);
1975
- return { ...file, pattern };
2123
+ const routes = candidates.map((candidate, index) => {
2124
+ const kind = kinds[index] ?? "page";
2125
+ const { segments, sourcePath } = candidate;
2126
+ const key = keys[index] ?? "";
2127
+ let parentPath = candidate.index ? layouts.get(key) : undefined;
2128
+ for (let depth = segments.length - 1;parentPath === undefined && depth > 0; depth -= 1) {
2129
+ parentPath = layouts.get(segmentKey(segments.slice(0, depth)));
2130
+ }
2131
+ const path = `/${key}${candidate.index && key !== "" ? "/" : ""}`;
2132
+ const id = prefix === "" ? path : `${prefix}${path}`;
2133
+ const previousId = seenIds.get(id);
2134
+ if (previousId !== undefined) {
2135
+ throw new Error(`[furin] Duplicate route id "${id}" from "${relativePath(previousId)}" and "${relativePath(sourcePath)}".`);
2136
+ }
2137
+ seenIds.set(id, sourcePath);
2138
+ const pattern = urlPattern(segments);
2139
+ if (kind === "page") {
2140
+ claimPatterns(seenPatterns, pattern, sourcePath, relativePath);
2141
+ }
2142
+ return { id, kind, params: routeParams(segments), parentPath, pattern, sourcePath };
1976
2143
  });
2144
+ return { boundaries: scan.boundaries, rootPath: scan.rootPath, routes };
1977
2145
  }
1978
- function buildRouteTree(pagesDir, instanceId) {
1979
- const nodes = new Map;
1980
- const ensureNode = (segments) => {
1981
- const key = segments.join("/");
1982
- const existing = nodes.get(key);
2146
+ function scanRouteManifest({ pagesDir, prefix, style }) {
2147
+ const directory = pagesDir.replaceAll("\\", "/");
2148
+ return buildManifest(style === "nextjs" ? scanNext(directory) : scanTanstack(directory), directory, prefix);
2149
+ }
2150
+
2151
+ // src/plugin/route-tree.ts
2152
+ function instanceKey(instance) {
2153
+ return `${resolve(instance.pagesDir)}\x00${instance.prefix}`;
2154
+ }
2155
+ function routeModuleSpecifier(instance) {
2156
+ return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
2157
+ }
2158
+ function routeId(instanceId, id) {
2159
+ const encodedId = Array.from(new TextEncoder().encode(id), (byte) => byte.toString(16).padStart(2, "0")).join("");
2160
+ return `_route_${instanceId}_${encodedId}`;
2161
+ }
2162
+ function relativePrefix(pattern, parentPattern) {
2163
+ const own = pattern === "/" ? "" : pattern;
2164
+ const parent = parentPattern === "/" ? "" : parentPattern;
2165
+ if (!own.startsWith(parent)) {
2166
+ throw new Error(`[furin] Route pattern "${pattern}" does not extend its layout's "${parentPattern}".`);
2167
+ }
2168
+ return own.slice(parent.length);
2169
+ }
2170
+ function buildRouteTree(instance, instanceId) {
2171
+ const { routes } = scanRouteManifest(instance);
2172
+ const byPath = new Map(routes.map((route) => [route.sourcePath, route]));
2173
+ const root = { children: [], layout: undefined, pages: [], prefix: "" };
2174
+ const nodes = new Map([[undefined, root]]);
2175
+ const parentPattern = (route) => route.parentPath === undefined ? "/" : byPath.get(route.parentPath)?.pattern ?? "/";
2176
+ const ensureNode = (sourcePath) => {
2177
+ const existing = nodes.get(sourcePath);
1983
2178
  if (existing) {
1984
2179
  return existing;
1985
2180
  }
2181
+ const layout = sourcePath === undefined ? undefined : byPath.get(sourcePath);
2182
+ if (!layout) {
2183
+ return root;
2184
+ }
2185
+ const prefix = relativePrefix(layout.pattern, parentPattern(layout));
1986
2186
  const node = {
1987
2187
  children: [],
1988
- fileRoutes: [],
1989
- indexRoute: undefined,
1990
- layout: undefined,
1991
- name: segments.at(-1) ?? ""
2188
+ layout: {
2189
+ id: routeId(instanceId, layout.id),
2190
+ path: "",
2191
+ prefix,
2192
+ sourcePath: resolve(layout.sourcePath)
2193
+ },
2194
+ pages: [],
2195
+ prefix
1992
2196
  };
1993
- nodes.set(key, node);
1994
- if (segments.length > 0) {
1995
- ensureNode(segments.slice(0, -1)).children.push(node);
1996
- }
2197
+ nodes.set(sourcePath, node);
2198
+ ensureNode(layout.parentPath).children.push(node);
1997
2199
  return node;
1998
2200
  };
1999
- const root = ensureNode([]);
2000
- for (const file of scanRouteManifest(pagesDir)) {
2001
- const node = ensureNode(file.directorySegments);
2002
- if (file.pattern === undefined) {
2003
- const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
2004
- node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
2201
+ for (const route of routes) {
2202
+ if (route.kind === "layout") {
2203
+ ensureNode(route.sourcePath);
2005
2204
  continue;
2006
2205
  }
2007
- const route = {
2008
- id: routeId(instanceId, file.pattern),
2009
- path: file.pattern,
2010
- sourcePath: file.sourcePath
2011
- };
2012
- if (file.base === "index") {
2013
- node.indexRoute = route;
2014
- } else {
2015
- node.fileRoutes.push(route);
2016
- }
2206
+ ensureNode(route.parentPath).pages.push({
2207
+ id: routeId(instanceId, route.id),
2208
+ path: route.pattern,
2209
+ prefix: relativePrefix(route.pattern, parentPattern(route)),
2210
+ sourcePath: resolve(route.sourcePath)
2211
+ });
2017
2212
  }
2018
2213
  return root;
2019
2214
  }
@@ -2028,17 +2223,13 @@ function collectRouteFiles(root) {
2028
2223
  if (node.layout) {
2029
2224
  files.push(node.layout);
2030
2225
  }
2031
- if (node.indexRoute) {
2032
- files.push(node.indexRoute);
2033
- }
2034
- files.push(...node.fileRoutes);
2226
+ files.push(...node.pages);
2035
2227
  nodes.push(...node.children);
2036
2228
  }
2037
2229
  return files;
2038
2230
  }
2039
2231
  function routeSourcePaths(instance) {
2040
- const instanceId = Bun.hash(instanceKey(instance)).toString(16);
2041
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve(sourcePath)).toSorted((left, right) => left.localeCompare(right));
2232
+ return scanRouteManifest(instance).routes.map(({ sourcePath }) => resolve(sourcePath)).toSorted((left, right) => left.localeCompare(right));
2042
2233
  }
2043
2234
 
2044
2235
  // src/plugin/route-registry.ts
@@ -2061,15 +2252,10 @@ function instanceNamespace(instance) {
2061
2252
  }
2062
2253
  function emitRouteNode(node, indentation, includeRootCatchAll) {
2063
2254
  const childIndentation = `${indentation} `;
2064
- const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
2065
- const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
2255
+ const head = `new Elysia({ prefix: ${JSON.stringify(node.prefix)} })`;
2066
2256
  const content = [];
2067
- if (node.indexRoute) {
2068
- content.push(`${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`);
2069
- }
2070
- for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
2071
- const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
2072
- content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`);
2257
+ for (const route of node.pages.filter((file) => includeRootCatchAll || file.path !== "/*")) {
2258
+ content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(route.prefix)} }).use(${route.id}.elysia))`);
2073
2259
  }
2074
2260
  for (const child of node.children) {
2075
2261
  content.push(`${childIndentation}.use(`);
@@ -2099,11 +2285,8 @@ async function retainComposableRoutes(node) {
2099
2285
  if (node.layout && !await isComposable(node.layout)) {
2100
2286
  node.layout = undefined;
2101
2287
  }
2102
- if (node.indexRoute && !await isComposable(node.indexRoute)) {
2103
- node.indexRoute = undefined;
2104
- }
2105
- const composableRoutes = (await Promise.all(node.fileRoutes.map(async (route) => ({ keep: await isComposable(route), route })))).flatMap(({ keep, route }) => keep ? [route] : []);
2106
- node.fileRoutes = composableRoutes;
2288
+ const composableRoutes = (await Promise.all(node.pages.map(async (route) => ({ keep: await isComposable(route), route })))).flatMap(({ keep, route }) => keep ? [route] : []);
2289
+ node.pages = composableRoutes;
2107
2290
  await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
2108
2291
  }
2109
2292
  async function generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll) {
@@ -2114,7 +2297,7 @@ async function generateServerInstance(instance, routeFilesBySpecifier, materiali
2114
2297
  return includeRootCatchAll ? instance.routeRegistry.complete : instance.routeRegistry.composable;
2115
2298
  }
2116
2299
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
2117
- const tree = buildRouteTree(instance.pagesDir, instanceId);
2300
+ const tree = buildRouteTree(instance, instanceId);
2118
2301
  await retainComposableRoutes(tree);
2119
2302
  const imports = collectRouteFiles(tree).sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)).map((route) => {
2120
2303
  const specifier = materialized ? resolve2(route.sourcePath).replaceAll("\\", "/") : routeFileSpecifier(route);
@@ -2158,7 +2341,7 @@ async function clientRoutesSource(instance) {
2158
2341
  if (instance.routeRegistry) {
2159
2342
  return instance.routeRegistry.client;
2160
2343
  }
2161
- const tree = buildRouteTree(instance.pagesDir, Bun.hash(instanceKey(instance)).toString(16));
2344
+ const tree = buildRouteTree(instance, Bun.hash(instanceKey(instance)).toString(16));
2162
2345
  const routes = collectRouteFiles(tree).filter((route) => route.path !== "").sort((left, right) => left.path.localeCompare(right.path));
2163
2346
  const metadata = await Promise.all(routes.map(async (routeFile) => {
2164
2347
  const module = await loadRouteModule(routeFile.sourcePath);
@@ -2188,8 +2371,8 @@ function serverProxySource(instance, includeRootCatchAll) {
2188
2371
  function createRoutesPlugin(options) {
2189
2372
  const routeFilesBySpecifier = new Map;
2190
2373
  const routeFilesByResolvedPath = new Map;
2191
- const registryVirtualPath = join6(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
2192
- const composableRegistryVirtualPath = join6(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
2374
+ const registryVirtualPath = join5(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
2375
+ const composableRegistryVirtualPath = join5(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
2193
2376
  const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
2194
2377
  [
2195
2378
  routeModuleSpecifier(instance),
@@ -2272,11 +2455,11 @@ async function materializeServerAppEntry(options) {
2272
2455
  if (!instance) {
2273
2456
  throw new Error(`[furin] Missing route instance for server app ${index}.`);
2274
2457
  }
2275
- const routePath = join7(options.outDir, `_furin-routes-${index}.ts`);
2458
+ const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
2276
2459
  writeFileSync2(routePath, await materializedRouteModuleSource(instance));
2277
2460
  return { ...app, nativeRoutes: toPosixPath(routePath) };
2278
2461
  }));
2279
- const entryPath = join7(options.outDir, "_furin-app.ts");
2462
+ const entryPath = join6(options.outDir, "_furin-app.ts");
2280
2463
  writeFileSync2(entryPath, buildEntrySource({
2281
2464
  apps,
2282
2465
  headerComment: options.headerComment,
@@ -2289,7 +2472,7 @@ async function materializeServerAppEntry(options) {
2289
2472
 
2290
2473
  // src/rsc/build/index.ts
2291
2474
  import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
2292
- import { basename as basename2, join as join9 } from "path";
2475
+ import { basename as basename2, join as join8 } from "path";
2293
2476
  import { fileURLToPath as fileURLToPath5 } from "url";
2294
2477
  // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/aliases.js
2295
2478
  var ALIAS_GROUPS = {
@@ -4813,9 +4996,9 @@ var MagicString = class MagicString {
4813
4996
  };
4814
4997
 
4815
4998
  // src/shared/parser.ts
4816
- import { parse as parse2 } from "yuku-parser";
4999
+ import { parse } from "yuku-parser";
4817
5000
  function parseSource(code, lang) {
4818
- return parse2(code, { lang, sourceType: "module" });
5001
+ return parse(code, { lang, sourceType: "module" });
4819
5002
  }
4820
5003
 
4821
5004
  // src/plugin/module-transform.ts
@@ -5687,7 +5870,7 @@ import { dirname as dirname8 } from "path";
5687
5870
  var A;
5688
5871
  var B = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
5689
5872
  var Q = typeof Buffer != "undefined";
5690
- function parse3(g, C = "@") {
5873
+ function parse2(g, C = "@") {
5691
5874
  A || initSync();
5692
5875
  const G = g.length + 1, D = (A.__heap_base.value || A.__heap_base) + 4 * G - A.memory.buffer.byteLength;
5693
5876
  D > 0 && A.memory.grow(Math.ceil(D / 65536));
@@ -5866,11 +6049,11 @@ function initSync() {
5866
6049
  import { readFileSync as readFileSync2 } from "fs";
5867
6050
 
5868
6051
  // src/rsc/build/paths.ts
5869
- import { dirname as dirname7, join as join8 } from "path";
6052
+ import { dirname as dirname7, join as join7 } from "path";
5870
6053
  import { fileURLToPath as fileURLToPath3 } from "url";
5871
6054
  var SOURCE_DIR = dirname7(fileURLToPath3(import.meta.resolve("@teyik0/furin/rsc")));
5872
- var CLIENT_REFERENCE_RUNTIME_PATH = join8(SOURCE_DIR, "rsc/client-references.ts");
5873
- var BUNDLED_CLIENT_CODEC_PATH = join8(SOURCE_DIR, "rsc/bundled-client-codec.ts");
6055
+ var CLIENT_REFERENCE_RUNTIME_PATH = join7(SOURCE_DIR, "rsc/client-references.ts");
6056
+ var BUNDLED_CLIENT_CODEC_PATH = join7(SOURCE_DIR, "rsc/bundled-client-codec.ts");
5874
6057
 
5875
6058
  // src/rsc/build/flight-loader.ts
5876
6059
  var CLIENT_CODEC = /react-server-dom-webpack-client\.(?:edge|browser)\.(?:development|production)\.js$/;
@@ -6022,7 +6205,7 @@ function commonJsExports(source, path) {
6022
6205
  withoutImports.remove(statement.start, statement.end);
6023
6206
  }
6024
6207
  }
6025
- return parse3(withoutImports.toString());
6208
+ return parse2(withoutImports.toString());
6026
6209
  }
6027
6210
  async function exportedNames(source, path, visited) {
6028
6211
  if (visited.has(path)) {
@@ -6151,7 +6334,7 @@ ${codecResult.logs.map((log) => log.message).join(`
6151
6334
  }
6152
6335
  async function buildRscGraph(apps, outDir, buildId, userPlugins, external) {
6153
6336
  await assertInstalledRscVersions();
6154
- const graphDir = join9(outDir, "rsc");
6337
+ const graphDir = join8(outDir, "rsc");
6155
6338
  mkdirSync2(graphDir, { recursive: true });
6156
6339
  const rscEntry = fileURLToPath5(import.meta.resolve("../../rsc-server.tsx"));
6157
6340
  const entrypoints = [
@@ -6205,13 +6388,13 @@ ${result.logs.map((log) => log.message).join(`
6205
6388
  clientReferences: referencedClientExports(clientReferences, result.metafile),
6206
6389
  css
6207
6390
  };
6208
- writeFileSync3(join9(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
6391
+ writeFileSync3(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
6209
6392
  return manifest;
6210
6393
  }
6211
6394
 
6212
6395
  // src/adapter/prerender.ts
6213
6396
  import { readFileSync as readFileSync3, rmSync as rmSync2 } from "fs";
6214
- import { join as join10 } from "path";
6397
+ import { join as join9 } from "path";
6215
6398
  import { pathToFileURL as pathToFileURL2 } from "url";
6216
6399
  function prerenderScript(module, render, resultPath) {
6217
6400
  const href = JSON.stringify(pathToFileURL2(module.path).href);
@@ -6230,7 +6413,7 @@ process.exit(0);
6230
6413
  `;
6231
6414
  }
6232
6415
  async function runBundleScript(script, cwd, failure) {
6233
- const resultPath = join10(cwd, ".furin", "build", `prerender-${crypto.randomUUID()}.json`);
6416
+ const resultPath = join9(cwd, ".furin", "build", `prerender-${crypto.randomUUID()}.json`);
6234
6417
  const child = Bun.spawn([process.execPath, "-e", script(resultPath)], {
6235
6418
  cwd,
6236
6419
  env: { ...process.env, NODE_ENV: "production" },
@@ -6263,12 +6446,12 @@ function exportStaticFromBundle(path, cwd, options) {
6263
6446
  // src/adapter/runtime-build.ts
6264
6447
  import { existsSync as existsSync10, realpathSync as realpathSync4, writeFileSync as writeFileSync6 } from "fs";
6265
6448
  import { createRequire } from "module";
6266
- import { dirname as dirname12, isAbsolute as isAbsolute5, join as join13, relative as relative6, resolve as resolve7 } from "path";
6449
+ import { dirname as dirname12, isAbsolute as isAbsolute5, join as join12, relative as relative5, resolve as resolve7 } from "path";
6267
6450
  import { fileURLToPath as fileURLToPath7 } from "url";
6268
6451
 
6269
6452
  // src/build/client.ts
6270
6453
  import { existsSync as existsSync9, mkdirSync as mkdirSync3 } from "fs";
6271
- import { basename as basename4, dirname as dirname11, join as join12, sep as sep2 } from "path";
6454
+ import { basename as basename4, dirname as dirname11, join as join11, sep as sep2 } from "path";
6272
6455
  import { fileURLToPath as fileURLToPath6 } from "url";
6273
6456
 
6274
6457
  // src/plugin/client-plugin.ts
@@ -7430,7 +7613,7 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
7430
7613
 
7431
7614
  // src/build/route-types.ts
7432
7615
  import { existsSync as existsSync7, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
7433
- import { extname as extname2, join as join11, relative as relative5, resolve as resolve5 } from "path";
7616
+ import { extname as extname2, join as join10, relative as relative4, resolve as resolve5 } from "path";
7434
7617
 
7435
7618
  // src/shared/route-map.ts
7436
7619
  function compareCodeUnits(left, right) {
@@ -7469,38 +7652,19 @@ function tagToStringLiteral(tag) {
7469
7652
  function importSpecifier(path, projectRoot) {
7470
7653
  const extension = extname2(path);
7471
7654
  const sourcePath = extension ? path.slice(0, -extension.length) : path;
7472
- const relativePath = relative5(projectRoot, sourcePath).replaceAll("\\", "/");
7655
+ const relativePath = relative4(projectRoot, sourcePath).replaceAll("\\", "/");
7473
7656
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
7474
7657
  }
7475
- function fileRouteEntries({ pagesDir, prefix }, projectRoot) {
7476
- const pages = resolve5(pagesDir);
7477
- const files = routeSourcePaths({ pagesDir: pages, prefix }).map((path) => {
7478
- const relativePath = relative5(pages, path).replaceAll("\\", "/");
7479
- const segments = relativePath.split("/");
7480
- const base = (segments.pop() ?? "").slice(0, -extname2(path).length);
7481
- return { base, path, relativePath, segments };
7482
- });
7483
- const layouts = new Map(files.filter(({ base }) => base === "_route").map((file) => [file.segments.join("/"), file.path]));
7484
- return files.map(({ base, path, relativePath, segments }) => {
7485
- const isLayout = base === "_route";
7486
- let parent = join11(pages, "root.tsx");
7487
- for (let depth = isLayout ? segments.length - 1 : segments.length;depth > 0; depth -= 1) {
7488
- const layout = layouts.get(segments.slice(0, depth).join("/"));
7489
- if (layout) {
7490
- parent = layout;
7491
- break;
7492
- }
7493
- }
7494
- const pathParams = [...segments, base].flatMap((segment) => {
7495
- const dynamic = parseDynamicRouteSegment(segment, path);
7496
- return dynamic ? [dynamic.catchAll ? '"*": string' : `${dynamic.name}: string`] : [];
7497
- });
7498
- const id = fileRouteId({ pagesDir: pages, prefix }, path);
7499
- const pattern = filePathToPattern(isLayout ? segments.concat("index").join("/") : relativePath);
7658
+ function fileRouteEntries(instance, projectRoot) {
7659
+ const { prefix } = instance;
7660
+ const manifest = scanRouteManifest({ ...instance, pagesDir: resolve5(instance.pagesDir) });
7661
+ return manifest.routes.map(({ id, kind, params, parentPath, pattern }) => {
7662
+ const parent = parentPath ?? manifest.rootPath;
7663
+ const pathParams = params.map(({ name, optional }) => `${name}${optional ? "?" : ""}: string`);
7500
7664
  return {
7501
7665
  id,
7502
7666
  lines: ` ${JSON.stringify(id)}: {
7503
- kind: "${isLayout ? "layout" : "page"}";
7667
+ kind: "${kind}";
7504
7668
  pattern: ${JSON.stringify(`${prefix}${pattern === "/" ? "" : pattern}` || "/")};
7505
7669
  parent: typeof import(${JSON.stringify(importSpecifier(parent, projectRoot))}).route;
7506
7670
  pathParams: {${pathParams.length > 0 ? ` ${pathParams.join("; ")} ` : ""}};
@@ -7539,7 +7703,7 @@ import "@teyik0/furin/routes";
7539
7703
 
7540
7704
  ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapDeclaration(entries)}${tagBlock}
7541
7705
  `;
7542
- const typesPath = join11(projectRoot, "furin-env.d.ts");
7706
+ const typesPath = join10(projectRoot, "furin-env.d.ts");
7543
7707
  const existing = existsSync7(typesPath) ? readFileSync5(typesPath, "utf8") : "";
7544
7708
  if (content === existing) {
7545
7709
  return false;
@@ -7602,11 +7766,13 @@ function hydrateEntry(routes, rootLayout, basePath, clientLogging, modulePathKey
7602
7766
  continue;
7603
7767
  }
7604
7768
  const parts = [`depth: ${seg.depth}`];
7769
+ const errorExport = seg.fromRoute ? "route.errorComponent" : "default";
7770
+ const notFoundExport = seg.fromRoute ? "route.notFoundComponent" : "default";
7605
7771
  if (errorIdent) {
7606
- parts.push(`error: ${errorIdent}.default`);
7772
+ parts.push(`error: ${errorIdent}.${errorExport}`);
7607
7773
  }
7608
7774
  if (notFoundIdent) {
7609
- parts.push(`notFound: ${notFoundIdent}.default`);
7775
+ parts.push(`notFound: ${notFoundIdent}.${notFoundExport}`);
7610
7776
  }
7611
7777
  if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
7612
7778
  parts.push("isRoot: false");
@@ -8001,7 +8167,7 @@ function writeClientPreloadManifest(metafile, outputPaths, entryChunkPath, route
8001
8167
  }
8002
8168
 
8003
8169
  // src/build/client.ts
8004
- var CLIENT_DIST_DIR = `${join12(dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin")))), "dist")}${sep2}`;
8170
+ var CLIENT_DIST_DIR = `${join11(dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin")))), "dist")}${sep2}`;
8005
8171
  async function buildClient(routes, {
8006
8172
  outDir,
8007
8173
  rootLayout,
@@ -8014,11 +8180,11 @@ async function buildClient(routes, {
8014
8180
  metafilePath,
8015
8181
  optimizeImports,
8016
8182
  reactCompiler,
8017
- pagesDir,
8183
+ pages,
8018
8184
  routeRegistry
8019
8185
  }) {
8020
8186
  const dirName = clientDirName ?? "client";
8021
- const clientDir = join12(outDir, dirName);
8187
+ const clientDir = join11(outDir, dirName);
8022
8188
  if (!existsSync9(outDir)) {
8023
8189
  mkdirSync3(outDir, { recursive: true });
8024
8190
  }
@@ -8027,7 +8193,7 @@ async function buildClient(routes, {
8027
8193
  }
8028
8194
  const boundaries = await discoverClientBoundaries([...new Set([rootLayout, ...routes.flatMap((route) => [route.path, ...route.routeChain.flatMap((entry) => entry.sourcePath ? [entry.sourcePath] : [])])])], plugins);
8029
8195
  const hydrateCode = generateClientReferenceEntry(boundaries) + generateProductionHydrateEntry(routes, rootLayout, basePath, clientLogging);
8030
- const hydratePath = join12(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8196
+ const hydratePath = join11(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8031
8197
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8032
8198
  console.log("[furin] Building production client bundle\u2026");
8033
8199
  const routerLoggerPlugin = {
@@ -8067,7 +8233,7 @@ async function buildClient(routes, {
8067
8233
  hydrateEntry.plugin,
8068
8234
  ...plugins ?? [],
8069
8235
  ...!clientLogging ? [routerLoggerPlugin] : [],
8070
- ...pagesDir ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath, routeRegistry }], target: "client" })] : [],
8236
+ ...pages ? [createRoutesPlugin({ instances: [{ ...pages, prefix: basePath, routeRegistry }], target: "client" })] : [],
8071
8237
  createClientStripPlugin({ mode: "build" })
8072
8238
  ],
8073
8239
  define: {
@@ -8105,10 +8271,10 @@ async function buildClient(routes, {
8105
8271
 
8106
8272
  // src/adapter/runtime-build.ts
8107
8273
  var _pkgRoot2 = dirname12(dirname12(fileURLToPath7(import.meta.resolve("@teyik0/furin"))));
8108
- var _pkgSrcDir2 = existsSync10(join13(_pkgRoot2, "src", "furin.ts")) ? join13(_pkgRoot2, "src") : join13(_pkgRoot2, "dist");
8274
+ var _pkgSrcDir2 = existsSync10(join12(_pkgRoot2, "src", "furin.ts")) ? join12(_pkgRoot2, "src") : join12(_pkgRoot2, "dist");
8109
8275
  var _ext2 = ".ts";
8110
8276
  function frameworkSourceModule(path) {
8111
- return join13(_pkgRoot2, "src", path);
8277
+ return join12(_pkgRoot2, "src", path);
8112
8278
  }
8113
8279
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
8114
8280
  var MIXED_CACHE_IMPORT_RE = /mixed-cache(?:\.ts)?$/;
@@ -8161,7 +8327,7 @@ function nearestFingerprintFile(directory, names, boundary) {
8161
8327
  let current = directory;
8162
8328
  while (current !== undefined) {
8163
8329
  for (const name of names) {
8164
- const path = join13(current, name);
8330
+ const path = join12(current, name);
8165
8331
  if (existsSync10(path)) {
8166
8332
  return path;
8167
8333
  }
@@ -8219,7 +8385,7 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
8219
8385
  if (!isScript) {
8220
8386
  return;
8221
8387
  }
8222
- const relativePath = toPosixPath(relative6(rootBoundary, path));
8388
+ const relativePath = toPosixPath(relative5(rootBoundary, path));
8223
8389
  const manifestBoundary = relativePath === ".." || relativePath.startsWith("../") || isAbsolute5(relativePath) ? undefined : rootBoundary;
8224
8390
  const manifest = nearestFingerprintFile(dirname12(path), ["package.json"], manifestBoundary);
8225
8391
  if (manifest) {
@@ -8268,11 +8434,11 @@ function stableFingerprintPath(path, projectRoot) {
8268
8434
  if (dependencyStart !== -1) {
8269
8435
  return `dependency/${posixPath.slice(dependencyStart + "/node_modules/".length)}`;
8270
8436
  }
8271
- const projectPath = relative6(realpathSync4(projectRoot), absolutePath);
8437
+ const projectPath = relative5(realpathSync4(projectRoot), absolutePath);
8272
8438
  if (!isAbsolute5(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
8273
8439
  return `app/${toPosixPath(projectPath)}`;
8274
8440
  }
8275
- const frameworkPath = relative6(_pkgRoot2, absolutePath);
8441
+ const frameworkPath = relative5(_pkgRoot2, absolutePath);
8276
8442
  if (!isAbsolute5(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
8277
8443
  return `furin/${toPosixPath(frameworkPath)}`;
8278
8444
  }
@@ -8286,11 +8452,13 @@ function buildCompileMetadata(root, routes) {
8286
8452
  const routeMetadata = {};
8287
8453
  for (const route of routes) {
8288
8454
  routeMetadata[toPosixPath(route.path)] = {
8455
+ layouts: route.layouts.map((layout) => ({ ...layout, path: toPosixPath(layout.path) })),
8289
8456
  requestKeys: route.requestKeys,
8290
8457
  requestKeysByLoader: route.requestKeysByLoader,
8291
8458
  segmentBoundaries: route.segmentBoundaries.map((boundary) => ({
8292
8459
  depth: boundary.depth,
8293
8460
  errorPath: boundary.errorPath ? toPosixPath(boundary.errorPath) : undefined,
8461
+ ...boundary.fromRoute ? { fromRoute: boundary.fromRoute } : {},
8294
8462
  notFoundPath: boundary.notFoundPath ? toPosixPath(boundary.notFoundPath) : undefined,
8295
8463
  path: toPosixPath(boundary.path)
8296
8464
  }))
@@ -8356,7 +8524,7 @@ function isFrameworkRuntimeImporter(importer) {
8356
8524
  if (importer === "") {
8357
8525
  return false;
8358
8526
  }
8359
- const fromRuntimeRoot = relative6(_pkgSrcDir2, importer.split("?")[0]);
8527
+ const fromRuntimeRoot = relative5(_pkgSrcDir2, importer.split("?")[0]);
8360
8528
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
8361
8529
  }
8362
8530
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -8368,10 +8536,10 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
8368
8536
  basePath: prefix,
8369
8537
  clientDirName,
8370
8538
  clientLogging: options.clientLogging ?? false,
8371
- metafilePath: options.analyze ? join13(dirname12(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
8539
+ metafilePath: options.analyze ? join12(dirname12(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
8372
8540
  optimizeImports: options.optimizeImports,
8373
8541
  outDir: targetDir,
8374
- pagesDir: app.pagesDir,
8542
+ pages: { pagesDir: app.pagesDir, style: app.style },
8375
8543
  routeRegistry: app.routeRegistry,
8376
8544
  plugins: options.plugins,
8377
8545
  preloadRouteChunks: options.preload?.routeChunks,
@@ -8382,9 +8550,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
8382
8550
  const buildFingerprint = await createBuildFingerprint(`${prefix}
8383
8551
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
8384
8552
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
8385
- const clientDir = join13(targetDir, clientDirName);
8553
+ const clientDir = join12(targetDir, clientDirName);
8386
8554
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
8387
- writeFileSync6(join13(clientDir, "index.html"), indexHtml);
8555
+ writeFileSync6(join12(clientDir, "index.html"), indexHtml);
8388
8556
  const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
8389
8557
  console.log(`[furin] Built ${label} (buildId ${buildId})`);
8390
8558
  return {
@@ -8411,16 +8579,16 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
8411
8579
  }
8412
8580
 
8413
8581
  // src/adapter/server-bundle.ts
8414
- import { dirname as dirname15, relative as relative9 } from "path";
8582
+ import { dirname as dirname15, relative as relative8 } from "path";
8415
8583
 
8416
8584
  // src/build/elysia-aot.ts
8417
8585
  import { fork } from "child_process";
8418
8586
  import { existsSync as existsSync11, realpathSync as realpathSync5 } from "fs";
8419
- import { dirname as dirname13, join as join14, relative as relative7, resolve as resolve8 } from "path";
8587
+ import { dirname as dirname13, join as join13, relative as relative6, resolve as resolve8 } from "path";
8420
8588
  import { fileURLToPath as fileURLToPath8 } from "url";
8421
8589
  var AOT_NAMESPACE = "furin-elysia-aot";
8422
8590
  var ELYSIA_RESOLVE_DIR = dirname13(Bun.resolveSync("elysia", import.meta.dir));
8423
- var AOT_PROCESS_PATH = join14(dirname13(dirname13(fileURLToPath8(import.meta.resolve("@teyik0/furin")))), "src/build/elysia-aot-worker.ts");
8591
+ var AOT_PROCESS_PATH = join13(dirname13(dirname13(fileURLToPath8(import.meta.resolve("@teyik0/furin")))), "src/build/elysia-aot-worker.ts");
8424
8592
  var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
8425
8593
  var ELYSIA_IMPORT_FILTER = /^elysia(?:\/(?!compiled$|type$).*)?$/;
8426
8594
  var ELYSIA_VIRTUAL_IMPORT_FILTER = /^elysia\/(?:compiled|type)$/;
@@ -8450,10 +8618,10 @@ export function drainWaiters(){return e()}
8450
8618
  export function handleWSResponse(){return e()}
8451
8619
  `;
8452
8620
  }
8453
- function mountLabel(rootDir, { pagesDir, prefix }) {
8621
+ function mountLabel(rootDir, { pagesDir, prefix, style }) {
8454
8622
  const absolute = resolve8(rootDir, pagesDir);
8455
8623
  const path = existsSync11(absolute) ? realpathSync5(absolute) : absolute;
8456
- return `prefix ${JSON.stringify(prefix || "/")} (pagesDir ${relative7(rootDir, path) || "."})`;
8624
+ return `prefix ${JSON.stringify(prefix || "/")} (pagesDir ${relative6(rootDir, path) || "."}, style ${style})`;
8457
8625
  }
8458
8626
  function registrationMismatch(build, registrations, evaluated) {
8459
8627
  const root = realpathSync5(build.rootDir);
@@ -8614,7 +8782,7 @@ function elysiaAot(entry, expected) {
8614
8782
  }
8615
8783
 
8616
8784
  // src/build/production-instrumentation.ts
8617
- import { dirname as dirname14, relative as relative8, resolve as resolve9 } from "path";
8785
+ import { dirname as dirname14, relative as relative7, resolve as resolve9 } from "path";
8618
8786
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
8619
8787
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
8620
8788
  var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin|runtime)(?:\.ts|\.js)?$/;
@@ -8624,7 +8792,7 @@ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plu
8624
8792
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
8625
8793
  var FURIN_RUNTIME_ROOT = resolve9(import.meta.dir, "..");
8626
8794
  function isFurinRuntimePath(path) {
8627
- const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT, path);
8795
+ const fromRuntimeRoot = relative7(FURIN_RUNTIME_ROOT, path);
8628
8796
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
8629
8797
  }
8630
8798
  function devBuildExports(path) {
@@ -8682,7 +8850,7 @@ function isFurinRuntimeImporter(importer) {
8682
8850
  if (importer === "") {
8683
8851
  return false;
8684
8852
  }
8685
- const fromRuntimeRoot = relative9(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
8853
+ const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
8686
8854
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
8687
8855
  }
8688
8856
  function appSpecifierPlugin(appEntry) {
@@ -8776,10 +8944,10 @@ function withAssetContexts(adapter, builds, targetDir) {
8776
8944
  return prepareCompileEntryApps({
8777
8945
  apps: contexts.map((context) => ({
8778
8946
  ...context,
8779
- embed: { clientDir: join15(targetDir, clientDirNameForPrefix(context.prefix ?? "")) }
8947
+ embed: { clientDir: join14(targetDir, clientDirNameForPrefix(context.prefix ?? "")) }
8780
8948
  })),
8781
8949
  outDir: targetDir,
8782
- publicDir: join15(targetDir, "public")
8950
+ publicDir: join14(targetDir, "public")
8783
8951
  });
8784
8952
  }
8785
8953
  function adapterRoute(app, route) {
@@ -8823,22 +8991,22 @@ async function bundleServer(adapter, apps, appEntry, clientReferences, rootDir,
8823
8991
  if (build.metafile === undefined) {
8824
8992
  throw new Error(`[furin] The ${adapter.name} server build did not produce its metafile.`);
8825
8993
  }
8826
- writeBuildMetafile(join15(buildRoot, "analysis", `${adapter.name}-server.json`), build.metafile, "Server");
8994
+ writeBuildMetafile(join14(buildRoot, "analysis", `${adapter.name}-server.json`), build.metafile, "Server");
8827
8995
  }
8828
8996
  return {
8829
8997
  dir: targetDir,
8830
8998
  entry: `${basename5(adapter.runtimeModule, extname3(adapter.runtimeModule))}.js`,
8831
- files: build.outputs.filter((output) => output.path.endsWith(".js")).map((output) => toPosixPath(relative10(targetDir, output.path)))
8999
+ files: build.outputs.filter((output) => output.path.endsWith(".js")).map((output) => toPosixPath(relative9(targetDir, output.path)))
8832
9000
  };
8833
9001
  }
8834
9002
  function writePrerenderSnapshot(targetDir, prerenders) {
8835
9003
  const snapshot = Object.fromEntries(prerenders.map(({ prefix, ssg }) => [prefix, ssg]));
8836
- writeFileSync7(join15(targetDir, PRERENDER_SNAPSHOT_FILE), `${JSON.stringify(snapshot)}
9004
+ writeFileSync7(join14(targetDir, PRERENDER_SNAPSHOT_FILE), `${JSON.stringify(snapshot)}
8837
9005
  `);
8838
9006
  }
8839
9007
  async function buildAdapterTarget(adapter, apps, rootDir, buildRoot, serverEntry, options) {
8840
9008
  assertServerEntry(serverEntry, adapter);
8841
- const targetDir = join15(buildRoot, adapter.name);
9009
+ const targetDir = join14(buildRoot, adapter.name);
8842
9010
  rmSync3(targetDir, { force: true, recursive: true });
8843
9011
  rmSync3(privateServerSourceMapDir(buildRoot, adapter.name), {
8844
9012
  force: true,
@@ -8849,10 +9017,10 @@ async function buildAdapterTarget(adapter, apps, rootDir, buildRoot, serverEntry
8849
9017
  const rootIndex = apps.findIndex((app) => app.prefix === "");
8850
9018
  const { buildId } = builds[rootIndex === -1 ? 0 : rootIndex];
8851
9019
  const rscManifest = await buildRscGraph(apps, targetDir, buildId, options.plugins, options.serverExternalPackages);
8852
- const projectPublicDir = join15(rootDir, "public");
9020
+ const projectPublicDir = join14(rootDir, "public");
8853
9021
  const publicDir = existsSync12(projectPublicDir) ? projectPublicDir : undefined;
8854
9022
  if (publicDir !== undefined && adapter.capabilities.assets !== "platform") {
8855
- copyDirRecursive(publicDir, join15(targetDir, "public"));
9023
+ copyDirRecursive(publicDir, join14(targetDir, "public"));
8856
9024
  }
8857
9025
  const frameworkCache = adapter.capabilities.publicCache === "framework";
8858
9026
  const appEntry = await materializeServerAppEntry({
@@ -8871,7 +9039,7 @@ async function buildAdapterTarget(adapter, apps, rootDir, buildRoot, serverEntry
8871
9039
  const info = routeBuildInfo(route);
8872
9040
  return info.documentMode !== "ssr" && (info.queryKeys?.length ?? 0) === 0;
8873
9041
  }));
8874
- const prerenders = needsPrerender ? await prerenderFromBundle({ kind: "app", path: join15(targetDir, APP_MODULE) }, rootDir, frameworkCache) : [];
9042
+ const prerenders = needsPrerender ? await prerenderFromBundle({ kind: "app", path: join14(targetDir, APP_MODULE) }, rootDir, frameworkCache) : [];
8875
9043
  if (frameworkCache) {
8876
9044
  writePrerenderSnapshot(targetDir, prerenders);
8877
9045
  }
@@ -8895,7 +9063,7 @@ async function buildAdapterTarget(adapter, apps, rootDir, buildRoot, serverEntry
8895
9063
 
8896
9064
  // src/adapter/bun.ts
8897
9065
  import { existsSync as existsSync13, rmSync as rmSync4 } from "fs";
8898
- import { join as join16, relative as relative11 } from "path";
9066
+ import { join as join15, relative as relative10 } from "path";
8899
9067
  var RUNTIME_MODULE = frameworkSourceModule("adapter/bun/server.ts");
8900
9068
  var APP_RUNTIME_MODULE = frameworkSourceModule("adapter/bun/app.ts");
8901
9069
  function compiledServerFilename(platform) {
@@ -8904,12 +9072,12 @@ function compiledServerFilename(platform) {
8904
9072
  async function compileExecutable(output, compile, manifest) {
8905
9073
  const { apps, buildRoot, server } = output;
8906
9074
  const filename = compiledServerFilename(process.platform);
8907
- const publicDir = join16(server.dir, "public");
9075
+ const publicDir = join15(server.dir, "public");
8908
9076
  const embedded = compile === "embed" ? [...apps.map((app) => app.clientDir), ...existsSync13(publicDir) ? [publicDir] : []] : undefined;
8909
9077
  const build = await runBunBuild({
8910
9078
  bytecode: true,
8911
- compile: { assets: embedded, outfile: join16(server.dir, filename) },
8912
- entrypoints: [join16(server.dir, server.entry)],
9079
+ compile: { assets: embedded, outfile: join15(server.dir, filename) },
9080
+ entrypoints: [join15(server.dir, server.entry)],
8913
9081
  format: "esm",
8914
9082
  minify: true,
8915
9083
  sourcemap: output.serverSourceMaps ? "external" : "none",
@@ -8920,13 +9088,13 @@ async function compileExecutable(output, compile, manifest) {
8920
9088
  movePrivateServerSourceMaps(server.dir, privateServerSourceMapDir(buildRoot, "bun"), build.outputs.filter((entry) => entry.kind === "sourcemap").map((entry) => entry.path));
8921
9089
  }
8922
9090
  for (const file of [...server.files, PRERENDER_SNAPSHOT_FILE]) {
8923
- rmSync4(join16(server.dir, file), { force: true });
9091
+ rmSync4(join15(server.dir, file), { force: true });
8924
9092
  }
8925
- manifest.serverPath = toPosixPath(join16(manifest.targetDir, filename));
8926
- console.log(`[furin] Server binary: ${join16(server.dir, filename)}`);
9093
+ manifest.serverPath = toPosixPath(join15(manifest.targetDir, filename));
9094
+ console.log(`[furin] Server binary: ${join15(server.dir, filename)}`);
8927
9095
  if (compile === "embed") {
8928
9096
  for (const app of apps) {
8929
- rmSync4(join16(server.dir, clientDirNameForPrefix(app.prefix)), {
9097
+ rmSync4(join15(server.dir, clientDirNameForPrefix(app.prefix)), {
8930
9098
  force: true,
8931
9099
  recursive: true
8932
9100
  });
@@ -8949,15 +9117,15 @@ function bun(compile, bunOutput) {
8949
9117
  },
8950
9118
  name: "bun",
8951
9119
  async onBuildComplete(output) {
8952
- const targetDir = toPosixPath(relative11(output.rootDir, output.server.dir));
9120
+ const targetDir = toPosixPath(relative10(output.rootDir, output.server.dir));
8953
9121
  const manifest = {
8954
9122
  buildId: output.buildId,
8955
- clientDir: toPosixPath(join16(targetDir, "client")),
9123
+ clientDir: toPosixPath(join15(targetDir, "client")),
8956
9124
  generatedAt: new Date().toISOString(),
8957
- rscManifestPath: toPosixPath(join16(targetDir, "rsc", "manifest.json")),
8958
- serverPath: toPosixPath(join16(targetDir, output.server.entry)),
9125
+ rscManifestPath: toPosixPath(join15(targetDir, "rsc", "manifest.json")),
9126
+ serverPath: toPosixPath(join15(targetDir, output.server.entry)),
8959
9127
  targetDir,
8960
- templatePath: toPosixPath(join16(targetDir, "client", "index.html"))
9128
+ templatePath: toPosixPath(join15(targetDir, "client", "index.html"))
8961
9129
  };
8962
9130
  if (isApp) {
8963
9131
  manifest.appPath = manifest.serverPath;
@@ -8978,20 +9146,20 @@ function bun(compile, bunOutput) {
8978
9146
 
8979
9147
  // src/adapter/package.ts
8980
9148
  import { existsSync as existsSync14, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
8981
- import { join as join17, relative as relative12, resolve as resolve10 } from "path";
9149
+ import { join as join16, relative as relative11, resolve as resolve10 } from "path";
8982
9150
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
8983
9151
  const { prefix, root, routes, pagesDir } = app;
8984
9152
  const modulePaths = routeSourcePaths(app);
8985
- const targetDir = join17(buildRoot, "package");
9153
+ const targetDir = join16(buildRoot, "package");
8986
9154
  rmSync5(targetDir, { force: true, recursive: true });
8987
9155
  ensureDir(targetDir);
8988
9156
  const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
8989
9157
  basePath: prefix,
8990
9158
  clientLogging: options.clientLogging ?? false,
8991
- metafilePath: options.analyze ? join17(buildRoot, "analysis", "package-client.json") : undefined,
9159
+ metafilePath: options.analyze ? join16(buildRoot, "analysis", "package-client.json") : undefined,
8992
9160
  optimizeImports: options.optimizeImports,
8993
9161
  outDir: targetDir,
8994
- pagesDir,
9162
+ pages: { pagesDir, style: app.style },
8995
9163
  routeRegistry: app.routeRegistry,
8996
9164
  plugins: options.plugins,
8997
9165
  preloadRouteChunks: options.preload?.routeChunks,
@@ -9002,30 +9170,14 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
9002
9170
  const buildFingerprint = await createBuildFingerprint(`${prefix}
9003
9171
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
9004
9172
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
9005
- const clientDir = join17(targetDir, "client");
9006
- const publicDir = join17(rootDir, "public");
9173
+ const clientDir = join16(targetDir, "client");
9174
+ const publicDir = join16(rootDir, "public");
9007
9175
  if (existsSync14(publicDir)) {
9008
- copyDirRecursive(publicDir, join17(targetDir, "public"));
9176
+ copyDirRecursive(publicDir, join16(targetDir, "public"));
9009
9177
  }
9010
9178
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
9011
- writeFileSync8(join17(clientDir, "index.html"), indexHtml);
9012
- const rootConventions = root.errorPath || root.notFoundPath ? {
9013
- errorPath: root.errorPath ? toPosixPath(root.errorPath) : undefined,
9014
- notFoundPath: root.notFoundPath ? toPosixPath(root.notFoundPath) : undefined
9015
- } : undefined;
9016
- const routeMetadata = {};
9017
- for (const route of routes) {
9018
- routeMetadata[toPosixPath(route.path)] = {
9019
- requestKeys: route.requestKeys,
9020
- requestKeysByLoader: route.requestKeysByLoader,
9021
- segmentBoundaries: route.segmentBoundaries.map((b) => ({
9022
- depth: b.depth,
9023
- errorPath: b.errorPath ? toPosixPath(b.errorPath) : undefined,
9024
- notFoundPath: b.notFoundPath ? toPosixPath(b.notFoundPath) : undefined,
9025
- path: toPosixPath(b.path)
9026
- }))
9027
- };
9028
- }
9179
+ writeFileSync8(join16(clientDir, "index.html"), indexHtml);
9180
+ const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
9029
9181
  const registerSource = buildEntrySource({
9030
9182
  apps: [
9031
9183
  {
@@ -9045,7 +9197,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
9045
9197
  mode: "register",
9046
9198
  prerenderSnapshot: true
9047
9199
  });
9048
- const registerEntry = join17(targetDir, "register.ts");
9200
+ const registerEntry = join16(targetDir, "register.ts");
9049
9201
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
9050
9202
  const result = await runBunBuild({
9051
9203
  define: PRODUCTION_DEFINE,
@@ -9072,7 +9224,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
9072
9224
  if (!result.success) {
9073
9225
  throw new AggregateError(result.logs, "[furin] package register build failed");
9074
9226
  }
9075
- const relativePagesDir = toPosixPath(relative12(targetDir, resolve10(rootDir, pagesDir)));
9227
+ const relativePagesDir = toPosixPath(relative11(targetDir, resolve10(rootDir, pagesDir)));
9076
9228
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
9077
9229
  import { fileURLToPath } from "node:url";
9078
9230
  import { furin } from "@teyik0/furin";
@@ -9085,7 +9237,7 @@ const CLIENT_DIR = fileURLToPath(new URL("./client", import.meta.url));
9085
9237
  * Mounts this packaged furin app as an Elysia plugin.
9086
9238
  *
9087
9239
  * @param {object} [options] Extra furin() options (logger, sync, ...) \u2014
9088
- * pagesDir/prefix/clientDir are baked into the package and cannot be overridden.
9240
+ * pagesDir/prefix/style/clientDir are baked into the package and cannot be overridden.
9089
9241
  * @returns {ReturnType<typeof import("@teyik0/furin").furin>}
9090
9242
  */
9091
9243
  export function createFurinApp(options = {}) {
@@ -9093,45 +9245,46 @@ export function createFurinApp(options = {}) {
9093
9245
  ...options,
9094
9246
  pagesDir: PAGES_DIR,
9095
9247
  prefix: ${JSON.stringify(prefix)},
9248
+ style: ${JSON.stringify(app.style)},
9096
9249
  clientDir: CLIENT_DIR,
9097
9250
  });
9098
9251
  }
9099
9252
 
9100
9253
  export const prefix = ${JSON.stringify(prefix)};
9101
9254
  `;
9102
- writeFileSync8(join17(targetDir, "index.js"), factorySource);
9255
+ writeFileSync8(join16(targetDir, "index.js"), factorySource);
9103
9256
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
9104
9257
 
9105
- /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
9106
- export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "clientDir">;
9258
+ /** Extra furin() options \u2014 pagesDir/prefix/style/clientDir are baked into the package and cannot be overridden. */
9259
+ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "style" | "clientDir">;
9107
9260
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
9108
9261
  export declare const prefix: string;
9109
9262
  `;
9110
- writeFileSync8(join17(targetDir, "index.d.ts"), dtsSource);
9111
- const snapshotPath = join17(targetDir, PRERENDER_SNAPSHOT_FILE);
9263
+ writeFileSync8(join16(targetDir, "index.d.ts"), dtsSource);
9264
+ const snapshotPath = join16(targetDir, PRERENDER_SNAPSHOT_FILE);
9112
9265
  writeFileSync8(snapshotPath, `{}
9113
9266
  `);
9114
- const prerenders = await prerenderFromBundle({ kind: "package", path: join17(targetDir, "index.js") }, rootDir, true);
9267
+ const prerenders = await prerenderFromBundle({ kind: "package", path: join16(targetDir, "index.js") }, rootDir, true);
9115
9268
  writeFileSync8(snapshotPath, `${JSON.stringify(Object.fromEntries(prerenders.map(({ prefix: key, ssg }) => [key, ssg])))}
9116
9269
  `);
9117
- console.log(`[furin] Package artifact: ${toPosixPath(relative12(rootDir, targetDir))}`);
9270
+ console.log(`[furin] Package artifact: ${toPosixPath(relative11(rootDir, targetDir))}`);
9118
9271
  return {
9119
9272
  buildId,
9120
9273
  generatedAt: new Date().toISOString(),
9121
9274
  prefix,
9122
- targetDir: toPosixPath(relative12(rootDir, targetDir))
9275
+ targetDir: toPosixPath(relative11(rootDir, targetDir))
9123
9276
  };
9124
9277
  }
9125
9278
 
9126
9279
  // src/adapter/static.ts
9127
9280
  import { cpSync as cpSync2, existsSync as existsSync15, rmSync as rmSync6, writeFileSync as writeFileSync9 } from "fs";
9128
- import { dirname as dirname16, isAbsolute as isAbsolute6, join as join18, parse as parse4, relative as relative13, resolve as resolve11, sep as sep3, win32 } from "path";
9281
+ import { dirname as dirname16, isAbsolute as isAbsolute6, join as join17, parse as parse3, relative as relative12, resolve as resolve11, sep as sep3, win32 } from "path";
9129
9282
  var TRAILING_SLASHES_RE = /\/+$/;
9130
9283
  var STATIC_RENDER_ORIGIN = "http://localhost";
9131
9284
  function pathToOutputFile(urlPath, outDir, fileName) {
9132
9285
  const normalizedOutDir = resolve11(outDir);
9133
9286
  if (urlPath === "/" || urlPath === "") {
9134
- return join18(normalizedOutDir, fileName);
9287
+ return join17(normalizedOutDir, fileName);
9135
9288
  }
9136
9289
  const resolved = resolve11(normalizedOutDir, urlPath.slice(1), fileName);
9137
9290
  if (!resolved.startsWith(`${normalizedOutDir}${sep3}`)) {
@@ -9265,12 +9418,12 @@ function replaceOutDir(outDir, publicSrcDir, clientSrcDir, outputs, shellHtml) {
9265
9418
  cpSync2(publicSrcDir, outDir, { recursive: true, dereference: true });
9266
9419
  }
9267
9420
  if (existsSync15(clientSrcDir)) {
9268
- cpSync2(clientSrcDir, join18(outDir, "_client"), { recursive: true, dereference: true });
9421
+ cpSync2(clientSrcDir, join17(outDir, "_client"), { recursive: true, dereference: true });
9269
9422
  }
9270
9423
  for (const output of outputs) {
9271
9424
  writeStaticOutput(output);
9272
9425
  }
9273
- writeFileSync9(join18(outDir, "404.html"), shellHtml);
9426
+ writeFileSync9(join17(outDir, "404.html"), shellHtml);
9274
9427
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
9275
9428
  }
9276
9429
  function logRenderFailure(failure, error) {
@@ -9299,7 +9452,7 @@ var STATIC_ENTRY = "_furin-static";
9299
9452
  async function bundleStaticExport(app, shellHtml, preloadManifest, serverDir, rootDir, options) {
9300
9453
  const { root, routes } = app;
9301
9454
  const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
9302
- const entry = createVirtualBuildEntry(join18(serverDir, `${STATIC_ENTRY}.ts`), buildEntrySource({
9455
+ const entry = createVirtualBuildEntry(join17(serverDir, `${STATIC_ENTRY}.ts`), buildEntrySource({
9303
9456
  apps: [
9304
9457
  {
9305
9458
  clientLogging: Boolean(options.clientLogging),
@@ -9346,7 +9499,7 @@ async function bundleStaticExport(app, shellHtml, preloadManifest, serverDir, ro
9346
9499
  throw new AggregateError(result.logs, "[furin] static export bundle failed");
9347
9500
  }
9348
9501
  await buildFlightCodec(serverDir, options.plugins);
9349
- return join18(serverDir, `${STATIC_ENTRY}.js`);
9502
+ return join17(serverDir, `${STATIC_ENTRY}.js`);
9350
9503
  }
9351
9504
  function assertNoRequestLoaders(routes, root) {
9352
9505
  const offenders = [];
@@ -9382,11 +9535,11 @@ async function buildStaticTarget(app, rootDir, buildRoot, options) {
9382
9535
  const outDir = resolve11(rootDir, rawOutDir);
9383
9536
  const normalizedRoot = resolve11(rootDir);
9384
9537
  const normalizedBuildRoot = resolve11(buildRoot);
9385
- if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse4(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
9538
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
9386
9539
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
9387
9540
  }
9388
9541
  function isOutsideOutDir(target) {
9389
- const rel = relative13(outDir, target);
9542
+ const rel = relative12(outDir, target);
9390
9543
  return rel.startsWith("..") || isAbsolute6(rel);
9391
9544
  }
9392
9545
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
@@ -9397,17 +9550,17 @@ async function buildStaticTarget(app, rootDir, buildRoot, options) {
9397
9550
  const renderedRoutes = [];
9398
9551
  const skippedRoutes = [];
9399
9552
  const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
9400
- const targetDir = join18(buildRoot, "static");
9553
+ const targetDir = join17(buildRoot, "static");
9401
9554
  rmSync6(targetDir, { force: true, recursive: true });
9402
9555
  ensureDir(targetDir);
9403
9556
  try {
9404
9557
  const { entryChunk, cssChunks, preloadManifest } = await buildClient(ssgRoutes, {
9405
9558
  basePath,
9406
9559
  clientLogging: Boolean(options.clientLogging),
9407
- metafilePath: options.analyze ? join18(buildRoot, "analysis", "static-client.json") : undefined,
9560
+ metafilePath: options.analyze ? join17(buildRoot, "analysis", "static-client.json") : undefined,
9408
9561
  optimizeImports: options.optimizeImports,
9409
9562
  outDir: targetDir,
9410
- pagesDir: dirname16(root.path),
9563
+ pages: { pagesDir: app.pagesDir, style: app.style },
9411
9564
  routeRegistry: app.routeRegistry,
9412
9565
  plugins: options.plugins,
9413
9566
  preloadRouteChunks: options.preload?.routeChunks,
@@ -9415,16 +9568,16 @@ async function buildStaticTarget(app, rootDir, buildRoot, options) {
9415
9568
  reactCompiler: options.reactCompiler,
9416
9569
  rootLayout: root.path
9417
9570
  });
9418
- const publicFavicon = join18(rootDir, "public", "favicon.ico");
9571
+ const publicFavicon = join17(rootDir, "public", "favicon.ico");
9419
9572
  const faviconHref = existsSync15(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
9420
9573
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
9421
- const bundle = await bundleStaticExport(app, shellHtml, preloadManifest, join18(targetDir, "server"), rootDir, options);
9574
+ const bundle = await bundleStaticExport(app, shellHtml, preloadManifest, join17(targetDir, "server"), rootDir, options);
9422
9575
  const exported = await exportStaticFromBundle(bundle, rootDir, {
9423
9576
  basePath,
9424
9577
  patterns: ssgRoutes.map((route) => route.pattern)
9425
9578
  });
9426
9579
  const outputs = await collectStaticOutputs(exported, outDir, basePath, onSSR, skippedRoutes);
9427
- replaceOutDir(outDir, join18(rootDir, "public"), join18(targetDir, "client"), outputs, shellHtml);
9580
+ replaceOutDir(outDir, join17(rootDir, "public"), join17(targetDir, "client"), outputs, shellHtml);
9428
9581
  renderedRoutes.push(...outputs.map((output) => output.path));
9429
9582
  } finally {
9430
9583
  rmSync6(targetDir, { force: true, recursive: true });
@@ -9449,7 +9602,7 @@ import {
9449
9602
  symlinkSync,
9450
9603
  writeFileSync as writeFileSync10
9451
9604
  } from "fs";
9452
- import { basename as basename6, dirname as dirname17, join as join19, relative as relative14 } from "path";
9605
+ import { basename as basename6, dirname as dirname17, join as join18, relative as relative13 } from "path";
9453
9606
  import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL3 } from "url";
9454
9607
 
9455
9608
  // src/adapter/vercel/data.ts
@@ -9495,7 +9648,7 @@ function assertRegions(regions) {
9495
9648
  }
9496
9649
  function frameworkVersion() {
9497
9650
  const packageRoot = dirname17(dirname17(fileURLToPath9(import.meta.resolve("@teyik0/furin"))));
9498
- const packageJson = JSON.parse(readFileSync8(join19(packageRoot, "package.json"), "utf8"));
9651
+ const packageJson = JSON.parse(readFileSync8(join18(packageRoot, "package.json"), "utf8"));
9499
9652
  return packageJson.version;
9500
9653
  }
9501
9654
  function encodeCacheTag(value) {
@@ -9520,7 +9673,7 @@ function functionNameForPath(path, mode, names) {
9520
9673
  return "[...splat]";
9521
9674
  }
9522
9675
  if (segment.startsWith(":")) {
9523
- return `[${segment.slice(1)}]`;
9676
+ return segment.endsWith("?") ? `[[${segment.slice(1, -1)}]]` : `[${segment.slice(1)}]`;
9524
9677
  }
9525
9678
  const sanitized = segment.replace(UNSAFE_FUNCTION_PATH_RE, "-");
9526
9679
  if (sanitized === segment && segment !== "." && segment !== "..") {
@@ -9635,7 +9788,7 @@ async function addPrerenderFallback(job, response, functionsDir) {
9635
9788
  const { spec } = job;
9636
9789
  const fallback = `${basename6(spec.functionName)}.prerender-fallback.html`;
9637
9790
  const location = response.headers.get("location") ?? undefined;
9638
- const fallbackPath = join19(dirname17(join19(functionsDir, spec.functionName)), fallback);
9791
+ const fallbackPath = join18(dirname17(join18(functionsDir, spec.functionName)), fallback);
9639
9792
  ensureDir(dirname17(fallbackPath));
9640
9793
  writeFileSync10(fallbackPath, await response.text());
9641
9794
  spec.config.fallback = fallback;
@@ -9651,10 +9804,10 @@ async function buildProductionFallbacks(jobs, functionsDir, rootDir, buildRoot)
9651
9804
  if (jobs.length === 0) {
9652
9805
  return;
9653
9806
  }
9654
- const resultPath = join19(buildRoot, `vercel-prerender-${crypto.randomUUID()}.json`);
9807
+ const resultPath = join18(buildRoot, `vercel-prerender-${crypto.randomUUID()}.json`);
9655
9808
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
9656
9809
  const script = `
9657
- const handler = (await import(${JSON.stringify(pathToFileURL3(join19(functionsDir, "__server.func/index.js")).href)})).default;
9810
+ const handler = (await import(${JSON.stringify(pathToFileURL3(join18(functionsDir, "__server.func/index.js")).href)})).default;
9658
9811
  const results = [];
9659
9812
  for (const [index, url] of ${JSON.stringify(requests)}.entries()) {
9660
9813
  const response = await handler.fetch(new Request(url));
@@ -9709,9 +9862,9 @@ async function buildBootstrap(serverFunctionDir) {
9709
9862
  });
9710
9863
  }
9711
9864
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
9712
- const aliasPath = join19(functionsDir, `${functionName}.func`);
9865
+ const aliasPath = join18(functionsDir, `${functionName}.func`);
9713
9866
  ensureDir(dirname17(aliasPath));
9714
- const target = relative14(dirname17(aliasPath), serverFunctionDir);
9867
+ const target = relative13(dirname17(aliasPath), serverFunctionDir);
9715
9868
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
9716
9869
  }
9717
9870
  function copyStaticAssets(output, staticDir) {
@@ -9719,16 +9872,16 @@ function copyStaticAssets(output, staticDir) {
9719
9872
  if (publicDir !== undefined) {
9720
9873
  cpSync3(publicDir, staticDir, { recursive: true });
9721
9874
  for (const app of apps) {
9722
- const appStaticDir = join19(staticDir, app.prefix.slice(1));
9723
- cpSync3(publicDir, join19(appStaticDir, "public"), { recursive: true });
9724
- const favicon = join19(publicDir, "favicon.ico");
9875
+ const appStaticDir = join18(staticDir, app.prefix.slice(1));
9876
+ cpSync3(publicDir, join18(appStaticDir, "public"), { recursive: true });
9877
+ const favicon = join18(publicDir, "favicon.ico");
9725
9878
  if (app.prefix !== "" && existsSync16(favicon)) {
9726
- cpSync3(favicon, join19(appStaticDir, "favicon.ico"));
9879
+ cpSync3(favicon, join18(appStaticDir, "favicon.ico"));
9727
9880
  }
9728
9881
  }
9729
9882
  }
9730
9883
  for (const app of apps) {
9731
- cpSync3(app.clientDir, join19(staticDir, app.prefix.slice(1), "_client"), { recursive: true });
9884
+ cpSync3(app.clientDir, join18(staticDir, app.prefix.slice(1), "_client"), { recursive: true });
9732
9885
  }
9733
9886
  }
9734
9887
  function buildOutputConfig(apps, specs) {
@@ -9762,7 +9915,7 @@ function buildOutputConfig(apps, specs) {
9762
9915
  };
9763
9916
  }
9764
9917
  function writeFunctionConfig(serverFunctionDir, regions) {
9765
- writeFileSync10(join19(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
9918
+ writeFileSync10(join18(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
9766
9919
  handler: "index.js",
9767
9920
  launcherType: "Nodejs",
9768
9921
  ...regions === undefined ? {} : { regions },
@@ -9779,39 +9932,39 @@ function vercel(options) {
9779
9932
  name: "vercel",
9780
9933
  async onBuildComplete(output) {
9781
9934
  const { apps, rootDir, server } = output;
9782
- const outputDir = join19(rootDir, ".vercel", "output");
9783
- const staticDir = join19(outputDir, "static");
9784
- const functionsDir = join19(outputDir, "functions");
9785
- const serverFunctionDir = join19(functionsDir, "__server.func");
9935
+ const outputDir = join18(rootDir, ".vercel", "output");
9936
+ const staticDir = join18(outputDir, "static");
9937
+ const functionsDir = join18(outputDir, "functions");
9938
+ const serverFunctionDir = join18(functionsDir, "__server.func");
9786
9939
  rmSync7(outputDir, { force: true, recursive: true });
9787
9940
  ensureDir(staticDir);
9788
9941
  ensureDir(serverFunctionDir);
9789
9942
  for (const file of [...server.files, "server-codec.js"]) {
9790
- cpSync3(join19(server.dir, file), join19(serverFunctionDir, file));
9943
+ cpSync3(join18(server.dir, file), join18(serverFunctionDir, file));
9791
9944
  }
9792
9945
  copyStaticAssets(output, staticDir);
9793
9946
  const pprResumeKey = crypto.randomUUID();
9794
9947
  const { jobs, specs } = createPrerenderSpecs(apps, pprResumeKey);
9795
- const serverBundleBytes = server.files.reduce((total, file) => total + statSync2(join19(server.dir, file)).size, 0);
9796
- writeFileSync10(join19(serverFunctionDir, VERCEL_DATA_FILE), `${JSON.stringify(runtimeData(apps, specs, pprResumeKey, serverBundleBytes))}
9948
+ const serverBundleBytes = server.files.reduce((total, file) => total + statSync2(join18(server.dir, file)).size, 0);
9949
+ writeFileSync10(join18(serverFunctionDir, VERCEL_DATA_FILE), `${JSON.stringify(runtimeData(apps, specs, pprResumeKey, serverBundleBytes))}
9797
9950
  `);
9798
9951
  await buildBootstrap(serverFunctionDir);
9799
9952
  await buildProductionFallbacks(jobs, functionsDir, rootDir, output.buildRoot);
9800
9953
  writeFunctionConfig(serverFunctionDir, options.regions);
9801
9954
  for (const spec of specs) {
9802
9955
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
9803
- writeFileSync10(join19(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
9956
+ writeFileSync10(join18(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
9804
9957
  `);
9805
9958
  }
9806
- writeFileSync10(join19(outputDir, "config.json"), `${JSON.stringify(buildOutputConfig(apps, specs), null, 2)}
9959
+ writeFileSync10(join18(outputDir, "config.json"), `${JSON.stringify(buildOutputConfig(apps, specs), null, 2)}
9807
9960
  `);
9808
- console.log(`[furin] Vercel output: ${toPosixPath(relative14(rootDir, outputDir))}`);
9961
+ console.log(`[furin] Vercel output: ${toPosixPath(relative13(rootDir, outputDir))}`);
9809
9962
  return {
9810
9963
  buildId: output.buildId,
9811
9964
  generatedAt: new Date().toISOString(),
9812
9965
  isrRoutes: apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted(),
9813
- outputDir: toPosixPath(relative14(rootDir, outputDir)),
9814
- serverPath: toPosixPath(relative14(rootDir, serverFunctionDir)),
9966
+ outputDir: toPosixPath(relative13(rootDir, outputDir)),
9967
+ serverPath: toPosixPath(relative13(rootDir, serverFunctionDir)),
9815
9968
  ssgRoutes: jobs.filter((job) => job.route.mode === "ssg").map((job) => job.path).toSorted()
9816
9969
  };
9817
9970
  },
@@ -9823,10 +9976,12 @@ function vercel(options) {
9823
9976
  import { t } from "elysia";
9824
9977
  var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
9825
9978
  var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
9979
+ var routeStyleSchema = t.Union([t.Literal("nextjs"), t.Literal("tanstack")]);
9826
9980
  var configSchema = t.Object({
9827
9981
  apps: t.Optional(t.Array(t.Object({
9828
9982
  pagesDir: t.String(),
9829
- prefix: t.Optional(t.String())
9983
+ prefix: t.Optional(t.String()),
9984
+ style: routeStyleSchema
9830
9985
  }))),
9831
9986
  bun: t.Optional(t.Object({
9832
9987
  compile: t.Optional(compileTargetSchema),
@@ -9841,6 +9996,7 @@ var configSchema = t.Object({
9841
9996
  rootDir: t.Optional(t.String()),
9842
9997
  serverEntry: t.Optional(t.String()),
9843
9998
  serverSourceMaps: t.Optional(t.Boolean()),
9999
+ style: t.Optional(routeStyleSchema),
9844
10000
  static: t.Optional(t.Object({
9845
10001
  basePath: t.Optional(t.String()),
9846
10002
  onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
@@ -9850,13 +10006,8 @@ var configSchema = t.Object({
9850
10006
 
9851
10007
  // src/plugin/route-config.ts
9852
10008
  import { existsSync as existsSync17, readFileSync as readFileSync9, writeFileSync as writeFileSync11 } from "fs";
9853
- import { basename as basename7, join as join20, relative as relative15, resolve as resolve12 } from "path";
9854
- var EXTENSION_RE = /\.(?:[cm]?[jt]sx?)$/;
10009
+ import { relative as relative14, resolve as resolve12 } from "path";
9855
10010
  var IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
9856
- var PATH_SEPARATOR_RE = /[\\/]/;
9857
- function withoutExtension(path) {
9858
- return path.replace(EXTENSION_RE, "");
9859
- }
9860
10011
  function propertyName(key) {
9861
10012
  if (key?.type === "Identifier") {
9862
10013
  return key.name;
@@ -9937,9 +10088,9 @@ function position2(source, offset) {
9937
10088
  function issueAt(file, parsed, node, message) {
9938
10089
  return { file, ...position2(parsed.source, node.start), message };
9939
10090
  }
9940
- function checkKey(file, instance, parsed) {
10091
+ function checkKey(file, route, parsed) {
9941
10092
  const { config, head, id } = parsed.route;
9942
- const expected = fileRouteId(instance, file);
10093
+ const expected = route.id;
9943
10094
  if (!id) {
9944
10095
  return issueAt(file, parsed, head, `defineRoute() must name this file. Its id is "${expected}":
9945
10096
  defineRoute("${expected}")`);
@@ -9968,21 +10119,21 @@ function suggestedMode(route, isRoot) {
9968
10119
  }
9969
10120
  return route.methods.has("loader") || route.methods.has("requestLoader") ? "ssr" : "ssg";
9970
10121
  }
9971
- function checkFactory(file, instance, parsed) {
10122
+ function checkFactory(file, manifestRoute, parsed) {
9972
10123
  const { route } = parsed;
9973
- const isRoot = withoutExtension(file) === join20(instance.pagesDir, "root");
10124
+ const isRoot = manifestRoute === undefined;
9974
10125
  if (isRoot === route.isRootFactory) {
9975
10126
  return;
9976
10127
  }
9977
10128
  const mode = suggestedMode(route, isRoot);
9978
10129
  if (isRoot) {
9979
- return issueAt(file, parsed, route.head, `root.tsx must use defineRootRoute(), which has no parent layout:
10130
+ return issueAt(file, parsed, route.head, `The root layout must use defineRootRoute(), which has no parent layout:
9980
10131
  import { defineRootRoute } from "@teyik0/furin";
9981
10132
  export const route = defineRootRoute().config({ mode: "${mode}" })`);
9982
10133
  }
9983
- return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for root.tsx. Use defineRoute with this file's id:
10134
+ return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for the root layout. Use defineRoute with this file's id:
9984
10135
  import { defineRoute } from "@teyik0/furin";
9985
- export const route = defineRoute("${fileRouteId(instance, file)}").config({ mode: "${mode}" })`);
10136
+ export const route = defineRoute("${manifestRoute.id}").config({ mode: "${mode}" })`);
9986
10137
  }
9987
10138
  function checkConfig(file, parsed) {
9988
10139
  const { route } = parsed;
@@ -10013,56 +10164,64 @@ function declaredParams(route) {
10013
10164
  }
10014
10165
  return new Set(keys.filter((key) => key !== undefined));
10015
10166
  }
10016
- function undeclaredSegments(file, pagesDir, declared) {
10017
- return withoutExtension(relative15(pagesDir, file)).split(PATH_SEPARATOR_RE).flatMap((segment) => {
10018
- const dynamic = parseDynamicRouteSegment(segment, file);
10019
- return dynamic ? [{ key: dynamic.catchAll ? "*" : dynamic.name, segment }] : [];
10020
- }).filter(({ key }) => declared !== true && !declared.has(key));
10167
+ function undeclaredParams(route, declared) {
10168
+ return route.params.filter(({ name }) => declared !== true && !declared.has(name));
10021
10169
  }
10022
- function paramsSchema(segments) {
10023
- const fields = segments.map(({ key }) => `${IDENTIFIER_RE.test(key) ? key : JSON.stringify(key)}: t.String()`);
10170
+ function paramsSchema(params) {
10171
+ const fields = params.map(({ name, optional }) => `${IDENTIFIER_RE.test(name) ? name : JSON.stringify(name)}: ${optional ? "t.Optional(t.String())" : "t.String()"}`);
10024
10172
  return `params: t.Object({ ${fields.join(", ")} })`;
10025
10173
  }
10026
- function checkParams(file, pagesDir, parsed) {
10027
- const missing = undeclaredSegments(file, pagesDir, declaredParams(parsed.route));
10174
+ function checkParams(file, route, parsed) {
10175
+ const missing = undeclaredParams(route, declaredParams(parsed.route));
10028
10176
  if (missing.length === 0) {
10029
10177
  return;
10030
10178
  }
10031
10179
  const plural = missing.length > 1;
10032
10180
  const tImport = parsed.imports.get("t")?.specifier === "elysia" ? "" : `
10033
10181
  import { t } from "elysia";`;
10034
- 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}
10182
+ 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}
10035
10183
  ${paramsSchema(missing)}`);
10036
10184
  }
10037
- function checkRoute(file, instance, parsed) {
10038
- const factory = checkFactory(file, instance, parsed);
10185
+ function checkBoundaryMethods(file, instance, parsed) {
10186
+ const method = ["error", "notFound"].find((name) => parsed.route.methods.has(name));
10187
+ if (instance.style !== "nextjs" || method === undefined) {
10188
+ return;
10189
+ }
10190
+ const convention = method === "error" ? "an error.tsx" : "a not-found.tsx";
10191
+ 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.`);
10192
+ }
10193
+ function checkRoute(file, instance, route, parsed) {
10194
+ const factory = checkFactory(file, route, parsed);
10039
10195
  if (factory) {
10040
10196
  return [factory];
10041
10197
  }
10042
- const isLayout = basename7(withoutExtension(file)) === "_route";
10043
10198
  return [
10044
10199
  checkConfig(file, parsed),
10045
- parsed.route.isRootFactory ? undefined : checkKey(file, instance, parsed),
10200
+ route === undefined ? undefined : checkKey(file, route, parsed),
10046
10201
  checkMode(file, parsed),
10047
- parsed.route.isRootFactory || isLayout ? undefined : checkParams(file, instance.pagesDir, parsed)
10202
+ route === undefined || route.kind === "layout" ? undefined : checkParams(file, route, parsed),
10203
+ checkBoundaryMethods(file, instance, parsed)
10048
10204
  ];
10049
10205
  }
10050
- function routeFiles(pagesDir) {
10051
- const root = join20(pagesDir, "root.tsx");
10052
- return [
10053
- ...existsSync17(root) ? [root] : [],
10054
- ...routeSourcePaths({ pagesDir, prefix: "" })
10055
- ].toSorted((left, right) => left.localeCompare(right));
10206
+ function routeFiles(manifest) {
10207
+ const files = manifest.routes.map((route) => [
10208
+ resolve12(route.sourcePath),
10209
+ route
10210
+ ]);
10211
+ if (existsSync17(manifest.rootPath)) {
10212
+ files.push([resolve12(manifest.rootPath), undefined]);
10213
+ }
10214
+ return files.toSorted(([left], [right]) => left.localeCompare(right));
10056
10215
  }
10057
- function validateRouteConfig({ pagesDir, prefix }) {
10058
- const instance = { pagesDir: resolve12(pagesDir), prefix };
10059
- return routeFiles(instance.pagesDir).flatMap((file) => {
10216
+ function validateRouteConfig(spec) {
10217
+ const instance = { ...spec, pagesDir: resolve12(spec.pagesDir) };
10218
+ return routeFiles(scanRouteManifest(instance)).flatMap(([file, route]) => {
10060
10219
  const parsed = parseRoute(file);
10061
- return parsed ? checkRoute(file, instance, parsed).filter((issue) => issue !== undefined) : [];
10220
+ return parsed ? checkRoute(file, instance, route, parsed).filter((issue) => issue !== undefined) : [];
10062
10221
  });
10063
10222
  }
10064
10223
  function displayPath(file) {
10065
- const projected = relative15(process.cwd(), file).replaceAll("\\", "/");
10224
+ const projected = relative14(process.cwd(), file).replaceAll("\\", "/");
10066
10225
  return projected.startsWith("../") ? file : projected;
10067
10226
  }
10068
10227
  function formatRouteConfigIssue(issue) {
@@ -10079,10 +10238,10 @@ function assertValidRouteConfig(instance) {
10079
10238
 
10080
10239
  // src/build/discover-mounts.ts
10081
10240
  import { readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
10082
- import { join as join21 } from "path";
10241
+ import { join as join19 } from "path";
10083
10242
  var DISCOVERY_PROCESS = frameworkSourceModule("build/discover-mounts-process.ts");
10084
10243
  async function discoverFurinMounts(serverEntry, rootDir) {
10085
- const resultPath = join21(rootDir, ".furin", "build", `mounts-${crypto.randomUUID()}.json`);
10244
+ const resultPath = join19(rootDir, ".furin", "build", `mounts-${crypto.randomUUID()}.json`);
10086
10245
  const child = Bun.spawn([process.execPath, DISCOVERY_PROCESS, serverEntry, resultPath], {
10087
10246
  cwd: rootDir,
10088
10247
  env: { ...process.env, NODE_ENV: "production" },
@@ -10109,7 +10268,7 @@ ${stdout}
10109
10268
 
10110
10269
  // src/build/discover-pages.ts
10111
10270
  import { mkdtempSync, readFileSync as readFileSync11, renameSync as renameSync3, rmSync as rmSync9, writeFileSync as writeFileSync12 } from "fs";
10112
- import { join as join22 } from "path";
10271
+ import { join as join20 } from "path";
10113
10272
  import { serialize } from "v8";
10114
10273
 
10115
10274
  // src/build/discovery-plugins.ts
@@ -10180,10 +10339,10 @@ async function discoveryPlugins(plugins) {
10180
10339
  // src/build/discover-pages.ts
10181
10340
  async function discoverPages(apps, rootDir, plugins) {
10182
10341
  const runtime = await discoveryPlugins(plugins);
10183
- const buildDir = join22(rootDir, ".furin/build");
10342
+ const buildDir = join20(rootDir, ".furin/build");
10184
10343
  ensureDir(buildDir);
10185
- const directory = mkdtempSync(join22(buildDir, "discovery-"));
10186
- const resultPath = join22(directory, "pages.json");
10344
+ const directory = mkdtempSync(join20(buildDir, "discovery-"));
10345
+ const resultPath = join20(directory, "pages.json");
10187
10346
  const child = Bun.spawn([
10188
10347
  process.execPath,
10189
10348
  frameworkSourceModule("build/discover-pages-process.ts"),
@@ -10253,22 +10412,21 @@ async function resolveAppSpecs(options, serverEntry, rootDir) {
10253
10412
  if (options.apps && options.apps.length > 0) {
10254
10413
  return options.apps.map((app) => ({
10255
10414
  pagesDir: resolve13(rootDir, app.pagesDir),
10256
- prefix: normalizePrefix(app.prefix)
10415
+ prefix: normalizePrefix(app.prefix),
10416
+ style: app.style
10257
10417
  }));
10258
10418
  }
10259
- if (options.pagesDir) {
10260
- return [{ pagesDir: resolve13(rootDir, options.pagesDir), prefix: "" }];
10261
- }
10262
10419
  if (serverEntry) {
10263
10420
  const mounted = await discoverFurinMounts(serverEntry, rootDir);
10264
10421
  if (mounted.length > 0) {
10265
10422
  return mounted.map((app) => ({
10266
10423
  pagesDir: resolve13(rootDir, app.pagesDir),
10267
- prefix: app.prefix
10424
+ prefix: app.prefix,
10425
+ style: app.style
10268
10426
  }));
10269
10427
  }
10270
10428
  }
10271
- return [{ pagesDir: resolve13(rootDir, "src/pages"), prefix: "" }];
10429
+ throw new Error(`[furin] No app to build: ${serverEntry ? `${toPosixPath(relative15(rootDir, serverEntry))} mounts no furin() plugin` : "no server entry found"}. Mount furin({ style }) in the server entry, or list the apps in furin.config.ts: apps: [{ pagesDir: "src/routes", style: "tanstack" }].`);
10272
10430
  }
10273
10431
  async function scanApps(options, serverEntry, rootDir) {
10274
10432
  const appSpecs = await resolveAppSpecs(options, serverEntry, rootDir);
@@ -10297,9 +10455,13 @@ function generateRouteTypes(options) {
10297
10455
  async function buildApp(options) {
10298
10456
  return withProductionBuild(() => buildAppInternal(options));
10299
10457
  }
10458
+ function existingServerEntry(options, rootDir) {
10459
+ const entry = resolve13(rootDir, options.serverEntry ?? "src/server.ts");
10460
+ return existsSync18(entry) ? entry : null;
10461
+ }
10300
10462
  async function buildAppInternal(options) {
10301
10463
  const rootDir = resolve13(options.rootDir ?? process.cwd());
10302
- const buildRoot = join23(rootDir, BUILD_OUTPUT_DIR);
10464
+ const buildRoot = join21(rootDir, BUILD_OUTPUT_DIR);
10303
10465
  const targets = requestedTargets(options.target);
10304
10466
  const serverEntry = (() => {
10305
10467
  if (targets.every(isServerless)) {
@@ -10317,7 +10479,8 @@ async function buildAppInternal(options) {
10317
10479
  }
10318
10480
  return entry;
10319
10481
  })();
10320
- const apps = await scanApps(options, serverEntry, rootDir);
10482
+ const mountEntry = serverEntry ?? existingServerEntry(options, rootDir);
10483
+ const apps = await scanApps(options, mountEntry, rootDir);
10321
10484
  writeAppRouteTypes(apps, rootDir);
10322
10485
  const primaryApp = apps.find((app) => app.prefix === "") ?? apps[0];
10323
10486
  ensureDir(buildRoot);
@@ -10325,13 +10488,14 @@ async function buildAppInternal(options) {
10325
10488
  version: 1,
10326
10489
  generatedAt: new Date().toISOString(),
10327
10490
  rootDir: toPosixPath(rootDir),
10328
- pagesDir: toPosixPath(relative16(rootDir, primaryApp.pagesDir)),
10329
- rootPath: toPosixPath(relative16(rootDir, primaryApp.root.path)),
10330
- serverEntry: serverEntry ? toPosixPath(relative16(rootDir, serverEntry)) : null,
10491
+ pagesDir: toPosixPath(relative15(rootDir, primaryApp.pagesDir)),
10492
+ rootPath: toPosixPath(relative15(rootDir, primaryApp.root.path)),
10493
+ serverEntry: serverEntry ? toPosixPath(relative15(rootDir, serverEntry)) : null,
10331
10494
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
10332
10495
  apps: apps.map((app) => ({
10333
- pagesDir: toPosixPath(relative16(rootDir, app.pagesDir)),
10496
+ pagesDir: toPosixPath(relative15(rootDir, app.pagesDir)),
10334
10497
  prefix: app.prefix,
10498
+ style: app.style,
10335
10499
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
10336
10500
  })),
10337
10501
  targets: {}
@@ -10357,7 +10521,7 @@ async function buildAppInternal(options) {
10357
10521
  const adapter = adapterFor(target, options);
10358
10522
  manifest.targets[adapter.name] = await buildAdapterTarget(adapter, apps, rootDir, buildRoot, serverEntry, options);
10359
10523
  }
10360
- writeFileSync13(join23(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
10524
+ writeFileSync13(join21(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
10361
10525
  `);
10362
10526
  return {
10363
10527
  manifest,
@@ -10481,6 +10645,9 @@ async function loadCliConfig(cwd, explicitConfigPath) {
10481
10645
  const [firstError] = compiledConfigSchema.Errors(configToValidate);
10482
10646
  throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.instancePath ?? "/"})`);
10483
10647
  }
10648
+ if (configToValidate.pagesDir !== undefined && configToValidate.style === undefined) {
10649
+ throw new Error(`[furin] Invalid config at ${configPath}: pagesDir needs its file-routing style: add style: "nextjs" or "tanstack".`);
10650
+ }
10484
10651
  const resolvedRootDir = resolve14(rootDir, configToValidate.rootDir ?? ".");
10485
10652
  return {
10486
10653
  ...configToValidate,
@@ -10493,7 +10660,7 @@ async function loadCliConfig(cwd, explicitConfigPath) {
10493
10660
  }
10494
10661
 
10495
10662
  // src/cli/dev.ts
10496
- import { join as join24, resolve as resolve15 } from "path";
10663
+ import { join as join22, resolve as resolve15 } from "path";
10497
10664
  import { pathToFileURL as pathToFileURL5 } from "url";
10498
10665
  import { parseArgs } from "util";
10499
10666
  var PORT = /^\d+$/;
@@ -10544,7 +10711,7 @@ async function runDevelopment(cwd, args) {
10544
10711
  const child = Bun.spawn([
10545
10712
  process.execPath,
10546
10713
  "--hot",
10547
- join24(import.meta.dir, "dev-worker.ts"),
10714
+ join22(import.meta.dir, "dev-worker.ts"),
10548
10715
  resolve15(config.rootDir, config.serverEntry ?? "src/server.ts"),
10549
10716
  port ?? "",
10550
10717
  integration
@@ -10586,7 +10753,7 @@ async function runDevelopment(cwd, args) {
10586
10753
 
10587
10754
  // src/cli/preview.ts
10588
10755
  import { existsSync as existsSync20 } from "fs";
10589
- import { isAbsolute as isAbsolute7, join as join25, relative as relative17, resolve as resolve16 } from "path";
10756
+ import { isAbsolute as isAbsolute7, join as join23, relative as relative16, resolve as resolve16 } from "path";
10590
10757
  var LEADING_SLASHES_RE = /^\/+/;
10591
10758
  var TRAILING_SLASHES_RE2 = /\/+$/;
10592
10759
  function normalizeStaticPreviewBasePath(basePath) {
@@ -10605,14 +10772,14 @@ function startStaticPreview({
10605
10772
  }) {
10606
10773
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
10607
10774
  const distDir = resolve16(rawDistDir);
10608
- const indexPath = join25(distDir, "index.html");
10609
- const notFoundPath = join25(distDir, "404.html");
10610
- const faviconPath = join25(distDir, "favicon.ico");
10775
+ const indexPath = join23(distDir, "index.html");
10776
+ const notFoundPath = join23(distDir, "404.html");
10777
+ const faviconPath = join23(distDir, "favicon.ico");
10611
10778
  if (!(existsSync20(indexPath) && existsSync20(notFoundPath))) {
10612
10779
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
10613
10780
  }
10614
10781
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
10615
- const clientDir = join25(distDir, "_client");
10782
+ const clientDir = join23(distDir, "_client");
10616
10783
  const fetchStaticFile = async (request) => {
10617
10784
  const encodedPathname = new URL(request.url).pathname;
10618
10785
  let pathname;
@@ -10626,7 +10793,7 @@ function startStaticPreview({
10626
10793
  }
10627
10794
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
10628
10795
  const exactPath = resolve16(distDir, logicalPath);
10629
- const relativePath = relative17(distDir, exactPath);
10796
+ const relativePath = relative16(distDir, exactPath);
10630
10797
  if (relativePath.startsWith("..") || isAbsolute7(relativePath)) {
10631
10798
  return notFound();
10632
10799
  }
@@ -10634,7 +10801,7 @@ function startStaticPreview({
10634
10801
  if (!pathname.endsWith("/") && await exactFile.exists()) {
10635
10802
  return new Response(exactFile);
10636
10803
  }
10637
- const indexFile = Bun.file(join25(exactPath, "index.html"));
10804
+ const indexFile = Bun.file(join23(exactPath, "index.html"));
10638
10805
  if (await indexFile.exists()) {
10639
10806
  return new Response(indexFile);
10640
10807
  }
@@ -10665,6 +10832,15 @@ function bail(msg) {
10665
10832
  console.error(`\x1B[31m\u2717\x1B[0m ${msg}`);
10666
10833
  process.exit(1);
10667
10834
  }
10835
+ function singleApp(pagesDir, style, prefix) {
10836
+ if (!pagesDir) {
10837
+ return;
10838
+ }
10839
+ if (style !== "nextjs" && style !== "tanstack") {
10840
+ bail(`pagesDir ${pagesDir} needs its file-routing style: pass --style nextjs|tanstack or set \`style\` in furin.config.ts.`);
10841
+ }
10842
+ return [{ pagesDir, prefix: normalizePrefix(prefix), style }];
10843
+ }
10668
10844
  function resolveCompileMode(flag, configCompile) {
10669
10845
  if (flag === "embed") {
10670
10846
  return "embed";
@@ -10752,6 +10928,7 @@ if (command === "dev") {
10752
10928
  output: { type: "string" },
10753
10929
  pagesDir: { type: "string" },
10754
10930
  prefix: { type: "string" },
10931
+ style: { type: "string" },
10755
10932
  target: { type: "string" }
10756
10933
  },
10757
10934
  strict: true
@@ -10787,16 +10964,10 @@ if (command === "dev") {
10787
10964
  const result = await buildApp({
10788
10965
  analyze: values.analyze,
10789
10966
  bun: output === undefined ? undefined : { output },
10790
- apps: values.pagesDir ?? config.pagesDir ? [
10791
- {
10792
- pagesDir: values.pagesDir ?? config.pagesDir,
10793
- prefix: normalizePrefix(values.prefix)
10794
- }
10795
- ] : config.apps,
10967
+ apps: singleApp(values.pagesDir ?? config.pagesDir, values.style ?? config.style, values.prefix) ?? config.apps,
10796
10968
  clientLogging: config.clientLogging ?? false,
10797
10969
  compile: resolveCompileMode(compileFlag, config.bun?.compile),
10798
10970
  optimizeImports: config.optimizeImports,
10799
- pagesDir: undefined,
10800
10971
  plugins: config.plugins,
10801
10972
  serverExternalPackages: values.external,
10802
10973
  preload: config.preload,
@@ -10816,7 +10987,8 @@ if (command === "dev") {
10816
10987
  args: argv.slice(1),
10817
10988
  options: {
10818
10989
  config: { type: "string" },
10819
- pagesDir: { type: "string" }
10990
+ pagesDir: { type: "string" },
10991
+ style: { type: "string" }
10820
10992
  },
10821
10993
  strict: true
10822
10994
  }).values;
@@ -10825,10 +10997,8 @@ if (command === "dev") {
10825
10997
  }
10826
10998
  const values = rawValues;
10827
10999
  const config = await loadCliConfig(process.cwd(), values.config);
10828
- const pagesDir = values.pagesDir ?? config.pagesDir;
10829
11000
  await generateRouteTypes({
10830
- apps: pagesDir ? [{ pagesDir, prefix: "" }] : config.apps,
10831
- pagesDir: undefined,
11001
+ apps: singleApp(values.pagesDir ?? config.pagesDir, values.style ?? config.style, undefined) ?? config.apps,
10832
11002
  plugins: config.plugins,
10833
11003
  rootDir: config.rootDir,
10834
11004
  serverEntry: config.serverEntry
@@ -10847,6 +11017,7 @@ BUILD OPTIONS
10847
11017
  --target ${BUILD_TARGETS.join(" | ")} | all (default: bun)
10848
11018
  "package" builds a publishable Elysia-plugin artifact (register.js + factory + client assets)
10849
11019
  --pagesDir Pages directory
11020
+ --style File-routing style of --pagesDir: nextjs or tanstack
10850
11021
  --prefix Mount prefix for the built app (e.g. /admin) \u2014 pairs with --pagesDir
10851
11022
  --config Config file path
10852
11023
  --compile server | embed Compile to binary: "server" keeps client on disk, "embed" is self-contained
@@ -10856,7 +11027,8 @@ BUILD OPTIONS
10856
11027
 
10857
11028
  TYPEGEN OPTIONS
10858
11029
  Writes furin-env.d.ts for every mounted app (run it before tsc in CI)
10859
- --pagesDir Pages directory (default: config apps, server entry furin() mounts, then src/pages)
11030
+ --pagesDir Pages directory (default: config pagesDir, config apps, then the server entry's furin() mounts)
11031
+ --style File-routing style of --pagesDir: nextjs or tanstack
10860
11032
  --config Config file path
10861
11033
 
10862
11034
  PREVIEW OPTIONS