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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -72,6 +72,12 @@ function routeSegmentToPattern(segment) {
72
72
  }
73
73
  return dynamic.catchAll ? "*" : `:${dynamic.name}`;
74
74
  }
75
+ function isRouteGroup(segment) {
76
+ return ROUTE_GROUP_RE.test(segment);
77
+ }
78
+ function routePatternKey(pattern) {
79
+ return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
80
+ }
75
81
  function filePathToPattern(path) {
76
82
  const parts = path.replaceAll("\\", "/").split("/");
77
83
  const segments = [];
@@ -83,6 +89,9 @@ function filePathToPattern(path) {
83
89
  }
84
90
  const isFile = idx === lastIndex;
85
91
  const name = isFile ? parse(part).name : part;
92
+ if (!isFile && isRouteGroup(name)) {
93
+ continue;
94
+ }
86
95
  if (isFile && name === "index") {
87
96
  continue;
88
97
  }
@@ -177,9 +186,11 @@ function buildRouteMatcher(routes) {
177
186
  return null;
178
187
  };
179
188
  }
180
- var DYNAMIC_PARAMETER_NAME_RE, REGEX_META_CHARS_RE;
189
+ var DYNAMIC_PARAMETER_NAME_RE, ROUTE_GROUP_RE, DYNAMIC_ROUTE_SEGMENT_RE, REGEX_META_CHARS_RE;
181
190
  var init_patterns = __esm(() => {
182
191
  DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
192
+ ROUTE_GROUP_RE = /^\([^()]+\)$/;
193
+ DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
183
194
  REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
184
195
  });
185
196
 
@@ -6725,11 +6736,11 @@ import { parseArgs } from "util";
6725
6736
 
6726
6737
  // src/build/index.ts
6727
6738
  import { existsSync as existsSync14, writeFileSync as writeFileSync10 } from "fs";
6728
- import { join as join15, relative as relative10, resolve as resolve12 } from "path";
6739
+ import { join as join16, relative as relative10, resolve as resolve12 } from "path";
6729
6740
 
6730
6741
  // src/adapter/bun.ts
6731
6742
  import { existsSync as existsSync9, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
6732
- import { join as join10, resolve as resolve9 } from "path";
6743
+ import { join as join11, resolve as resolve9 } from "path";
6733
6744
 
6734
6745
  // src/build/bun-build.ts
6735
6746
  function runBunBuild(config) {
@@ -6978,11 +6989,16 @@ function prepareCompileEntryApps(options) {
6978
6989
  }
6979
6990
 
6980
6991
  // src/build/elysia-aot.ts
6981
- import { dirname as dirname2, resolve } from "path";
6982
- import { aotFactory } from "elysia/plugin/aot/unplugin";
6992
+ import { dirname as dirname2, join as join4, resolve } from "path";
6993
+ import { fileURLToPath as fileURLToPath3 } from "url";
6994
+ import { Worker } from "worker_threads";
6983
6995
  var AOT_NAMESPACE = "furin-elysia-aot";
6984
6996
  var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
6997
+ var AOT_WORKER_PATH = join4(dirname2(dirname2(fileURLToPath3(import.meta.resolve("@teyik0/furin")))), "src/build/elysia-aot-worker.ts");
6985
6998
  var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
6999
+ var ELYSIA_IMPORT_FILTER = /^elysia(?:\/(?!compiled$|type$).*)?$/;
7000
+ var ELYSIA_VIRTUAL_IMPORT_FILTER = /^elysia\/(?:compiled|type)$/;
7001
+ var ANY_MODULE_FILTER = /.*/;
6986
7002
  var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
6987
7003
  function loaderFor(path) {
6988
7004
  const extension = path.slice(path.lastIndexOf("."));
@@ -7010,44 +7026,88 @@ export function handleWSResponse(){return e()}
7010
7026
  }
7011
7027
  function elysiaAot(entry) {
7012
7028
  const entryPath = resolve(entry);
7013
- const hooks = aotFactory({ entry, strip: false, target: "bun" });
7014
7029
  return {
7015
7030
  name: "elysia-aot",
7016
7031
  async setup(build) {
7032
+ const worker = new Worker(AOT_WORKER_PATH, { workerData: { entry: entryPath } });
7033
+ const pending = new Map;
7034
+ let nextId = 0;
7035
+ let workerFailure;
7036
+ const fail = (error) => {
7037
+ workerFailure = error;
7038
+ for (const request of pending.values()) {
7039
+ request.reject(error);
7040
+ }
7041
+ pending.clear();
7042
+ };
7043
+ worker.on("message", (response) => {
7044
+ const request = pending.get(response.id);
7045
+ pending.delete(response.id);
7046
+ if (response.ok) {
7047
+ request?.resolve(response);
7048
+ } else {
7049
+ request?.reject(response.error);
7050
+ }
7051
+ });
7052
+ worker.on("error", fail);
7053
+ worker.on("exit", (code) => fail(new Error(`[furin] Elysia AOT worker exited (${code}).`)));
7054
+ const request = (payload) => new Promise((resolveResponse, reject) => {
7055
+ if (workerFailure) {
7056
+ reject(workerFailure);
7057
+ return;
7058
+ }
7059
+ const id = nextId;
7060
+ nextId += 1;
7061
+ pending.set(id, { reject, resolve: resolveResponse });
7062
+ worker.postMessage({ ...payload, id });
7063
+ });
7064
+ let compiled;
7065
+ let virtualType;
7017
7066
  try {
7018
- await hooks.buildStart?.();
7067
+ ({ code: compiled, virtualType } = await request({ method: "start" }));
7019
7068
  } catch (error) {
7069
+ await worker.terminate();
7020
7070
  if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
7021
7071
  console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
7022
7072
  return;
7023
7073
  }
7024
7074
  throw error;
7025
7075
  }
7076
+ build.onEnd(async () => {
7077
+ try {
7078
+ await request({ method: "end" });
7079
+ } finally {
7080
+ await worker.terminate();
7081
+ }
7082
+ });
7026
7083
  const entrySource = await Bun.file(entryPath).text();
7027
- const transformedEntry = await hooks.transform?.(entrySource, entryPath);
7084
+ const { code: transformedEntry } = await request({
7085
+ code: entrySource,
7086
+ method: "transform",
7087
+ path: entryPath
7088
+ });
7028
7089
  if (transformedEntry !== undefined) {
7029
7090
  await Bun.write(entryPath, transformedEntry);
7030
7091
  }
7031
- build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
7092
+ build.onResolve({ filter: ELYSIA_IMPORT_FILTER }, ({ path }) => ({
7032
7093
  path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
7033
7094
  }));
7034
- build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
7035
- const resolved = hooks.resolveId?.(path);
7036
- return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
7095
+ build.onResolve({ filter: ELYSIA_VIRTUAL_IMPORT_FILTER }, ({ path }) => {
7096
+ if (path === "elysia/type" && virtualType === undefined) {
7097
+ return;
7098
+ }
7099
+ return { namespace: AOT_NAMESPACE, path };
7037
7100
  });
7038
- build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
7039
- const contents = hooks.load?.(path);
7101
+ build.onLoad({ filter: ANY_MODULE_FILTER, namespace: AOT_NAMESPACE }, ({ path }) => {
7102
+ const contents = path === "elysia/compiled" ? compiled : virtualType;
7040
7103
  return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
7041
7104
  });
7042
7105
  build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
7043
7106
  if (resolve(path) === entryPath) {
7044
7107
  return;
7045
7108
  }
7046
- if (hooks.transformInclude?.(path) === false) {
7047
- return;
7048
- }
7049
7109
  const original = await Bun.file(path).text();
7050
- const transformed = await hooks.transform?.(original, path);
7110
+ const { code: transformed } = await request({ code: original, method: "transform", path });
7051
7111
  if (transformed === undefined) {
7052
7112
  return;
7053
7113
  }
@@ -7056,23 +7116,20 @@ function elysiaAot(entry) {
7056
7116
  loader: loaderFor(path)
7057
7117
  };
7058
7118
  });
7059
- build.onEnd(() => {
7060
- hooks.buildEnd?.();
7061
- });
7062
7119
  }
7063
7120
  };
7064
7121
  }
7065
7122
 
7066
7123
  // src/build/private-server-sourcemaps.ts
7067
7124
  import { existsSync as existsSync4, renameSync } from "fs";
7068
- import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
7125
+ import { dirname as dirname3, isAbsolute, join as join5, relative as relative2 } from "path";
7069
7126
  function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
7070
7127
  for (const filename of filenames) {
7071
- const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
7128
+ const source = isAbsolute(filename) ? filename : join5(outputDir, filename);
7072
7129
  if (!existsSync4(source)) {
7073
7130
  continue;
7074
7131
  }
7075
- const destination = join4(privateDir, relative2(outputDir, source));
7132
+ const destination = join5(privateDir, relative2(outputDir, source));
7076
7133
  ensureDir(dirname3(destination));
7077
7134
  renameSync(source, destination);
7078
7135
  }
@@ -7137,7 +7194,7 @@ function productionInstrumentationPlugin() {
7137
7194
 
7138
7195
  // src/build/server-app-entry.ts
7139
7196
  import { writeFileSync } from "fs";
7140
- import { join as join6 } from "path";
7197
+ import { join as join7 } from "path";
7141
7198
 
7142
7199
  // src/plugin/routes.ts
7143
7200
  import {
@@ -7148,7 +7205,7 @@ import {
7148
7205
  statSync as statSync2,
7149
7206
  watch
7150
7207
  } from "fs";
7151
- import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute3, join as join5, relative as relative4, resolve as resolve4, sep } from "path";
7208
+ import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute3, join as join6, relative as relative4, resolve as resolve4, sep } from "path";
7152
7209
  import { pathToFileURL } from "url";
7153
7210
  import { Elysia } from "elysia";
7154
7211
 
@@ -7612,12 +7669,13 @@ function instanceNamespace(instance) {
7612
7669
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
7613
7670
  }
7614
7671
  function scanRouteFiles(directory, directorySegments, files) {
7615
- for (const entry of readdirSync2(directory, { withFileTypes: true })) {
7672
+ const entries = readdirSync2(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
7673
+ for (const entry of entries) {
7616
7674
  if (entry.isDirectory()) {
7617
7675
  if (entry.name.startsWith("_")) {
7618
7676
  continue;
7619
7677
  }
7620
- scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
7678
+ scanRouteFiles(join6(directory, entry.name), [...directorySegments, entry.name], files);
7621
7679
  continue;
7622
7680
  }
7623
7681
  const extension = extname2(entry.name);
@@ -7625,7 +7683,7 @@ function scanRouteFiles(directory, directorySegments, files) {
7625
7683
  continue;
7626
7684
  }
7627
7685
  const base = entry.name.slice(0, -extension.length);
7628
- const sourcePath = join5(directory, entry.name);
7686
+ const sourcePath = join6(directory, entry.name);
7629
7687
  for (const segment of [...directorySegments, base]) {
7630
7688
  parseDynamicRouteSegment(segment, sourcePath);
7631
7689
  }
@@ -7645,9 +7703,6 @@ function scanRouteFiles(directory, directorySegments, files) {
7645
7703
  function segmentPath(segment) {
7646
7704
  return routeSegmentToPattern(segment);
7647
7705
  }
7648
- function routePath(segments) {
7649
- return segments.length === 0 ? "/" : `/${segments.map(segmentPath).join("/")}`;
7650
- }
7651
7706
  function routeId(instanceId, path) {
7652
7707
  const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
7653
7708
  return `_route_${instanceId}_${encodedPath}`;
@@ -7676,14 +7731,22 @@ function buildRouteTree(pagesDir, instanceId) {
7676
7731
  return node;
7677
7732
  };
7678
7733
  const root = ensureNode([]);
7734
+ const seenPatterns = new Map;
7679
7735
  for (const file of scannedFiles) {
7680
7736
  const node = ensureNode(file.directorySegments);
7681
7737
  if (file.base === "_route") {
7682
- const path = `${routePath(file.directorySegments)}#layout`;
7738
+ const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
7683
7739
  node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
7684
7740
  continue;
7685
7741
  }
7686
- const path = file.base === "index" ? routePath(file.directorySegments) : routePath([...file.directorySegments, file.base]);
7742
+ const path = filePathToPattern(relative4(pagesDir, file.sourcePath));
7743
+ const patternKey = routePatternKey(path);
7744
+ const relativePath = relative4(pagesDir, file.sourcePath).replaceAll("\\", "/");
7745
+ const previousPath = seenPatterns.get(patternKey);
7746
+ if (previousPath !== undefined) {
7747
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
7748
+ }
7749
+ seenPatterns.set(patternKey, relativePath);
7687
7750
  const route = { id: routeId(instanceId, path), path, sourcePath: file.sourcePath };
7688
7751
  if (file.base === "index") {
7689
7752
  node.indexRoute = route;
@@ -7718,7 +7781,7 @@ function routeSourcePaths(instance) {
7718
7781
  }
7719
7782
  function emitRouteNode(node, indentation, includeRootCatchAll) {
7720
7783
  const childIndentation = `${indentation} `;
7721
- const prefix = node.name ? `/${segmentPath(node.name)}` : "";
7784
+ const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
7722
7785
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
7723
7786
  const content = [];
7724
7787
  if (node.indexRoute) {
@@ -7827,12 +7890,12 @@ function findPackageRoot(sourcePath) {
7827
7890
  const fallback = dirname6(sourcePath);
7828
7891
  let directory = fallback;
7829
7892
  while (dirname6(directory) !== directory) {
7830
- if (existsSync5(join5(directory, "package.json"))) {
7893
+ if (existsSync5(join6(directory, "package.json"))) {
7831
7894
  return directory;
7832
7895
  }
7833
7896
  directory = dirname6(directory);
7834
7897
  }
7835
- return existsSync5(join5(directory, "package.json")) ? directory : fallback;
7898
+ return existsSync5(join6(directory, "package.json")) ? directory : fallback;
7836
7899
  }
7837
7900
  function isWithinDirectory(path, directory) {
7838
7901
  const relativePath = relative4(directory, path);
@@ -7952,8 +8015,8 @@ function serverProxySource(instance, includeRootCatchAll) {
7952
8015
  function createRoutesPlugin(options) {
7953
8016
  const routeFilesBySpecifier = new Map;
7954
8017
  const routeFilesByResolvedPath = new Map;
7955
- const registryVirtualPath = join5(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
7956
- const composableRegistryVirtualPath = join5(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
8018
+ const registryVirtualPath = join6(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
8019
+ const composableRegistryVirtualPath = join6(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
7957
8020
  const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
7958
8021
  [
7959
8022
  routeModuleSpecifier(instance),
@@ -8034,11 +8097,11 @@ async function materializeServerAppEntry(options) {
8034
8097
  if (!instance) {
8035
8098
  throw new Error(`[furin] Missing route instance for server app ${index}.`);
8036
8099
  }
8037
- const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
8100
+ const routePath = join7(options.outDir, `_furin-routes-${index}.ts`);
8038
8101
  writeFileSync(routePath, await materializedRouteModuleSource(instance));
8039
8102
  return { ...app, nativeRoutes: toPosixPath(routePath) };
8040
8103
  }));
8041
- const entryPath = join6(options.outDir, "_furin-app.ts");
8104
+ const entryPath = join7(options.outDir, "_furin-app.ts");
8042
8105
  writeFileSync(entryPath, buildEntrySource({
8043
8106
  apps,
8044
8107
  headerComment: options.headerComment,
@@ -8068,7 +8131,7 @@ if (typeof startServer === "function") {
8068
8131
  init_transform_isomorphic();
8069
8132
 
8070
8133
  // src/rsc/build/environment.ts
8071
- import { fileURLToPath as fileURLToPath3 } from "url";
8134
+ import { fileURLToPath as fileURLToPath4 } from "url";
8072
8135
  var SERVER_ONLY_RE = /^(?:@teyik0\/)?furin\/server-only$/;
8073
8136
  var CLIENT_ONLY_RE = /^(?:@teyik0\/)?furin\/client-only$/;
8074
8137
  function environmentGuardPlugin(graph) {
@@ -8079,13 +8142,13 @@ function environmentGuardPlugin(graph) {
8079
8142
  if (graph === "client") {
8080
8143
  throw new Error(`[furin] ${args.importer} imports furin/server-only from the client graph.`);
8081
8144
  }
8082
- return { path: fileURLToPath3(import.meta.resolve("../../server-only.ts")) };
8145
+ return { path: fileURLToPath4(import.meta.resolve("../../server-only.ts")) };
8083
8146
  });
8084
8147
  build.onResolve({ filter: CLIENT_ONLY_RE }, (args) => {
8085
8148
  if (graph !== "client") {
8086
8149
  throw new Error(`[furin] ${args.importer} imports furin/client-only from the ${graph} graph.`);
8087
8150
  }
8088
- return { path: fileURLToPath3(import.meta.resolve("../../client-only.ts")) };
8151
+ return { path: fileURLToPath4(import.meta.resolve("../../client-only.ts")) };
8089
8152
  });
8090
8153
  }
8091
8154
  };
@@ -8118,12 +8181,12 @@ function assertNoPrefixSlugCollisions(prefixes) {
8118
8181
 
8119
8182
  // src/adapter/runtime-build.ts
8120
8183
  import { existsSync as existsSync8, realpathSync as realpathSync4, writeFileSync as writeFileSync5 } from "fs";
8121
- import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute5, join as join9, relative as relative6, resolve as resolve8 } from "path";
8122
- import { fileURLToPath as fileURLToPath5 } from "url";
8184
+ import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute5, join as join10, relative as relative6, resolve as resolve8 } from "path";
8185
+ import { fileURLToPath as fileURLToPath6 } from "url";
8123
8186
 
8124
8187
  // src/build/client.ts
8125
8188
  import { existsSync as existsSync7, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
8126
- import { basename as basename3, dirname as dirname9, join as join7, resolve as resolve7 } from "path";
8189
+ import { basename as basename3, dirname as dirname9, join as join8, resolve as resolve7 } from "path";
8127
8190
 
8128
8191
  // src/plugin/transform-client.ts
8129
8192
  init_dist();
@@ -9025,6 +9088,7 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
9025
9088
  // src/build/hydrate.ts
9026
9089
  init_patterns();
9027
9090
  function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
9091
+ const rootDirectory = rootLayout.replaceAll("\\", "/").split("/").slice(0, -1).join("/");
9028
9092
  const getBoundaryIdent = (idents, filePath) => {
9029
9093
  if (!filePath) {
9030
9094
  return;
@@ -9065,6 +9129,9 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
9065
9129
  if (notFoundIdent) {
9066
9130
  parts.push(`notFound: ${notFoundIdent}.default`);
9067
9131
  }
9132
+ if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
9133
+ parts.push("isRoot: false");
9134
+ }
9068
9135
  boundaryLiterals.push(`{ ${parts.join(", ")} }`);
9069
9136
  }
9070
9137
  const lazyImports = [
@@ -9474,7 +9541,7 @@ async function buildClient(routes, {
9474
9541
  pagesDir
9475
9542
  }) {
9476
9543
  const dirName = clientDirName ?? "client";
9477
- const clientDir = join7(outDir, dirName);
9544
+ const clientDir = join8(outDir, dirName);
9478
9545
  if (!existsSync7(outDir)) {
9479
9546
  mkdirSync2(outDir, { recursive: true });
9480
9547
  }
@@ -9482,7 +9549,7 @@ async function buildClient(routes, {
9482
9549
  mkdirSync2(clientDir, { recursive: true });
9483
9550
  }
9484
9551
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
9485
- const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
9552
+ const hydratePath = join8(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
9486
9553
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
9487
9554
  console.log("[furin] Building production client bundle\u2026");
9488
9555
  const transformPlugin = {
@@ -13589,17 +13656,23 @@ function buildElement(route, data, rootLayout) {
13589
13656
  const byDepth = new Map;
13590
13657
  const legacyRoute = route;
13591
13658
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
13592
- byDepth.set(segment.depth, segment);
13659
+ const boundaries = byDepth.get(segment.depth) ?? [];
13660
+ boundaries.unshift(segment);
13661
+ byDepth.set(segment.depth, boundaries);
13593
13662
  }
13594
13663
  for (let i = route.routeChain.length - 1;i >= 1; i -= 1) {
13595
- element = wrapSegmentBoundaries(element, byDepth.get(i), undefined);
13664
+ for (const segment of byDepth.get(i) ?? []) {
13665
+ element = wrapSegmentBoundaries(element, segment, undefined);
13666
+ }
13596
13667
  const routeEntry = route.routeChain[i];
13597
13668
  if (routeEntry?.layout) {
13598
13669
  const Layout = routeEntry.layout;
13599
13670
  element = createElement6(Layout, data, element);
13600
13671
  }
13601
13672
  }
13602
- element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
13673
+ for (const segment of byDepth.get(0) ?? []) {
13674
+ element = wrapSegmentBoundaries(element, segment, undefined);
13675
+ }
13603
13676
  if (rootLayout.layout) {
13604
13677
  const RootLayoutComponent = rootLayout.layout;
13605
13678
  element = createElement6(RootLayoutComponent, data, element);
@@ -15096,7 +15169,7 @@ var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
15096
15169
  function hasRequestDependentInput(route, root) {
15097
15170
  return [root.route, ...route.routeChain].some((routeConfig) => routeConfig.query !== undefined);
15098
15171
  }
15099
- async function buildRoutePrerenders(routes, root, origin, basePath) {
15172
+ async function buildRoutePrerenders(routes, root, origin, basePath, deferRendering) {
15100
15173
  const prerenders = [];
15101
15174
  const searchRoutes = createSearchRouteMetadata(routes);
15102
15175
  const matchRoute = buildRouteMatcher(routes);
@@ -15121,7 +15194,7 @@ async function buildRoutePrerenders(routes, root, origin, basePath) {
15121
15194
  if (matchRoute(path)?.route !== route) {
15122
15195
  continue;
15123
15196
  }
15124
- if (root.route.requestLoader !== undefined || hasRequestLoader(route)) {
15197
+ if (deferRendering || root.route.requestLoader !== undefined || hasRequestLoader(route)) {
15125
15198
  prerenders.push({ path, route });
15126
15199
  continue;
15127
15200
  }
@@ -15151,8 +15224,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
15151
15224
 
15152
15225
  // src/rsc/build/index.ts
15153
15226
  import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
15154
- import { basename as basename4, join as join8 } from "path";
15155
- import { fileURLToPath as fileURLToPath4 } from "url";
15227
+ import { basename as basename4, join as join9 } from "path";
15228
+ import { fileURLToPath as fileURLToPath5 } from "url";
15156
15229
  init_transform_isomorphic();
15157
15230
 
15158
15231
  // src/rsc/version.ts
@@ -15201,9 +15274,9 @@ function assertInstalledRscVersions() {
15201
15274
  // src/rsc/build/index.ts
15202
15275
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
15203
15276
  await assertInstalledRscVersions();
15204
- const graphDir = join8(outDir, "rsc");
15277
+ const graphDir = join9(outDir, "rsc");
15205
15278
  mkdirSync3(graphDir, { recursive: true });
15206
- const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
15279
+ const rscEntry = fileURLToPath5(import.meta.resolve("../../rsc-server.tsx"));
15207
15280
  const entrypoints = [
15208
15281
  ...new Set(apps.flatMap(({ root, routes }) => [
15209
15282
  root.path,
@@ -15243,7 +15316,7 @@ ${result.logs.map((log) => log.message).join(`
15243
15316
  `)}`);
15244
15317
  }
15245
15318
  const codecResult = await runBunBuild({
15246
- entrypoints: [fileURLToPath4(import.meta.resolve("../server-codec.ts"))],
15319
+ entrypoints: [fileURLToPath5(import.meta.resolve("../server-codec.ts"))],
15247
15320
  outdir: outDir,
15248
15321
  target: "bun",
15249
15322
  format: "esm",
@@ -15263,14 +15336,14 @@ ${codecResult.logs.map((log) => log.message).join(`
15263
15336
  }
15264
15337
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename4(output.path)}` }));
15265
15338
  const manifest = { buildId, clientReferences: [], css };
15266
- writeFileSync4(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
15339
+ writeFileSync4(join9(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
15267
15340
  return manifest;
15268
15341
  }
15269
15342
 
15270
15343
  // src/adapter/runtime-build.ts
15271
15344
  init_patterns();
15272
- var _pkgRoot2 = dirname11(dirname11(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
15273
- var _pkgSrcDir2 = existsSync8(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
15345
+ var _pkgRoot2 = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
15346
+ var _pkgSrcDir2 = existsSync8(join10(_pkgRoot2, "src", "furin.ts")) ? join10(_pkgRoot2, "src") : join10(_pkgRoot2, "dist");
15274
15347
  var _ext2 = ".ts";
15275
15348
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
15276
15349
  var MIXED_CACHE_IMPORT_RE = /mixed-cache(?:\.ts)?$/;
@@ -15421,8 +15494,8 @@ function buildCompileMetadata(root, routes) {
15421
15494
  function pprRuntimePlugin(apps) {
15422
15495
  const enabled = apps.some((app) => app.routes.some((route) => resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
15423
15496
  const pprPath = resolve8(_pkgSrcDir2, "server/render/ppr-route.ts");
15424
- const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
15425
- const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
15497
+ const reactServerPath = fileURLToPath6(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
15498
+ const reactStaticPath = fileURLToPath6(import.meta.resolve("react-dom/static.edge"));
15426
15499
  return {
15427
15500
  name: "furin-ppr-runtime",
15428
15501
  setup(build) {
@@ -15488,7 +15561,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
15488
15561
  basePath: prefix,
15489
15562
  clientDirName,
15490
15563
  clientLogging: options.clientLogging ?? false,
15491
- metafilePath: options.analyze ? join9(dirname11(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
15564
+ metafilePath: options.analyze ? join10(dirname11(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
15492
15565
  optimizeImports: options.optimizeImports,
15493
15566
  outDir: targetDir,
15494
15567
  pagesDir: app.pagesDir,
@@ -15501,9 +15574,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
15501
15574
  const buildFingerprint = await createBuildFingerprint(`${prefix}
15502
15575
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
15503
15576
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
15504
- const clientDir = join9(targetDir, clientDirName);
15577
+ const clientDir = join10(targetDir, clientDirName);
15505
15578
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
15506
- writeFileSync5(join9(clientDir, "index.html"), indexHtml);
15579
+ writeFileSync5(join10(clientDir, "index.html"), indexHtml);
15507
15580
  setProductionTemplateContent(indexHtml);
15508
15581
  setProductionPreloadManifest(preloadManifest);
15509
15582
  ssgRouteCache().clear();
@@ -15511,7 +15584,7 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
15511
15584
  let prerenders = [];
15512
15585
  if (serverEntry) {
15513
15586
  if (targetName === "vercel") {
15514
- prerenders = await buildRoutePrerenders(routes, root, "http://localhost", prefix);
15587
+ prerenders = await buildRoutePrerenders(routes, root, "http://localhost", prefix, true);
15515
15588
  } else {
15516
15589
  ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
15517
15590
  }
@@ -15565,7 +15638,7 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
15565
15638
  // src/adapter/bun.ts
15566
15639
  function generateBootEntry(appEntry, outDir, filename) {
15567
15640
  ensureDir(outDir);
15568
- const entryPath = join10(outDir, filename);
15641
+ const entryPath = join11(outDir, filename);
15569
15642
  return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
15570
15643
  }
15571
15644
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
@@ -15588,7 +15661,7 @@ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
15588
15661
  if (!enabled) {
15589
15662
  return;
15590
15663
  }
15591
- movePrivateServerSourceMaps(targetDir, join10(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
15664
+ movePrivateServerSourceMaps(targetDir, join11(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
15592
15665
  }
15593
15666
  function writeServerMetafile(build, analyze, buildRoot) {
15594
15667
  if (!analyze) {
@@ -15597,9 +15670,9 @@ function writeServerMetafile(build, analyze, buildRoot) {
15597
15670
  if (build.metafile === undefined) {
15598
15671
  throw new Error("[furin] Bun server build did not produce the requested metafile.");
15599
15672
  }
15600
- const analysisDir = join10(buildRoot, "analysis");
15673
+ const analysisDir = join11(buildRoot, "analysis");
15601
15674
  ensureDir(analysisDir);
15602
- const metafilePath = join10(analysisDir, "bun-server.json");
15675
+ const metafilePath = join11(analysisDir, "bun-server.json");
15603
15676
  writeFileSync6(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
15604
15677
  `);
15605
15678
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
@@ -15609,7 +15682,7 @@ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
15609
15682
  return;
15610
15683
  }
15611
15684
  for (const app of apps) {
15612
- rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
15685
+ rmSync2(join11(targetDir, clientDirNameForPrefix(app.prefix)), {
15613
15686
  force: true,
15614
15687
  recursive: true
15615
15688
  });
@@ -15632,7 +15705,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
15632
15705
  ...context.extraContext ?? [],
15633
15706
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
15634
15707
  ],
15635
- templateHtml: readFileSync6(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
15708
+ templateHtml: readFileSync6(join11(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
15636
15709
  }));
15637
15710
  return await materializeServerAppEntry({
15638
15711
  apps: contexts,
@@ -15653,25 +15726,25 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
15653
15726
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
15654
15727
  const targetDir = resolve9(rootDir, targetManifest.targetDir);
15655
15728
  rmSync2(targetDir, { force: true, recursive: true });
15656
- rmSync2(join10(buildRoot, "private", "server-sourcemaps", "bun"), {
15729
+ rmSync2(join11(buildRoot, "private", "server-sourcemaps", "bun"), {
15657
15730
  force: true,
15658
15731
  recursive: true
15659
15732
  });
15660
15733
  ensureDir(targetDir);
15661
- const publicDir = existsSync9(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
15734
+ const publicDir = existsSync9(join11(rootDir, "public")) ? join11(rootDir, "public") : undefined;
15662
15735
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
15663
15736
  targetManifest.buildId = headlineBuildId;
15664
15737
  if (serverEntry) {
15665
- targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
15738
+ targetManifest.rscManifestPath = toPosixPath(join11(targetManifest.targetDir, "rsc", "manifest.json"));
15666
15739
  }
15667
- const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
15740
+ const targetPublicDir = publicDir ? join11(targetDir, "public") : undefined;
15668
15741
  if (publicDir && targetPublicDir && options.compile !== "embed") {
15669
15742
  copyDirRecursive(publicDir, targetPublicDir);
15670
15743
  }
15671
15744
  const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
15672
15745
  if (options.compile && serverEntry && appEntry) {
15673
15746
  const serverFilename = compiledServerFilename(process.platform);
15674
- const outfile = join10(targetDir, serverFilename);
15747
+ const outfile = join11(targetDir, serverFilename);
15675
15748
  const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
15676
15749
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
15677
15750
  const serverBuild = await runBunBuild({
@@ -15701,7 +15774,7 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
15701
15774
  relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
15702
15775
  writeServerMetafile(serverBuild, options.analyze, buildRoot);
15703
15776
  console.log(`[furin] Server binary: ${outfile}`);
15704
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, serverFilename));
15777
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, serverFilename));
15705
15778
  finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
15706
15779
  } else if (serverEntry && appEntry) {
15707
15780
  const entry = generateBootEntry(appEntry, targetDir, "server.ts");
@@ -15728,26 +15801,26 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
15728
15801
  });
15729
15802
  relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
15730
15803
  writeServerMetafile(serverBuild, options.analyze, buildRoot);
15731
- console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
15732
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
15804
+ console.log(`[furin] Server bundle: ${toPosixPath(join11(targetManifest.targetDir, "server.js"))}`);
15805
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, "server.js"));
15733
15806
  }
15734
15807
  return targetManifest;
15735
15808
  }
15736
15809
 
15737
15810
  // src/adapter/package.ts
15738
15811
  import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
15739
- import { join as join11, relative as relative7, resolve as resolve10 } from "path";
15812
+ import { join as join12, relative as relative7, resolve as resolve10 } from "path";
15740
15813
  init_transform_isomorphic();
15741
15814
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
15742
15815
  const { prefix, root, routes, pagesDir } = app;
15743
15816
  const modulePaths = routeSourcePaths(app);
15744
- const targetDir = join11(buildRoot, "package");
15817
+ const targetDir = join12(buildRoot, "package");
15745
15818
  rmSync3(targetDir, { force: true, recursive: true });
15746
15819
  ensureDir(targetDir);
15747
15820
  const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
15748
15821
  basePath: prefix,
15749
15822
  clientLogging: options.clientLogging ?? false,
15750
- metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
15823
+ metafilePath: options.analyze ? join12(buildRoot, "analysis", "package-client.json") : undefined,
15751
15824
  optimizeImports: options.optimizeImports,
15752
15825
  outDir: targetDir,
15753
15826
  pagesDir,
@@ -15760,13 +15833,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
15760
15833
  const buildFingerprint = await createBuildFingerprint(`${prefix}
15761
15834
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
15762
15835
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
15763
- const clientDir = join11(targetDir, "client");
15764
- const publicDir = join11(rootDir, "public");
15836
+ const clientDir = join12(targetDir, "client");
15837
+ const publicDir = join12(rootDir, "public");
15765
15838
  if (existsSync10(publicDir)) {
15766
- copyDirRecursive(publicDir, join11(targetDir, "public"));
15839
+ copyDirRecursive(publicDir, join12(targetDir, "public"));
15767
15840
  }
15768
15841
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
15769
- writeFileSync7(join11(clientDir, "index.html"), indexHtml);
15842
+ writeFileSync7(join12(clientDir, "index.html"), indexHtml);
15770
15843
  setProductionTemplateContent(indexHtml);
15771
15844
  setProductionPreloadManifest(preloadManifest);
15772
15845
  ssgRouteCache().clear();
@@ -15807,7 +15880,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
15807
15880
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
15808
15881
  mode: "register"
15809
15882
  });
15810
- const registerEntry = join11(targetDir, "register.ts");
15883
+ const registerEntry = join12(targetDir, "register.ts");
15811
15884
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
15812
15885
  const result = await runBunBuild({
15813
15886
  entrypoints: [register.entrypoint],
@@ -15856,7 +15929,7 @@ export function createFurinApp(options = {}) {
15856
15929
 
15857
15930
  export const prefix = ${JSON.stringify(prefix)};
15858
15931
  `;
15859
- writeFileSync7(join11(targetDir, "index.js"), factorySource);
15932
+ writeFileSync7(join12(targetDir, "index.js"), factorySource);
15860
15933
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
15861
15934
 
15862
15935
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -15864,7 +15937,7 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
15864
15937
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
15865
15938
  export declare const prefix: string;
15866
15939
  `;
15867
- writeFileSync7(join11(targetDir, "index.d.ts"), dtsSource);
15940
+ writeFileSync7(join12(targetDir, "index.d.ts"), dtsSource);
15868
15941
  console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
15869
15942
  return {
15870
15943
  buildId,
@@ -15876,7 +15949,7 @@ export declare const prefix: string;
15876
15949
 
15877
15950
  // src/adapter/static.ts
15878
15951
  import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
15879
- import { dirname as dirname12, isAbsolute as isAbsolute6, join as join12, parse as parse3, relative as relative8, resolve as resolve11, sep as sep2, win32 } from "path";
15952
+ import { dirname as dirname12, isAbsolute as isAbsolute6, join as join13, parse as parse3, relative as relative8, resolve as resolve11, sep as sep2, win32 } from "path";
15880
15953
  init_patterns();
15881
15954
  var STATIC_CONCURRENCY = 4;
15882
15955
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
@@ -15885,7 +15958,7 @@ var STATIC_RENDER_ORIGIN = "http://localhost";
15885
15958
  function pathToOutputFile(urlPath, outDir, fileName) {
15886
15959
  const normalizedOutDir = resolve11(outDir);
15887
15960
  if (urlPath === "/" || urlPath === "") {
15888
- return join12(normalizedOutDir, fileName);
15961
+ return join13(normalizedOutDir, fileName);
15889
15962
  }
15890
15963
  const resolved = resolve11(normalizedOutDir, urlPath.slice(1), fileName);
15891
15964
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
@@ -16106,13 +16179,13 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
16106
16179
  const afterQueueCount = skippedRoutes.length;
16107
16180
  rmSync4(outDir, { force: true, recursive: true });
16108
16181
  ensureDir(outDir);
16109
- const targetDir = join12(buildRoot, "static");
16182
+ const targetDir = join13(buildRoot, "static");
16110
16183
  rmSync4(targetDir, { force: true, recursive: true });
16111
16184
  ensureDir(targetDir);
16112
16185
  const { entryChunk, cssChunks, preloadManifest } = await buildClient(ssgRoutes, {
16113
16186
  basePath,
16114
16187
  clientLogging: Boolean(options.clientLogging),
16115
- metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
16188
+ metafilePath: options.analyze ? join13(buildRoot, "analysis", "static-client.json") : undefined,
16116
16189
  optimizeImports: options.optimizeImports,
16117
16190
  outDir: targetDir,
16118
16191
  pagesDir: dirname12(root.path),
@@ -16122,22 +16195,22 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
16122
16195
  reactCompiler: options.reactCompiler,
16123
16196
  rootLayout: root.path
16124
16197
  });
16125
- const publicFavicon = join12(rootDir, "public", "favicon.ico");
16198
+ const publicFavicon = join13(rootDir, "public", "favicon.ico");
16126
16199
  const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
16127
16200
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
16128
16201
  setProductionTemplateContent(shellHtml);
16129
16202
  setProductionPreloadManifest(preloadManifest);
16130
- const publicSrcDir = join12(rootDir, "public");
16203
+ const publicSrcDir = join13(rootDir, "public");
16131
16204
  if (existsSync11(publicSrcDir)) {
16132
16205
  cpSync2(publicSrcDir, outDir, { recursive: true });
16133
16206
  }
16134
- const clientSrcDir = join12(targetDir, "client");
16207
+ const clientSrcDir = join13(targetDir, "client");
16135
16208
  if (existsSync11(clientSrcDir)) {
16136
- cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
16209
+ cpSync2(clientSrcDir, join13(outDir, "_client"), { recursive: true });
16137
16210
  }
16138
16211
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
16139
16212
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
16140
- writeFileSync8(join12(outDir, "404.html"), shellHtml);
16213
+ writeFileSync8(join13(outDir, "404.html"), shellHtml);
16141
16214
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
16142
16215
  rmSync4(targetDir, { force: true, recursive: true });
16143
16216
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -16152,8 +16225,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
16152
16225
 
16153
16226
  // src/adapter/vercel.ts
16154
16227
  import { cpSync as cpSync3, existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync9 } from "fs";
16155
- import { basename as basename6, dirname as dirname13, extname as extname3, join as join13, relative as relative9 } from "path";
16156
- import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
16228
+ import { basename as basename6, dirname as dirname13, extname as extname3, join as join14, relative as relative9 } from "path";
16229
+ import { fileURLToPath as fileURLToPath7, pathToFileURL as pathToFileURL2 } from "url";
16157
16230
  init_transform_isomorphic();
16158
16231
  init_patterns();
16159
16232
  var ISR_PATH_PARAM = "__furin_path";
@@ -16162,7 +16235,7 @@ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
16162
16235
  var MATCH_ALL_RE = /.*/;
16163
16236
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
16164
16237
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
16165
- var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
16238
+ var VERCEL_FUNCTIONS_PATH = fileURLToPath7(import.meta.resolve("@vercel/functions"));
16166
16239
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
16167
16240
  var FURIN_RUNTIME_ROOT2 = dirname13(import.meta.dir);
16168
16241
  function isFurinRuntimeImporter(importer) {
@@ -16195,8 +16268,8 @@ function vercelRuntimePlugin() {
16195
16268
  };
16196
16269
  }
16197
16270
  function frameworkVersion() {
16198
- const packageRoot = dirname13(dirname13(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
16199
- const packageJson = JSON.parse(readFileSync7(join13(packageRoot, "package.json"), "utf8"));
16271
+ const packageRoot = dirname13(dirname13(fileURLToPath7(import.meta.resolve("@teyik0/furin"))));
16272
+ const packageJson = JSON.parse(readFileSync7(join14(packageRoot, "package.json"), "utf8"));
16200
16273
  return packageJson.version;
16201
16274
  }
16202
16275
  function serverEntryLoader(serverEntry) {
@@ -16312,7 +16385,7 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
16312
16385
  body = result.html;
16313
16386
  ({ status } = result);
16314
16387
  }
16315
- const fallbackPath = join13(dirname13(join13(functionsDir, spec.functionName)), fallback);
16388
+ const fallbackPath = join14(dirname13(join14(functionsDir, spec.functionName)), fallback);
16316
16389
  ensureDir(dirname13(fallbackPath));
16317
16390
  writeFileSync9(fallbackPath, body);
16318
16391
  spec.config.fallback = fallback;
@@ -16325,7 +16398,7 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
16325
16398
  spec.config.initialStatus = status;
16326
16399
  }
16327
16400
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
16328
- const aliasPath = join13(functionsDir, `${functionName}.func`);
16401
+ const aliasPath = join14(functionsDir, `${functionName}.func`);
16329
16402
  ensureDir(dirname13(aliasPath));
16330
16403
  const target = relative9(dirname13(aliasPath), serverFunctionDir);
16331
16404
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
@@ -16538,26 +16611,26 @@ export { initialization };
16538
16611
  export default { fetch: handle };
16539
16612
  `;
16540
16613
  }
16541
- async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, targetDir) {
16614
+ async function buildProductionFallbacks(apps, builds, specs, functionsDir, rootDir, targetDir) {
16542
16615
  const jobs = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.result === undefined).map((prerender) => {
16543
16616
  const path = physicalPath(apps[index].prefix, prerender.path);
16544
- const spec = specs.find((candidate) => candidate.config.chain !== undefined && new RegExp(`^(?:${candidate.source})$`).test(path));
16617
+ const spec = specs.find((candidate) => new RegExp(`^(?:${candidate.source})$`).test(path));
16545
16618
  if (!spec) {
16546
- throw new Error(`[furin] Missing PPR build target for ${path}`);
16619
+ throw new Error(`[furin] Missing prerender build target for ${path}`);
16547
16620
  }
16548
16621
  return { path, prerender, spec };
16549
16622
  }));
16550
16623
  if (jobs.length === 0) {
16551
16624
  return;
16552
16625
  }
16553
- const resultPath = join13(targetDir, "ppr-results.json");
16626
+ const resultPath = join14(targetDir, "prerender-results.json");
16554
16627
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
16555
16628
  const script = `
16556
- const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
16629
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join14(functionsDir, "__server.func/index.js")).href)})).default;
16557
16630
  const results = [];
16558
- for (const url of ${JSON.stringify(requests)}) {
16631
+ for (const [index, url] of ${JSON.stringify(requests)}.entries()) {
16559
16632
  const response = await handler.fetch(new Request(url));
16560
- if (response.status >= 400) throw new Error("PPR build failed for " + url + ": HTTP " + response.status);
16633
+ if (response.status >= 500 || (response.status >= 400 && ${JSON.stringify(jobs.map(({ spec }) => spec.config.chain !== undefined))}[index])) throw new Error("Production prerender failed for " + url + ": HTTP " + response.status);
16561
16634
  results.push({ body: await response.text(), headers: Object.fromEntries(response.headers), status: response.status });
16562
16635
  }
16563
16636
  await Bun.write(${JSON.stringify(resultPath)}, JSON.stringify(results));
@@ -16576,7 +16649,7 @@ process.exit(0);
16576
16649
  new Response(child.stderr).text()
16577
16650
  ]);
16578
16651
  if (exitCode !== 0) {
16579
- throw new Error(`[furin] PPR production prerender failed:
16652
+ throw new Error(`[furin] Production prerender failed:
16580
16653
  ${stderr}
16581
16654
  ${stdout}`);
16582
16655
  }
@@ -16662,13 +16735,13 @@ export default { fetch: handle };
16662
16735
  }
16663
16736
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
16664
16737
  assertDefaultServerExport(serverEntry);
16665
- const targetDir = join13(buildRoot, "vercel");
16666
- const outputDir = join13(rootDir, ".vercel", "output");
16667
- const staticDir = join13(outputDir, "static");
16668
- const functionsDir = join13(outputDir, "functions");
16669
- const serverFunctionDir = join13(functionsDir, "__server.func");
16738
+ const targetDir = join14(buildRoot, "vercel");
16739
+ const outputDir = join14(rootDir, ".vercel", "output");
16740
+ const staticDir = join14(outputDir, "static");
16741
+ const functionsDir = join14(outputDir, "functions");
16742
+ const serverFunctionDir = join14(functionsDir, "__server.func");
16670
16743
  rmSync5(targetDir, { force: true, recursive: true });
16671
- rmSync5(join13(buildRoot, "private", "server-sourcemaps", "vercel"), {
16744
+ rmSync5(join14(buildRoot, "private", "server-sourcemaps", "vercel"), {
16672
16745
  force: true,
16673
16746
  recursive: true
16674
16747
  });
@@ -16677,24 +16750,24 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
16677
16750
  ensureDir(staticDir);
16678
16751
  ensureDir(serverFunctionDir);
16679
16752
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
16680
- cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
16681
- const publicDir = join13(rootDir, "public");
16753
+ cpSync3(join14(targetDir, "server-codec.js"), join14(serverFunctionDir, "server-codec.js"));
16754
+ const publicDir = join14(rootDir, "public");
16682
16755
  if (existsSync12(publicDir)) {
16683
16756
  cpSync3(publicDir, staticDir, { recursive: true });
16684
16757
  for (const app of apps) {
16685
- const appStaticDir = join13(staticDir, app.prefix.slice(1));
16686
- const appPublicDir = join13(appStaticDir, "public");
16758
+ const appStaticDir = join14(staticDir, app.prefix.slice(1));
16759
+ const appPublicDir = join14(appStaticDir, "public");
16687
16760
  cpSync3(publicDir, appPublicDir, { recursive: true });
16688
- const favicon = join13(publicDir, "favicon.ico");
16761
+ const favicon = join14(publicDir, "favicon.ico");
16689
16762
  if (app.prefix !== "" && existsSync12(favicon)) {
16690
- cpSync3(favicon, join13(appStaticDir, "favicon.ico"));
16763
+ cpSync3(favicon, join14(appStaticDir, "favicon.ico"));
16691
16764
  }
16692
16765
  }
16693
16766
  }
16694
16767
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
16695
16768
  const app = apps[appIndex];
16696
16769
  const build = builds[appIndex];
16697
- const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
16770
+ const clientOutputDir = join14(staticDir, app.prefix.slice(1), "_client");
16698
16771
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
16699
16772
  }
16700
16773
  const pprResumeKey = crypto.randomUUID();
@@ -16713,7 +16786,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
16713
16786
  serverEntry
16714
16787
  })
16715
16788
  ]);
16716
- const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
16789
+ const entryPath = join14(serverFunctionDir, "_vercel-handler.ts");
16717
16790
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
16718
16791
  const serverBuild = await runBunBuild({
16719
16792
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
@@ -16741,22 +16814,22 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
16741
16814
  target: "bun"
16742
16815
  });
16743
16816
  if (options.serverSourceMaps) {
16744
- movePrivateServerSourceMaps(serverFunctionDir, join13(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
16817
+ movePrivateServerSourceMaps(serverFunctionDir, join14(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
16745
16818
  }
16746
16819
  if (options.analyze) {
16747
16820
  if (serverBuild.metafile === undefined) {
16748
16821
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
16749
16822
  }
16750
- const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
16823
+ const metafilePath = join14(buildRoot, "analysis", "vercel-server.json");
16751
16824
  ensureDir(dirname13(metafilePath));
16752
16825
  writeFileSync9(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
16753
16826
  `);
16754
16827
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
16755
16828
  }
16756
16829
  const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
16757
- writeFileSync9(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
16758
- await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
16759
- writeFileSync9(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
16830
+ writeFileSync9(join14(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
16831
+ await buildProductionFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
16832
+ writeFileSync9(join14(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
16760
16833
  handler: "index.js",
16761
16834
  launcherType: "Nodejs",
16762
16835
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -16767,7 +16840,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
16767
16840
  `);
16768
16841
  for (const spec of prerenderSpecs) {
16769
16842
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
16770
- writeFileSync9(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
16843
+ writeFileSync9(join14(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
16771
16844
  `);
16772
16845
  }
16773
16846
  const assetRoutes = apps.map((app) => ({
@@ -16797,7 +16870,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
16797
16870
  ],
16798
16871
  version: 3
16799
16872
  };
16800
- writeFileSync9(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
16873
+ writeFileSync9(join14(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
16801
16874
  `);
16802
16875
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => resolveDocumentMode(prerender.route) === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
16803
16876
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => resolveDocumentMode(route) === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
@@ -16876,7 +16949,7 @@ init_instance();
16876
16949
  // src/server/router/discovery.ts
16877
16950
  import { existsSync as existsSync13 } from "fs";
16878
16951
  import { readdir } from "fs/promises";
16879
- import { join as join14, parse as parse4 } from "path";
16952
+ import { join as join15, parse as parse4 } from "path";
16880
16953
 
16881
16954
  // src/server/internal.ts
16882
16955
  var _compileContexts = new Map;
@@ -17056,10 +17129,6 @@ async function scanRootLayout(pagesDir) {
17056
17129
  }
17057
17130
  var CONVENTION_FILE_NAMES = ["not-found", "error"];
17058
17131
  var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
17059
- var DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
17060
- function routePatternKey(pattern) {
17061
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
17062
- }
17063
17132
  function isConventionFileName(name) {
17064
17133
  return CONVENTION_FILE_NAMES.includes(name);
17065
17134
  }
@@ -17108,7 +17177,7 @@ async function scanPageFiles(pagesDir, root) {
17108
17177
  const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
17109
17178
  devRoute.notFound = notFound;
17110
17179
  devRoute.error = errorComponent;
17111
- devRoute.segmentBoundaries = segmentBoundaries;
17180
+ devRoute.segmentBoundaries = alignSegmentBoundaryDepths(segmentBoundaries, devRoute.routeChain);
17112
17181
  routes.push(devRoute);
17113
17182
  continue;
17114
17183
  }
@@ -17128,7 +17197,7 @@ async function scanPageFiles(pagesDir, root) {
17128
17197
  path: absolutePath,
17129
17198
  pattern,
17130
17199
  routeChain,
17131
- segmentBoundaries,
17200
+ segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
17132
17201
  tags: collectRouteTags(routeChain, page)
17133
17202
  });
17134
17203
  }
@@ -17166,6 +17235,21 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
17166
17235
  }
17167
17236
  return parent;
17168
17237
  }
17238
+ function alignSegmentBoundaryDepths(boundaries, routeChain) {
17239
+ return boundaries.map((boundary) => {
17240
+ let depth = 0;
17241
+ for (const [index, entry] of routeChain.entries()) {
17242
+ if (!entry.sourcePath) {
17243
+ continue;
17244
+ }
17245
+ const directory = entry.sourcePath.slice(0, entry.sourcePath.lastIndexOf("/"));
17246
+ if (boundary.path === directory || boundary.path.startsWith(`${directory}/`)) {
17247
+ depth = index;
17248
+ }
17249
+ }
17250
+ return { ...boundary, depth };
17251
+ });
17252
+ }
17169
17253
  async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
17170
17254
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
17171
17255
  const dirs = [pagesDir];
@@ -17253,7 +17337,7 @@ async function collectPageFilePaths(dir) {
17253
17337
  const files = [];
17254
17338
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
17255
17339
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
17256
- const absolutePath = toPosixPath2(join14(dir, entry.name));
17340
+ const absolutePath = toPosixPath2(join15(dir, entry.name));
17257
17341
  if (entry.isDirectory()) {
17258
17342
  return await collectPageFilePaths(absolutePath);
17259
17343
  }
@@ -17379,7 +17463,7 @@ async function buildApp(options) {
17379
17463
  }
17380
17464
  async function buildAppInternal(options) {
17381
17465
  const rootDir = resolve12(options.rootDir ?? process.cwd());
17382
- const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
17466
+ const buildRoot = join16(rootDir, BUILD_OUTPUT_DIR);
17383
17467
  const serverEntry = (() => {
17384
17468
  if (options.target === "static" || options.target === "package") {
17385
17469
  return null;
@@ -17472,7 +17556,7 @@ async function buildAppInternal(options) {
17472
17556
  throw new Error(`[furin] Unsupported build target "${target}"`);
17473
17557
  }
17474
17558
  }
17475
- writeFileSync10(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
17559
+ writeFileSync10(join16(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
17476
17560
  `);
17477
17561
  return {
17478
17562
  manifest,
@@ -17525,7 +17609,7 @@ async function loadCliConfig(cwd, explicitConfigPath) {
17525
17609
 
17526
17610
  // src/cli/preview.ts
17527
17611
  import { existsSync as existsSync16 } from "fs";
17528
- import { isAbsolute as isAbsolute7, join as join16, relative as relative11, resolve as resolve14 } from "path";
17612
+ import { isAbsolute as isAbsolute7, join as join17, relative as relative11, resolve as resolve14 } from "path";
17529
17613
  var LEADING_SLASHES_RE = /^\/+/;
17530
17614
  var TRAILING_SLASHES_RE2 = /\/+$/;
17531
17615
  function normalizeStaticPreviewBasePath(basePath) {
@@ -17544,14 +17628,14 @@ function startStaticPreview({
17544
17628
  }) {
17545
17629
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
17546
17630
  const distDir = resolve14(rawDistDir);
17547
- const indexPath = join16(distDir, "index.html");
17548
- const notFoundPath = join16(distDir, "404.html");
17549
- const faviconPath = join16(distDir, "favicon.ico");
17631
+ const indexPath = join17(distDir, "index.html");
17632
+ const notFoundPath = join17(distDir, "404.html");
17633
+ const faviconPath = join17(distDir, "favicon.ico");
17550
17634
  if (!(existsSync16(indexPath) && existsSync16(notFoundPath))) {
17551
17635
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
17552
17636
  }
17553
17637
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
17554
- const clientDir = join16(distDir, "_client");
17638
+ const clientDir = join17(distDir, "_client");
17555
17639
  const fetchStaticFile = async (request) => {
17556
17640
  const encodedPathname = new URL(request.url).pathname;
17557
17641
  let pathname;
@@ -17573,7 +17657,7 @@ function startStaticPreview({
17573
17657
  if (!pathname.endsWith("/") && await exactFile.exists()) {
17574
17658
  return new Response(exactFile);
17575
17659
  }
17576
- const indexFile = Bun.file(join16(exactPath, "index.html"));
17660
+ const indexFile = Bun.file(join17(exactPath, "index.html"));
17577
17661
  if (await indexFile.exists()) {
17578
17662
  return new Response(indexFile);
17579
17663
  }