@teyik0/furin 0.4.0-alpha.2 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +24 -5
  6. package/dist/build/index.js +753 -453
  7. package/dist/build/server-app-entry.d.ts +12 -0
  8. package/dist/cache.d.ts +1 -0
  9. package/dist/cache.js +185 -0
  10. package/dist/cli/index.js +766 -466
  11. package/dist/client/internal/runtime-types.d.ts +8 -1
  12. package/dist/client/link.js +221 -11
  13. package/dist/client/sync.d.ts +1 -0
  14. package/dist/config.d.ts +22 -21
  15. package/dist/config.js +1 -1
  16. package/dist/define-route.d.ts +273 -1009
  17. package/dist/furin.d.ts +20 -5
  18. package/dist/furin.js +6222 -5383
  19. package/dist/plugin/routes.d.ts +6 -0
  20. package/dist/server/assets/production.d.ts +3 -0
  21. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  22. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  23. package/dist/server/cache/invalidation.d.ts +1 -1
  24. package/dist/server/cache/page-cache-state.d.ts +5 -0
  25. package/dist/server/cache/page-cache.d.ts +53 -0
  26. package/dist/server/cache/redis/index.d.ts +39 -0
  27. package/dist/server/cache/redis/index.js +396 -0
  28. package/dist/server/cache/redis/scripts.d.ts +6 -0
  29. package/dist/server/context-logger.d.ts +2 -2
  30. package/dist/server/dev/runtime.production.d.ts +1 -0
  31. package/dist/server/dev-page-plugin.d.ts +7 -0
  32. package/dist/server/evlog.d.ts +14 -0
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +2537 -0
  35. package/dist/server/render/not-found.d.ts +1 -1
  36. package/dist/server/render/ssg.d.ts +5 -0
  37. package/dist/server/render/static-params.d.ts +4 -0
  38. package/dist/server/router/defined-route.d.ts +1 -1
  39. package/dist/server/router/schemas.d.ts +1 -0
  40. package/dist/server/sync/index.js +794 -116
  41. package/dist/server/sync/plugin.d.ts +31 -158
  42. package/dist/server/sync/stream.d.ts +34 -49
  43. package/dist/shared/elysia-contract.d.ts +8 -14
  44. package/package.json +13 -7
  45. package/src/adapter/README.md +9 -2
  46. package/src/adapter/bun.ts +73 -27
  47. package/src/adapter/package.ts +6 -2
  48. package/src/adapter/runtime-build.ts +11 -4
  49. package/src/adapter/static.ts +8 -6
  50. package/src/adapter/vercel.ts +49 -30
  51. package/src/build/client.ts +18 -1
  52. package/src/build/compile-entry.ts +17 -13
  53. package/src/build/elysia-aot.ts +102 -0
  54. package/src/build/entry-template.ts +24 -5
  55. package/src/build/index.ts +0 -5
  56. package/src/build/production-instrumentation.ts +2 -2
  57. package/src/build/server-app-entry.ts +60 -0
  58. package/src/build/shared.ts +3 -1
  59. package/src/build/ssg-cache.ts +5 -10
  60. package/src/build/virtual-entry.ts +5 -4
  61. package/src/cache.ts +12 -0
  62. package/src/cli/config.ts +3 -3
  63. package/src/cli/index.ts +5 -2
  64. package/src/client/internal/runtime-types.ts +10 -1
  65. package/src/client/sync.ts +1 -0
  66. package/src/config.ts +3 -2
  67. package/src/define-route.ts +266 -128
  68. package/src/furin.ts +138 -149
  69. package/src/plugin/route-config-autofix.ts +11 -2
  70. package/src/plugin/routes.ts +85 -29
  71. package/src/server/assets/production.ts +99 -0
  72. package/src/server/auto-invalidate/plugin.ts +4 -4
  73. package/src/server/auto-invalidate/runtime.ts +74 -42
  74. package/src/server/browser-events/plugin.ts +6 -1
  75. package/src/server/cache/invalidation.ts +61 -20
  76. package/src/server/cache/page-cache-state.ts +22 -0
  77. package/src/server/cache/page-cache.ts +300 -0
  78. package/src/server/cache/redis/index.ts +350 -0
  79. package/src/server/cache/redis/scripts.ts +160 -0
  80. package/src/server/context-logger.ts +5 -5
  81. package/src/server/dev/runtime.production.ts +4 -0
  82. package/src/server/dev-page-plugin.ts +54 -10
  83. package/src/server/evlog.ts +99 -0
  84. package/src/server/internal.ts +7 -0
  85. package/src/server/render/isr.ts +480 -132
  86. package/src/server/render/loaders.ts +18 -12
  87. package/src/server/render/not-found.ts +4 -4
  88. package/src/server/render/ppr-document.ts +2 -2
  89. package/src/server/render/ppr-route.ts +193 -7
  90. package/src/server/render/ssg.ts +148 -4
  91. package/src/server/render/ssr.ts +4 -6
  92. package/src/server/render/static-params.ts +174 -0
  93. package/src/server/router/defined-route.ts +2 -1
  94. package/src/server/router/hmr.ts +2 -0
  95. package/src/server/router/plugin.ts +44 -35
  96. package/src/server/router/schema-merge.ts +1 -1
  97. package/src/server/router/schemas.ts +174 -61
  98. package/src/server/sync/plugin.ts +14 -10
  99. package/src/server/sync/response.ts +3 -3
  100. package/src/shared/elysia-contract.ts +23 -25
package/dist/cli/index.js CHANGED
@@ -334,7 +334,7 @@ var init_config = __esm(() => {
334
334
  requestSyncPath = new AsyncLocalStorage2;
335
335
  });
336
336
 
337
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/utils.mjs
337
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
338
338
  function elapsedMs(startTime) {
339
339
  return Math.max(0, Date.now() - startTime);
340
340
  }
@@ -475,7 +475,7 @@ var init_utils = __esm(() => {
475
475
  _isoDate = /* @__PURE__ */ new Date;
476
476
  });
477
477
 
478
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
478
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
479
479
  function normalizeRedactPathPattern(pattern) {
480
480
  if (!pattern.includes("*") && !pattern.includes("."))
481
481
  return `**.${pattern}`;
@@ -784,7 +784,7 @@ var init_redact_C7FmdhwI = __esm(() => {
784
784
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
785
785
  });
786
786
 
787
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
787
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
788
788
  function logPluginError(name, hook, err) {
789
789
  console.error(`[evlog/${name}] ${hook} failed:`, err);
790
790
  }
@@ -954,7 +954,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
954
954
  globalConfig = getRegistry().config;
955
955
  });
956
956
 
957
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
957
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
958
958
  function pushTreeSpacer(children) {
959
959
  children.push(PRETTY_ERROR_TREE_SPACER);
960
960
  }
@@ -1180,7 +1180,7 @@ function formatGuidanceLine(label, text, labelColor) {
1180
1180
  let remaining = text.trim();
1181
1181
  let first = true;
1182
1182
  while (remaining.length > 0) {
1183
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1183
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
1184
1184
  if (remaining.length <= budget) {
1185
1185
  lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1186
1186
  break;
@@ -1248,14 +1248,14 @@ function buildErrorEntries(error, options = {}) {
1248
1248
  }];
1249
1249
  }
1250
1250
  var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
1251
- var init_pretty_error_DTIHxnBN = __esm(() => {
1251
+ var init_pretty_error_D8rlWNL1 = __esm(() => {
1252
1252
  init_utils();
1253
1253
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1254
1254
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1255
1255
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1256
1256
  });
1257
1257
 
1258
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1258
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1259
1259
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1260
1260
  const compact = partial.compact ?? (inDev && pretty);
1261
1261
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1308,7 +1308,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1308
1308
  };
1309
1309
  });
1310
1310
 
1311
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1311
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1312
1312
  function hasWideEventPublisher() {
1313
1313
  return publisher !== null;
1314
1314
  }
@@ -1324,7 +1324,7 @@ function publishWideEvent(event) {
1324
1324
  var publisher = null;
1325
1325
  var init_wideEventChannel_BUDW48oP = () => {};
1326
1326
 
1327
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1327
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1328
1328
  function isEvlogError(error) {
1329
1329
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1330
1330
  }
@@ -1333,7 +1333,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
1333
1333
  evlogErrorBrand = Symbol.for("evlog.error.brand");
1334
1334
  });
1335
1335
 
1336
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error.mjs
1336
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1337
1337
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1338
1338
  var init_error = __esm(() => {
1339
1339
  init_utils();
@@ -1442,7 +1442,7 @@ var init_error = __esm(() => {
1442
1442
  });
1443
1443
  });
1444
1444
 
1445
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1445
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1446
1446
  function extractSafeHeaders(headers) {
1447
1447
  const raw = {};
1448
1448
  headers.forEach((value, key) => {
@@ -1463,7 +1463,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
1463
1463
  init_utils();
1464
1464
  });
1465
1465
 
1466
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1466
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1467
1467
  function writePrettyStdout(text) {
1468
1468
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1469
1469
  }
@@ -1597,13 +1597,14 @@ function emitWideEvent(level, event, options = {}) {
1597
1597
  formatted = redactEvent(formatted, state.redact);
1598
1598
  markGloballyRedacted(formatted);
1599
1599
  }
1600
- if (!state.silent)
1600
+ if (!state.silent) {
1601
1601
  if (state.pretty)
1602
1602
  prettyPrintWideEvent(formatted);
1603
1603
  else if (state.stringify)
1604
1604
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1605
1605
  else
1606
1606
  console[getConsoleMethod(level)](formatted);
1607
+ }
1607
1608
  if (!deferDrain) {
1608
1609
  publishWideEvent(formatted);
1609
1610
  const drainPromises = [];
@@ -1654,11 +1655,12 @@ function formatValue(value) {
1654
1655
  if (isPlainObject$1(value)) {
1655
1656
  const pairs = [];
1656
1657
  for (const [k, v] of Object.entries(value))
1657
- if (v !== undefined && v !== null)
1658
+ if (v !== undefined && v !== null) {
1658
1659
  if (typeof v === "object")
1659
1660
  pairs.push(`${k}=${JSON.stringify(v)}`);
1660
1661
  else
1661
1662
  pairs.push(`${k}=${v}`);
1663
+ }
1662
1664
  return pairs.join(" ");
1663
1665
  }
1664
1666
  return String(value);
@@ -1713,6 +1715,20 @@ function asToolCallArray(value) {
1713
1715
  return;
1714
1716
  return value.every(isToolCallEntry) ? value : undefined;
1715
1717
  }
1718
+ function asCapturedLines(value) {
1719
+ if (typeof value !== "string" || value.length === 0)
1720
+ return;
1721
+ const lines = value.split(`
1722
+ `).map((line) => {
1723
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1724
+ });
1725
+ if (lines.length > CAPTURED_MAX_LINES) {
1726
+ lines.length = CAPTURED_MAX_LINES;
1727
+ lines.push(`+${value.split(`
1728
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1729
+ }
1730
+ return lines;
1731
+ }
1716
1732
  function buildAIEntries(ai) {
1717
1733
  const entries = [];
1718
1734
  const headerParts = [];
@@ -1807,7 +1823,7 @@ function buildAIEntries(ai) {
1807
1823
  value: "",
1808
1824
  children
1809
1825
  });
1810
- } else if (toolCalls?.length)
1826
+ } else if (toolCalls?.length) {
1811
1827
  if (toolCallEntries?.length) {
1812
1828
  const children = toolCallEntries.map((tc) => {
1813
1829
  const inputStr = serializeToolInput(tc.input);
@@ -1827,6 +1843,7 @@ function buildAIEntries(ai) {
1827
1843
  value: names.join(", ")
1828
1844
  });
1829
1845
  }
1846
+ }
1830
1847
  const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1831
1848
  if (stepsUsage?.length) {
1832
1849
  const firstModel = stepsUsage[0]?.model;
@@ -1848,6 +1865,20 @@ function buildAIEntries(ai) {
1848
1865
  key: "ai.steps",
1849
1866
  value: String(steps)
1850
1867
  });
1868
+ const promptLines = asCapturedLines(ai.prompt);
1869
+ if (promptLines)
1870
+ entries.push({
1871
+ key: "ai.prompt",
1872
+ value: "",
1873
+ children: promptLines
1874
+ });
1875
+ const outputLines = asCapturedLines(ai.output);
1876
+ if (outputLines)
1877
+ entries.push({
1878
+ key: "ai.output",
1879
+ value: "",
1880
+ children: outputLines
1881
+ });
1851
1882
  const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1852
1883
  if (embedding) {
1853
1884
  const parts = [];
@@ -1998,10 +2029,63 @@ function prettyPrintWideEvent(event) {
1998
2029
  if (!browser && lines.length > 0)
1999
2030
  flushPrettyLines(lines);
2000
2031
  }
2032
+ function removeErrorCycles(value, ancestors) {
2033
+ if (value === null || typeof value !== "object")
2034
+ return value;
2035
+ if (ancestors.has(value))
2036
+ return "[Circular]";
2037
+ ancestors.add(value);
2038
+ let changed = false;
2039
+ const visit = (item) => {
2040
+ const result = removeErrorCycles(item, ancestors);
2041
+ if (!Object.is(result, item))
2042
+ changed = true;
2043
+ return result;
2044
+ };
2045
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
2046
+ ancestors.delete(value);
2047
+ return changed ? copy : value;
2048
+ }
2049
+ function serializeError(err) {
2050
+ const errorObj = {
2051
+ name: err.name,
2052
+ message: err.message,
2053
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2054
+ };
2055
+ const errRecord = err;
2056
+ const ancestors = new WeakSet([err]);
2057
+ for (const k of [
2058
+ "code",
2059
+ "status",
2060
+ "statusText",
2061
+ "statusCode",
2062
+ "statusMessage",
2063
+ "data",
2064
+ "cause",
2065
+ "internal"
2066
+ ])
2067
+ if (k in err)
2068
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
2069
+ if (EvlogError.isEvlogError(err)) {
2070
+ if (err.code)
2071
+ errorObj.code = err.code;
2072
+ if (err.why)
2073
+ errorObj.why = err.why;
2074
+ if (err.fix)
2075
+ errorObj.fix = err.fix;
2076
+ if (err.link)
2077
+ errorObj.link = err.link;
2078
+ if (err.status)
2079
+ errorObj.status = err.status;
2080
+ }
2081
+ return errorObj;
2082
+ }
2001
2083
  function createLogMethod(level) {
2002
2084
  return function logMethod(tagOrEvent, message) {
2003
2085
  if (typeof tagOrEvent === "string" && message !== undefined)
2004
2086
  emitTaggedLog(level, tagOrEvent, message);
2087
+ else if (tagOrEvent instanceof Error)
2088
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
2005
2089
  else if (typeof tagOrEvent === "object")
2006
2090
  emitWideEvent(level, tagOrEvent);
2007
2091
  else
@@ -2080,36 +2164,7 @@ function createLogger(initialContext = {}, internalOptions) {
2080
2164
  const err = typeof error === "string" ? new Error(error) : error;
2081
2165
  if (errorContext)
2082
2166
  mergeInto(context, errorContext);
2083
- const errorObj = {
2084
- name: err.name,
2085
- message: err.message,
2086
- stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2087
- };
2088
- const errRecord = err;
2089
- for (const k of [
2090
- "code",
2091
- "status",
2092
- "statusText",
2093
- "statusCode",
2094
- "statusMessage",
2095
- "data",
2096
- "cause",
2097
- "internal"
2098
- ])
2099
- if (k in err)
2100
- errorObj[k] = errRecord[k];
2101
- if (EvlogError.isEvlogError(err)) {
2102
- if (err.code)
2103
- errorObj.code = err.code;
2104
- if (err.why)
2105
- errorObj.why = err.why;
2106
- if (err.fix)
2107
- errorObj.fix = err.fix;
2108
- if (err.link)
2109
- errorObj.link = err.link;
2110
- if (err.status)
2111
- errorObj.status = err.status;
2112
- }
2167
+ const errorObj = serializeError(err);
2113
2168
  if (isPlainObject$1(context.error))
2114
2169
  mergeInto(context.error, errorObj);
2115
2170
  else
@@ -2294,12 +2349,12 @@ function finalizeAudit(event) {
2294
2349
  event.audit = decorated;
2295
2350
  _testCollector?.(decorated, event);
2296
2351
  }
2297
- var nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, _log, noopLogger, _testCollector = null;
2298
- var init_audit_CW8wdQDm = __esm(() => {
2352
+ var nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2353
+ var init_audit_C8euLMvu = __esm(() => {
2299
2354
  init_utils();
2300
2355
  init_redact_C7FmdhwI();
2301
2356
  init_globalRegistry_Bh3bIGwA();
2302
- init_pretty_error_DTIHxnBN();
2357
+ init_pretty_error_D8rlWNL1();
2303
2358
  init_dev_terminal_Brarc6vc();
2304
2359
  init_wideEventChannel_BUDW48oP();
2305
2360
  init_error();
@@ -2330,12 +2385,12 @@ var init_audit_CW8wdQDm = __esm(() => {
2330
2385
  initLogger(__EVLOG_CONFIG__);
2331
2386
  });
2332
2387
 
2333
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/index.mjs
2388
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/index.mjs
2334
2389
  var init_dist = __esm(() => {
2335
- init_audit_CW8wdQDm();
2390
+ init_audit_C8euLMvu();
2336
2391
  });
2337
2392
 
2338
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2393
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2339
2394
  function shouldDeferEmitForResponse(response) {
2340
2395
  if (!response.body)
2341
2396
  return false;
@@ -2415,7 +2470,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
2415
2470
  }
2416
2471
  var init_streamResponse_OlirMA5P = () => {};
2417
2472
 
2418
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2473
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2419
2474
  function extractErrorStatus(error) {
2420
2475
  if (error === null || typeof error !== "object")
2421
2476
  return 500;
@@ -2425,7 +2480,7 @@ function extractErrorStatus(error) {
2425
2480
  }
2426
2481
  var init_errors_CL8dDgIi = () => {};
2427
2482
 
2428
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2483
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2429
2484
  function shouldLog(path, include, exclude) {
2430
2485
  if (exclude && exclude.length > 0) {
2431
2486
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -2453,7 +2508,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
2453
2508
  init_utils();
2454
2509
  });
2455
2510
 
2456
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/middleware-DHm89-gB.mjs
2511
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2457
2512
  function resolveMiddlewarePluginRunner(options) {
2458
2513
  const global2 = getGlobalPluginRunner();
2459
2514
  const local = options.plugins;
@@ -2630,29 +2685,17 @@ function createMiddlewareLogger(options) {
2630
2685
  };
2631
2686
  }
2632
2687
  var noopResult, runnerCache;
2633
- var init_middleware_DHm89_gB = __esm(() => {
2688
+ var init_middleware_fam3VyaL = __esm(() => {
2634
2689
  init_utils();
2635
2690
  init_redact_C7FmdhwI();
2636
2691
  init_globalRegistry_Bh3bIGwA();
2637
2692
  init_wideEventChannel_BUDW48oP();
2638
- init_audit_CW8wdQDm();
2693
+ init_audit_C8euLMvu();
2639
2694
  init_errors_CL8dDgIi();
2640
2695
  init_deferred_drain_CfRYimo5();
2641
2696
  init_streamResponse_OlirMA5P();
2642
2697
  noopResult = {
2643
- logger: {
2644
- set() {},
2645
- error() {},
2646
- info() {},
2647
- warn() {},
2648
- setLevel() {},
2649
- emit() {
2650
- return null;
2651
- },
2652
- getContext() {
2653
- return {};
2654
- }
2655
- },
2698
+ logger: noopLogger,
2656
2699
  finish: () => Promise.resolve(null),
2657
2700
  finishResponse: (response) => Promise.resolve(response),
2658
2701
  skipped: true
@@ -2660,7 +2703,7 @@ var init_middleware_DHm89_gB = __esm(() => {
2660
2703
  runnerCache = /* @__PURE__ */ new WeakMap;
2661
2704
  });
2662
2705
 
2663
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/integration-Dprr4POU.mjs
2706
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2664
2707
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2665
2708
  const log = parent;
2666
2709
  log.fork = (label, fn) => {
@@ -2756,118 +2799,68 @@ function defineFrameworkIntegration(spec) {
2756
2799
  };
2757
2800
  } };
2758
2801
  }
2759
- var init_integration_Dprr4POU = __esm(() => {
2760
- init_audit_CW8wdQDm();
2802
+ var init_integration_CGD18W8r = __esm(() => {
2803
+ init_audit_C8euLMvu();
2761
2804
  init_headers_Bx1ieR_m();
2762
2805
  init_errors_CL8dDgIi();
2763
- init_middleware_DHm89_gB();
2806
+ init_middleware_fam3VyaL();
2764
2807
  });
2765
2808
 
2766
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/asyncStorageScope-CnJiW7V3.mjs
2767
- function supportsAsyncLocalStorageEnterWith(storage) {
2768
- if (typeof storage.enterWith !== "function")
2769
- return false;
2770
- try {
2771
- storage.enterWith(undefined);
2772
- return true;
2773
- } catch {
2774
- return false;
2809
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2810
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2811
+ function createLoggerStorage(contextHint, id = contextHint) {
2812
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
2813
+ function useLogger() {
2814
+ const logger = storage.getStore();
2815
+ if (!logger)
2816
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2817
+ return logger;
2775
2818
  }
2819
+ return {
2820
+ storage,
2821
+ useLogger
2822
+ };
2776
2823
  }
2777
- function createSharedEnterWithStorage(id, create) {
2778
- return getSharedStorage(id, () => {
2779
- const storage = create();
2780
- patchAsyncLocalStorageEnterWith(storage);
2781
- return storage;
2782
- });
2783
- }
2784
- function patchAsyncLocalStorageEnterWith(storage) {
2785
- if (supportsAsyncLocalStorageEnterWith(storage))
2786
- return;
2787
- let fallbackStore;
2788
- let runDepth = 0;
2789
- const originalGetStore = storage.getStore.bind(storage);
2790
- const originalRun = storage.run.bind(storage);
2791
- Object.defineProperty(storage, "enterWith", {
2792
- configurable: true,
2793
- writable: true,
2794
- value(store) {
2795
- fallbackStore = store;
2796
- }
2797
- });
2798
- Object.defineProperty(storage, "run", {
2799
- configurable: true,
2800
- writable: true,
2801
- value(store, callback, ...args) {
2802
- runDepth++;
2803
- try {
2804
- return originalRun(store, callback, ...args);
2805
- } finally {
2806
- runDepth--;
2807
- }
2808
- }
2809
- });
2810
- Object.defineProperty(storage, "getStore", {
2811
- configurable: true,
2812
- writable: true,
2813
- value() {
2814
- if (runDepth > 0)
2815
- return originalGetStore();
2816
- const active = originalGetStore();
2817
- return active !== undefined ? active : fallbackStore;
2818
- }
2819
- });
2820
- }
2821
- var init_asyncStorageScope_CnJiW7V3 = __esm(() => {
2824
+ var init_storage = __esm(() => {
2822
2825
  init_globalRegistry_Bh3bIGwA();
2823
2826
  });
2824
2827
 
2825
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/elysia/index.mjs
2826
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2828
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit.mjs
2829
+ var init_toolkit = __esm(() => {
2830
+ init_integration_CGD18W8r();
2831
+ init_storage();
2832
+ });
2833
+
2834
+ // src/server/evlog.ts
2827
2835
  import { Elysia as Elysia2 } from "elysia";
2828
- function useLogger2() {
2829
- const logger = storage.getStore();
2830
- if (!logger || !activeLoggers.has(logger))
2831
- throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
2832
- return logger;
2833
- }
2834
- var storage, activeLoggers, integration;
2835
- var init_elysia = __esm(() => {
2836
- init_integration_Dprr4POU();
2837
- init_asyncStorageScope_CnJiW7V3();
2838
- storage = createSharedEnterWithStorage("evlog:elysia", () => new AsyncLocalStorage3);
2839
- activeLoggers = /* @__PURE__ */ new WeakSet;
2836
+ var loggerStorage, integration, getRequestLogger;
2837
+ var init_evlog = __esm(() => {
2838
+ init_toolkit();
2839
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2840
2840
  integration = defineFrameworkIntegration({
2841
- name: "elysia",
2842
- extractRequest: ({ request, path, headers }) => ({
2843
- method: request.method,
2844
- path,
2845
- headers,
2846
- requestId: headers["x-request-id"]
2847
- }),
2848
- attachLogger: ({ request, path, headers }, logger) => {
2849
- attachForkToLogger(storage, logger, {
2841
+ attachLogger: () => {
2842
+ return;
2843
+ },
2844
+ extractRequest: ({ request }) => {
2845
+ const url = new URL(request.url);
2846
+ return {
2847
+ headers: request.headers,
2850
2848
  method: request.method,
2851
- path,
2852
- requestId: headers["x-request-id"]
2853
- }, {
2854
- onChildEnter: (child) => {
2855
- activeLoggers.add(child);
2856
- },
2857
- onChildExit: (child) => {
2858
- activeLoggers.delete(child);
2859
- }
2860
- });
2861
- activeLoggers.add(logger);
2862
- }
2849
+ path: url.pathname,
2850
+ requestId: request.headers.get("x-request-id") ?? undefined
2851
+ };
2852
+ },
2853
+ name: "furin",
2854
+ storage: loggerStorage.storage
2863
2855
  });
2856
+ getRequestLogger = loggerStorage.useLogger;
2864
2857
  });
2865
2858
 
2866
2859
  // src/server/context-logger.ts
2867
2860
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2868
- function useLogger3() {
2861
+ function getLogger() {
2869
2862
  try {
2870
- return useLogger2();
2863
+ return getRequestLogger();
2871
2864
  } catch {
2872
2865
  return syntheticRenderStorage.getStore() ?? noopLogger2;
2873
2866
  }
@@ -2887,7 +2880,7 @@ async function runInSyntheticRenderScope(fn, initialContext) {
2887
2880
  var noopLogger2, syntheticRenderStorage;
2888
2881
  var init_context_logger = __esm(() => {
2889
2882
  init_dist();
2890
- init_elysia();
2883
+ init_evlog();
2891
2884
  noopLogger2 = {
2892
2885
  emit: () => null,
2893
2886
  error: () => {},
@@ -2907,7 +2900,7 @@ var IS_DEV = true;
2907
2900
  // src/server/dev/graph.ts
2908
2901
  import { randomUUID } from "crypto";
2909
2902
  import { readFileSync as readFileSync2, statSync as statSync2 } from "fs";
2910
- import { dirname as dirname5, extname as extname2 } from "path";
2903
+ import { dirname as dirname6, extname as extname2 } from "path";
2911
2904
  function normalizeModulePath(path) {
2912
2905
  return path.replaceAll("\\", "/");
2913
2906
  }
@@ -2916,7 +2909,7 @@ function resolveDevSourceImports(source, path, loader) {
2916
2909
  const transpiler = new Bun.Transpiler({ loader });
2917
2910
  for (const imported of transpiler.scanImports(source)) {
2918
2911
  try {
2919
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname5(path)));
2912
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname6(path)));
2920
2913
  if (!resolved.includes("/node_modules/")) {
2921
2914
  imports.push(resolved);
2922
2915
  }
@@ -3366,6 +3359,7 @@ function browserEventsClientSource() {
3366
3359
 
3367
3360
  // src/server/browser-events/plugin.ts
3368
3361
  import { Elysia as Elysia3 } from "elysia";
3362
+ import { websocket } from "elysia/websocket";
3369
3363
  function browserEventsClientScript(basePath) {
3370
3364
  return `<script data-furin-framework-module="" type="module" src="${basePath}${CLIENT_PATH2}"></script>`;
3371
3365
  }
@@ -3394,16 +3388,16 @@ var init_plugin2 = () => {};
3394
3388
 
3395
3389
  // src/cli/index.ts
3396
3390
  import { existsSync as existsSync15 } from "fs";
3397
- import { resolve as resolve10 } from "path";
3391
+ import { resolve as resolve12 } from "path";
3398
3392
  import { parseArgs } from "util";
3399
3393
 
3400
3394
  // src/build/index.ts
3401
- import { existsSync as existsSync12, writeFileSync as writeFileSync7 } from "fs";
3402
- import { join as join13, relative as relative8, resolve as resolve7 } from "path";
3395
+ import { existsSync as existsSync12, writeFileSync as writeFileSync8 } from "fs";
3396
+ import { join as join14, relative as relative9, resolve as resolve9 } from "path";
3403
3397
 
3404
3398
  // src/adapter/bun.ts
3405
- import { existsSync as existsSync7, rmSync as rmSync2 } from "fs";
3406
- import { join as join8, resolve as resolve4 } from "path";
3399
+ import { existsSync as existsSync7, readFileSync as readFileSync4, rmSync as rmSync2 } from "fs";
3400
+ import { join as join9, resolve as resolve6 } from "path";
3407
3401
 
3408
3402
  // src/build/bun-build.ts
3409
3403
  function runBunBuild(config) {
@@ -3470,6 +3464,7 @@ function buildAppContextBlock(app, varPrefix) {
3470
3464
  const routeEntries = app.routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
3471
3465
  const rootConventionsLine = app.rootConventions ? ` rootConventions: ${JSON.stringify(app.rootConventions)},` : "";
3472
3466
  const routeMetadataLine = app.routeMetadata ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},` : "";
3467
+ const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
3473
3468
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
3474
3469
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
3475
3470
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
@@ -3477,6 +3472,7 @@ function buildAppContextBlock(app, varPrefix) {
3477
3472
  "__setCompileContext({",
3478
3473
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
3479
3474
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
3475
+ deploymentTargetLine,
3480
3476
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
3481
3477
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
3482
3478
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -3500,6 +3496,7 @@ function buildEntrySource(options) {
3500
3496
  const { apps, headerComment, serverEntry } = options;
3501
3497
  const mode = options.mode ?? "boot";
3502
3498
  const internalSpecifier = mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
3499
+ const productionMode = mode !== "register";
3503
3500
  const importLines = [];
3504
3501
  const contextBlocks = [];
3505
3502
  for (let appIndex = 0;appIndex < apps.length; appIndex++) {
@@ -3512,9 +3509,9 @@ function buildEntrySource(options) {
3512
3509
  const lines = [
3513
3510
  headerComment,
3514
3511
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
3515
- ...mode === "boot" ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3512
+ ...productionMode ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3516
3513
  ...importLines,
3517
- ...mode === "boot" ? [
3514
+ ...productionMode ? [
3518
3515
  "",
3519
3516
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3520
3517
  "__setDevMode(false);",
@@ -3522,7 +3519,7 @@ function buildEntrySource(options) {
3522
3519
  ] : [],
3523
3520
  ...contextBlocks,
3524
3521
  "",
3525
- ...serverEntry ? [
3522
+ ...serverEntry && mode === "boot" ? [
3526
3523
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3527
3524
  'if (typeof __serverModule.startServer === "function") {',
3528
3525
  " await __serverModule.startServer();",
@@ -3540,6 +3537,13 @@ function buildEntrySource(options) {
3540
3537
  " }",
3541
3538
  "}",
3542
3539
  ""
3540
+ ] : serverEntry && mode === "app" ? [
3541
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3542
+ "export const app = __serverModule.default;",
3543
+ "export const port = __serverModule.port;",
3544
+ "export const startServer = __serverModule.startServer;",
3545
+ "export default __serverModule.default;",
3546
+ ""
3543
3547
  ] : []
3544
3548
  ];
3545
3549
  return lines.join(`
@@ -3572,7 +3576,7 @@ function toBuildRouteManifestEntry(route, rootDir) {
3572
3576
  mode: route.mode,
3573
3577
  pagePath: toPosixPath(relative(rootDir, route.path)),
3574
3578
  hasLayout: route.routeChain.some((entry) => !!entry.layout),
3575
- hasStaticParams: !!route.page?.staticParams,
3579
+ hasStaticParams: route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined),
3576
3580
  revalidate: resolveRouteRevalidate(route.page) ?? null
3577
3581
  };
3578
3582
  }
@@ -3592,12 +3596,13 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
3592
3596
  // src/build/virtual-entry.ts
3593
3597
  var REGEX_SPECIAL_CHARACTERS_RE = /[.*+?^${}()|[\]\\]/g;
3594
3598
  function createVirtualBuildEntry(entrypoint, source, loader) {
3595
- const entrypointFilter = new RegExp(`^${entrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3599
+ const normalizedEntrypoint = entrypoint.replaceAll("\\", "/");
3600
+ const entrypointFilter = new RegExp(`^${normalizedEntrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3596
3601
  return {
3597
- entrypoint,
3598
- files: { [entrypoint]: source },
3602
+ entrypoint: normalizedEntrypoint,
3603
+ files: { [normalizedEntrypoint]: source },
3599
3604
  plugin: {
3600
- name: `furin-virtual-entry:${entrypoint}`,
3605
+ name: `furin-virtual-entry:${normalizedEntrypoint}`,
3601
3606
  setup(build) {
3602
3607
  build.onLoad({ filter: entrypointFilter }, () => ({ contents: source, loader }));
3603
3608
  }
@@ -3620,10 +3625,8 @@ function buildEmbeddedContext(clientDir, publicDir) {
3620
3625
  " },"
3621
3626
  ];
3622
3627
  }
3623
- function generateCompileEntry(options) {
3624
- const { apps, outDir, serverEntry, publicDir } = options;
3625
- ensureDir(outDir);
3626
- const preparedApps = apps.map((app) => {
3628
+ function prepareCompileEntryApps(options) {
3629
+ return options.apps.map((app) => {
3627
3630
  const { embed, ...context } = app;
3628
3631
  if (!embed) {
3629
3632
  return context;
@@ -3632,29 +3635,108 @@ function generateCompileEntry(options) {
3632
3635
  ...context,
3633
3636
  extraContext: [
3634
3637
  ...context.extraContext ?? [],
3635
- ...buildEmbeddedContext(embed.clientDir, publicDir)
3638
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir)
3636
3639
  ]
3637
3640
  };
3638
3641
  });
3639
- const source = buildEntrySource({
3640
- apps: preparedApps,
3641
- headerComment: options.headerComment ?? "// Auto-generated by furin compile \u2014 do not edit",
3642
- serverEntry
3643
- });
3644
- const entryPath = join3(outDir, "_compile-entry.ts");
3645
- return createVirtualBuildEntry(entryPath, source, "ts");
3642
+ }
3643
+
3644
+ // src/build/elysia-aot.ts
3645
+ import { dirname as dirname2, resolve } from "path";
3646
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3647
+ var AOT_NAMESPACE = "furin-elysia-aot";
3648
+ var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
3649
+ var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
3650
+ var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
3651
+ function loaderFor(path) {
3652
+ const extension = path.slice(path.lastIndexOf("."));
3653
+ if (extension === ".jsx") {
3654
+ return "jsx";
3655
+ }
3656
+ if (extension === ".tsx") {
3657
+ return "tsx";
3658
+ }
3659
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") {
3660
+ return "ts";
3661
+ }
3662
+ return "js";
3663
+ }
3664
+ function patchElysiaWebSocketStub(source) {
3665
+ if (!source.includes(WEBSOCKET_STUB_MARKER) || source.includes("accumulateWSOptions")) {
3666
+ return source;
3667
+ }
3668
+ return `${source}
3669
+ export function accumulateWSOptions(){return e()}
3670
+ export function resolveWSOptions(){return e()}
3671
+ export function drainWaiters(){return e()}
3672
+ export function handleWSResponse(){return e()}
3673
+ `;
3674
+ }
3675
+ function elysiaAot(entry) {
3676
+ const entryPath = resolve(entry);
3677
+ const hooks = aotFactory({ entry, strip: "auto", target: "bun" });
3678
+ return {
3679
+ name: "elysia-aot",
3680
+ async setup(build) {
3681
+ try {
3682
+ await hooks.buildStart?.();
3683
+ } catch (error) {
3684
+ if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
3685
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
3686
+ return;
3687
+ }
3688
+ throw error;
3689
+ }
3690
+ const entrySource = await Bun.file(entryPath).text();
3691
+ const transformedEntry = await hooks.transform?.(entrySource, entryPath);
3692
+ if (transformedEntry !== undefined) {
3693
+ await Bun.write(entryPath, transformedEntry);
3694
+ }
3695
+ build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
3696
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
3697
+ }));
3698
+ build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
3699
+ const resolved = hooks.resolveId?.(path);
3700
+ return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
3701
+ });
3702
+ build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
3703
+ const contents = hooks.load?.(path);
3704
+ return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
3705
+ });
3706
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
3707
+ if (resolve(path) === entryPath) {
3708
+ return;
3709
+ }
3710
+ if (hooks.transformInclude?.(path) === false) {
3711
+ return;
3712
+ }
3713
+ const original = await Bun.file(path).text();
3714
+ const transformed = await hooks.transform?.(original, path);
3715
+ if (transformed === undefined) {
3716
+ return;
3717
+ }
3718
+ return {
3719
+ contents: patchElysiaWebSocketStub(transformed),
3720
+ loader: loaderFor(path)
3721
+ };
3722
+ });
3723
+ build.onEnd(() => {
3724
+ hooks.buildEnd?.();
3725
+ });
3726
+ }
3727
+ };
3646
3728
  }
3647
3729
 
3648
3730
  // src/build/production-instrumentation.ts
3649
- import { dirname as dirname2, relative as relative2, resolve } from "path";
3731
+ import { dirname as dirname3, relative as relative2, resolve as resolve2 } from "path";
3650
3732
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3651
3733
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3652
- var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|plugin)(?:\.ts|\.js)?$/;
3734
+ var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
3653
3735
  var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
3654
3736
  var HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
3655
- var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3737
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3656
3738
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3657
- var FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
3739
+ var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3658
3740
  function isFurinRuntimePath(path) {
3659
3741
  const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3660
3742
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
@@ -3667,23 +3749,23 @@ function productionInstrumentationPlugin() {
3667
3749
  name: "furin-production-instrumentation",
3668
3750
  setup(build) {
3669
3751
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3670
- const importPath = resolve(dirname2(args.importer), args.path);
3752
+ const importPath = resolve2(dirname3(args.importer), args.path);
3671
3753
  if (!isFurinRuntimePath(importPath)) {
3672
3754
  return;
3673
3755
  }
3674
3756
  if (INSTRUMENTATION_IMPORT.test(importPath)) {
3675
3757
  return {
3676
- path: resolve(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3758
+ path: resolve2(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3677
3759
  };
3678
3760
  }
3679
3761
  if (DEV_PAGE_PLUGIN_IMPORT.test(importPath)) {
3680
- return { path: resolve(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3762
+ return { path: resolve2(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3681
3763
  }
3682
3764
  if (DEV_RUNTIME_IMPORT.test(importPath)) {
3683
- return { path: resolve(import.meta.dir, "../server/dev/runtime.production.ts") };
3765
+ return { path: resolve2(import.meta.dir, "../server/dev/runtime.production.ts") };
3684
3766
  }
3685
3767
  if (HMR_IMPORT.test(importPath)) {
3686
- return { path: resolve(import.meta.dir, "../server/router/hmr.production.ts") };
3768
+ return { path: resolve2(import.meta.dir, "../server/router/hmr.production.ts") };
3687
3769
  }
3688
3770
  if (DEV_BUILD_IMPORT.test(importPath)) {
3689
3771
  return { namespace: PRODUCTION_STUB_NAMESPACE, path: importPath };
@@ -3699,6 +3781,10 @@ function productionInstrumentationPlugin() {
3699
3781
  };
3700
3782
  }
3701
3783
 
3784
+ // src/build/server-app-entry.ts
3785
+ import { writeFileSync } from "fs";
3786
+ import { join as join5 } from "path";
3787
+
3702
3788
  // src/plugin/routes.ts
3703
3789
  import {
3704
3790
  existsSync as existsSync4,
@@ -3708,25 +3794,19 @@ import {
3708
3794
  statSync,
3709
3795
  watch
3710
3796
  } from "fs";
3711
- import { dirname as dirname3, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve2, sep } from "path";
3797
+ import { dirname as dirname4, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve3, sep } from "path";
3712
3798
  import { pathToFileURL } from "url";
3713
3799
  import { Elysia } from "elysia";
3714
3800
 
3715
3801
  // src/shared/elysia-contract.ts
3716
- import { getSchemaValidator as elysiaGetSchemaValidator } from "elysia";
3717
- import {
3718
- parseQueryFromURL as elysiaParseQueryFromURL,
3719
- parseQueryStandardSchema as elysiaParseQueryStandardSchema
3720
- } from "elysia/parse-query";
3721
- import { TypeCompiler as ElysiaTypeCompiler } from "elysia/type-system";
3722
- var TypeCompiler = ElysiaTypeCompiler;
3802
+ import { Validator } from "elysia";
3723
3803
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
3724
3804
  function isTypeBoxObjectSchema(schema) {
3725
3805
  if (schema === null || typeof schema !== "object") {
3726
3806
  return false;
3727
3807
  }
3728
3808
  const candidate = schema;
3729
- return candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object";
3809
+ return (candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object") && candidate.properties !== null && typeof candidate.properties === "object";
3730
3810
  }
3731
3811
 
3732
3812
  // src/shared/search-params.ts
@@ -3880,7 +3960,7 @@ function mergeRouteSchemas(routeChain, key) {
3880
3960
  return schemas[0];
3881
3961
  }
3882
3962
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
3883
- throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
3963
+ throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox object schemas. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
3884
3964
  }
3885
3965
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3886
3966
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
@@ -3944,10 +4024,11 @@ function unwrapTSExpression(node) {
3944
4024
  init_patterns();
3945
4025
  var ROUTES_NAMESPACE_PREFIX = "furin-routes";
3946
4026
  var ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
3947
- var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry$/;
4027
+ var COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
4028
+ var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
3948
4029
  var ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
3949
4030
  var ROUTE_FILES_NAMESPACE = "furin-route-files";
3950
- var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry\.ts\?furin-virtual$/;
4031
+ var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
3951
4032
  var CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
3952
4033
  var CLIENT_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes$/;
3953
4034
  var SERVER_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes\?instance=.+$/;
@@ -3958,11 +4039,14 @@ var DEV_ROUTES_APPS_SYMBOL = Symbol.for("@teyik0/furin/dev-routes-apps");
3958
4039
  var DEV_ROUTE_WATCHERS_SYMBOL = Symbol.for("@teyik0/furin/dev-route-watchers");
3959
4040
  var devInstancesBySpecifier = new Map;
3960
4041
  function instanceKey(instance) {
3961
- return `${resolve2(instance.pagesDir)}\x00${instance.prefix}`;
4042
+ return `${resolve3(instance.pagesDir)}\x00${instance.prefix}`;
3962
4043
  }
3963
4044
  function routeModuleSpecifier(instance) {
3964
4045
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
3965
4046
  }
4047
+ function composableRouteModuleSpecifier(instance) {
4048
+ return `${routeModuleSpecifier(instance)}&composable`;
4049
+ }
3966
4050
  function instanceNamespace(instance) {
3967
4051
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
3968
4052
  }
@@ -4069,9 +4153,9 @@ function collectRouteFiles(root) {
4069
4153
  }
4070
4154
  function routeSourcePaths(instance) {
4071
4155
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4072
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve2(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4156
+ return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve3(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4073
4157
  }
4074
- function emitRouteNode(node, indentation) {
4158
+ function emitRouteNode(node, indentation, includeRootCatchAll) {
4075
4159
  const childIndentation = `${indentation} `;
4076
4160
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
4077
4161
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
@@ -4079,13 +4163,13 @@ function emitRouteNode(node, indentation) {
4079
4163
  if (node.indexRoute) {
4080
4164
  content.push(`${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`);
4081
4165
  }
4082
- for (const route of node.fileRoutes) {
4166
+ for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
4083
4167
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
4084
4168
  content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`);
4085
4169
  }
4086
4170
  for (const child of node.children) {
4087
4171
  content.push(`${childIndentation}.use(`);
4088
- content.push(emitRouteNode(child, `${childIndentation} `));
4172
+ content.push(emitRouteNode(child, `${childIndentation} `, includeRootCatchAll));
4089
4173
  content.push(`${childIndentation})`);
4090
4174
  }
4091
4175
  if (node.layout) {
@@ -4118,28 +4202,28 @@ async function retainComposableRoutes(node) {
4118
4202
  node.fileRoutes = composableRoutes;
4119
4203
  await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
4120
4204
  }
4121
- async function generateServerInstance(instance, routeFilesBySpecifier) {
4205
+ async function generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4122
4206
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4123
4207
  const tree = buildRouteTree(instance.pagesDir, instanceId);
4124
4208
  await retainComposableRoutes(tree);
4125
4209
  const imports = collectRouteFiles(tree).sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)).map((route) => {
4126
- const specifier = routeFileSpecifier(route);
4210
+ const specifier = materialized ? resolve3(route.sourcePath).replaceAll("\\", "/") : routeFileSpecifier(route);
4127
4211
  routeFilesBySpecifier.set(specifier, {
4128
4212
  routePath: route.path,
4129
- sourcePath: resolve2(route.sourcePath)
4213
+ sourcePath: resolve3(route.sourcePath)
4130
4214
  });
4131
4215
  return `import { route as ${route.id} } from ${JSON.stringify(specifier)};`;
4132
4216
  }).join(`
4133
4217
  `);
4134
4218
  return {
4135
- appExpression: emitRouteNode(tree, ""),
4219
+ appExpression: emitRouteNode(tree, "", includeRootCatchAll),
4136
4220
  exportName: `furinApp_${instanceId}`,
4137
4221
  imports
4138
4222
  };
4139
4223
  }
4140
- async function serverRegistrySource(instances, routeFilesBySpecifier) {
4224
+ async function serverRegistrySource(instances, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4141
4225
  routeFilesBySpecifier.clear();
4142
- const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier)));
4226
+ const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll)));
4143
4227
  return `import { Elysia } from "elysia";
4144
4228
  ${generated.map(({ imports }) => imports).join(`
4145
4229
  `)}
@@ -4148,6 +4232,15 @@ ${generated.map(({ appExpression, exportName }) => `export const ${exportName} =
4148
4232
  `)}
4149
4233
  `;
4150
4234
  }
4235
+ async function materializedRouteModuleSource(instance) {
4236
+ const routeFilesBySpecifier = new Map;
4237
+ const source = await serverRegistrySource([instance], routeFilesBySpecifier, true, false);
4238
+ await validateRouteModules(routeFilesBySpecifier.values());
4239
+ const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4240
+ return `${source}
4241
+ export { ${exportName} as furinApp };
4242
+ `;
4243
+ }
4151
4244
  function validateRouteParams(path, schemas) {
4152
4245
  const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
4153
4246
  if (pathParams.length === 0) {
@@ -4170,13 +4263,13 @@ function routeModuleCache() {
4170
4263
  return cache;
4171
4264
  }
4172
4265
  function findPackageRoot(sourcePath) {
4173
- const fallback = dirname3(sourcePath);
4266
+ const fallback = dirname4(sourcePath);
4174
4267
  let directory = fallback;
4175
- while (dirname3(directory) !== directory) {
4268
+ while (dirname4(directory) !== directory) {
4176
4269
  if (existsSync4(join4(directory, "package.json"))) {
4177
4270
  return directory;
4178
4271
  }
4179
- directory = dirname3(directory);
4272
+ directory = dirname4(directory);
4180
4273
  }
4181
4274
  return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4182
4275
  }
@@ -4199,7 +4292,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4199
4292
  continue;
4200
4293
  }
4201
4294
  try {
4202
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname3(dependencyPath)));
4295
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname4(dependencyPath)));
4203
4296
  if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4204
4297
  resolvedImports.push(resolvedImport);
4205
4298
  }
@@ -4289,18 +4382,30 @@ function primaryInstance(instances) {
4289
4382
  }
4290
4383
  return instance;
4291
4384
  }
4292
- function serverProxySource(instance) {
4385
+ function serverProxySource(instance, includeRootCatchAll) {
4293
4386
  const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4294
- return `export { ${exportName} as furinApp } from ${JSON.stringify(ROUTES_REGISTRY_SPECIFIER)};
4387
+ const registry = includeRootCatchAll ? ROUTES_REGISTRY_SPECIFIER : COMPOSABLE_ROUTES_REGISTRY_SPECIFIER;
4388
+ return `export { ${exportName} as furinApp } from ${JSON.stringify(registry)};
4295
4389
  `;
4296
4390
  }
4297
4391
  function createRoutesPlugin(options) {
4298
4392
  const routeFilesBySpecifier = new Map;
4299
4393
  const routeFilesByResolvedPath = new Map;
4300
- const registryVirtualPath = join4(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4301
- const instancesBySpecifier = new Map(options.instances.map((instance) => [
4302
- routeModuleSpecifier(instance),
4303
- { instance, namespace: instanceNamespace(instance) }
4394
+ const registryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4395
+ const composableRegistryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4396
+ const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4397
+ [
4398
+ routeModuleSpecifier(instance),
4399
+ { includeRootCatchAll: true, instance, namespace: instanceNamespace(instance) }
4400
+ ],
4401
+ [
4402
+ composableRouteModuleSpecifier(instance),
4403
+ {
4404
+ includeRootCatchAll: false,
4405
+ instance,
4406
+ namespace: `${instanceNamespace(instance)}-composable`
4407
+ }
4408
+ ]
4304
4409
  ]));
4305
4410
  return {
4306
4411
  name: `furin-routes-${options.target}`,
@@ -4321,12 +4426,12 @@ function createRoutesPlugin(options) {
4321
4426
  }
4322
4427
  return { namespace: registered.namespace, path };
4323
4428
  });
4324
- build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, () => ({
4429
+ build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, ({ path }) => ({
4325
4430
  namespace: "file",
4326
- path: registryVirtualPath
4431
+ path: path === ROUTES_REGISTRY_SPECIFIER ? registryVirtualPath : composableRegistryVirtualPath
4327
4432
  }));
4328
- build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async () => {
4329
- const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier);
4433
+ build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async ({ path }) => {
4434
+ const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier, false, path === registryVirtualPath);
4330
4435
  await validateRouteModules(routeFilesBySpecifier.values());
4331
4436
  return { contents, loader: "ts" };
4332
4437
  });
@@ -4347,12 +4452,12 @@ function createRoutesPlugin(options) {
4347
4452
  return {
4348
4453
  contents: await Bun.file(routeFile.sourcePath).text(),
4349
4454
  loader: detectLoaderFromPath(routeFile.sourcePath),
4350
- resolveDir: dirname3(routeFile.sourcePath)
4455
+ resolveDir: dirname4(routeFile.sourcePath)
4351
4456
  };
4352
4457
  });
4353
- for (const { instance, namespace } of instancesBySpecifier.values()) {
4458
+ for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
4354
4459
  build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
4355
- contents: serverProxySource(instance),
4460
+ contents: serverProxySource(instance, includeRootCatchAll),
4356
4461
  loader: "ts"
4357
4462
  }));
4358
4463
  }
@@ -4360,6 +4465,43 @@ function createRoutesPlugin(options) {
4360
4465
  };
4361
4466
  }
4362
4467
 
4468
+ // src/build/server-app-entry.ts
4469
+ async function materializeServerAppEntry(options) {
4470
+ ensureDir(options.outDir);
4471
+ const apps = await Promise.all(options.apps.map(async (app, index) => {
4472
+ const instance = options.instances[index];
4473
+ if (!instance) {
4474
+ throw new Error(`[furin] Missing route instance for server app ${index}.`);
4475
+ }
4476
+ const routePath = join5(options.outDir, `_furin-routes-${index}.ts`);
4477
+ writeFileSync(routePath, await materializedRouteModuleSource(instance));
4478
+ return { ...app, nativeRoutes: toPosixPath(routePath) };
4479
+ }));
4480
+ const entryPath = join5(options.outDir, "_furin-app.ts");
4481
+ writeFileSync(entryPath, buildEntrySource({
4482
+ apps,
4483
+ headerComment: options.headerComment,
4484
+ mode: "app",
4485
+ serverEntry: options.serverEntry
4486
+ }));
4487
+ return entryPath;
4488
+ }
4489
+ function serverBootSource(appEntry) {
4490
+ return `// Auto-generated by furin build - do not edit
4491
+ import app, { port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4492
+
4493
+ if (typeof startServer === "function") {
4494
+ await startServer();
4495
+ } else if (app && typeof app.listen === "function" && !app.server) {
4496
+ const serverPort = process.env.PORT === undefined
4497
+ ? typeof port === "number" ? port : 3000
4498
+ : Number(process.env.PORT);
4499
+ app.listen(serverPort);
4500
+ console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4501
+ }
4502
+ `;
4503
+ }
4504
+
4363
4505
  // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
4364
4506
  init_sourcemap_codec();
4365
4507
  var BitSet = class BitSet {
@@ -6815,13 +6957,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6815
6957
  }
6816
6958
 
6817
6959
  // src/adapter/runtime-build.ts
6818
- import { existsSync as existsSync6, writeFileSync as writeFileSync3 } from "fs";
6819
- import { basename as basename4, dirname as dirname6, join as join7, relative as relative4, resolve as resolve3 } from "path";
6960
+ import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
6961
+ import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute2, join as join8, relative as relative5, resolve as resolve5 } from "path";
6820
6962
  import { fileURLToPath as fileURLToPath5 } from "url";
6821
6963
 
6822
6964
  // src/build/client.ts
6823
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync } from "fs";
6824
- import { basename as basename2, dirname as dirname4, join as join5 } from "path";
6965
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6966
+ import { basename as basename2, dirname as dirname5, join as join6, resolve as resolve4 } from "path";
6825
6967
 
6826
6968
  // src/plugin/transform-client.ts
6827
6969
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7871,6 +8013,7 @@ if (__deferred && __deferred._chunks) {
7871
8013
 
7872
8014
  // src/build/client.ts
7873
8015
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8016
+ var ROUTER_PROVIDER_PATH = resolve4(import.meta.dir, "../client/router/provider.tsx");
7874
8017
  function resolveClientModuleSpecifiers(code) {
7875
8018
  return code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH)).replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
7876
8019
  }
@@ -7888,7 +8031,7 @@ async function buildClient(routes, {
7888
8031
  pagesDir
7889
8032
  }) {
7890
8033
  const dirName = clientDirName ?? "client";
7891
- const clientDir = join5(outDir, dirName);
8034
+ const clientDir = join6(outDir, dirName);
7892
8035
  if (!existsSync5(outDir)) {
7893
8036
  mkdirSync2(outDir, { recursive: true });
7894
8037
  }
@@ -7896,7 +8039,7 @@ async function buildClient(routes, {
7896
8039
  mkdirSync2(clientDir, { recursive: true });
7897
8040
  }
7898
8041
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
7899
- const hydratePath = join5(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8042
+ const hydratePath = join6(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
7900
8043
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
7901
8044
  console.log("[furin] Building production client bundle\u2026");
7902
8045
  const transformPlugin = {
@@ -7917,6 +8060,20 @@ async function buildClient(routes, {
7917
8060
  });
7918
8061
  }
7919
8062
  };
8063
+ const routerLoggerPlugin = {
8064
+ name: "furin-client-router-logger",
8065
+ setup(build) {
8066
+ build.onResolve({ filter: /^evlog$/ }, ({ importer }) => {
8067
+ if (importer === ROUTER_PROVIDER_PATH) {
8068
+ return { namespace: "furin-client-router-logger", path: "router-logger" };
8069
+ }
8070
+ });
8071
+ build.onLoad({ filter: /.*/, namespace: "furin-client-router-logger" }, () => ({
8072
+ contents: "export const log = { warn: console.warn, error: console.error };",
8073
+ loader: "js"
8074
+ }));
8075
+ }
8076
+ };
7920
8077
  const clientBuildConfig = {
7921
8078
  entrypoints: [hydrateEntry.entrypoint],
7922
8079
  files: hydrateEntry.files,
@@ -7938,6 +8095,7 @@ async function buildClient(routes, {
7938
8095
  plugins: [
7939
8096
  hydrateEntry.plugin,
7940
8097
  ...plugins ?? [],
8098
+ ...!clientLogging ? [routerLoggerPlugin] : [],
7941
8099
  ...pagesDir ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })] : [],
7942
8100
  environmentGuardPlugin("client"),
7943
8101
  transformPlugin
@@ -7956,8 +8114,8 @@ async function buildClient(routes, {
7956
8114
  if (result.metafile === undefined) {
7957
8115
  throw new Error("[furin] client build did not produce the requested metafile");
7958
8116
  }
7959
- mkdirSync2(dirname4(metafilePath), { recursive: true });
7960
- writeFileSync(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8117
+ mkdirSync2(dirname5(metafilePath), { recursive: true });
8118
+ writeFileSync2(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
7961
8119
  `);
7962
8120
  console.log(`[furin] Client metafile: ${metafilePath}`);
7963
8121
  }
@@ -10167,7 +10325,7 @@ var FRAME_VERSION = 3;
10167
10325
  var MAX_FRAME_BYTES = 1024 * 1024;
10168
10326
  var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
10169
10327
  var RSC_DESCRIPTOR = "__furinRsc";
10170
- function isPlainObject3(value) {
10328
+ function isPlainObject4(value) {
10171
10329
  const prototype = Object.getPrototypeOf(value);
10172
10330
  return prototype === Object.prototype || prototype === null;
10173
10331
  }
@@ -10196,7 +10354,7 @@ function extractRscSources(value, sources, seen, idPrefix) {
10196
10354
  }
10197
10355
  return result;
10198
10356
  }
10199
- if (!isPlainObject3(value)) {
10357
+ if (!isPlainObject4(value)) {
10200
10358
  return value;
10201
10359
  }
10202
10360
  const result = {};
@@ -10276,7 +10434,7 @@ function containsRscSourceInner(value, seen) {
10276
10434
  if (Array.isArray(value)) {
10277
10435
  return value.some((entry) => containsRscSourceInner(entry, seen));
10278
10436
  }
10279
- return isPlainObject3(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10437
+ return isPlainObject4(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10280
10438
  }
10281
10439
  function serializeRouteFrames(data, deferredKeys) {
10282
10440
  const sources = [];
@@ -11180,13 +11338,17 @@ function injectInstrumentationClient(html, prefix) {
11180
11338
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11181
11339
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
11182
11340
  var ROUTE_CTX_RESERVED_KEYS = new Set([
11341
+ "catch",
11183
11342
  "children",
11343
+ "finally",
11184
11344
  "key",
11185
11345
  "params",
11186
11346
  "path",
11187
11347
  "query",
11188
11348
  "ref",
11189
- "requestData"
11349
+ "requestData",
11350
+ "then",
11351
+ "toJSON"
11190
11352
  ]);
11191
11353
  function assertPublicLoaderKey(key) {
11192
11354
  if (key.startsWith(FURIN_RESERVED_KEY_PREFIX)) {
@@ -11220,7 +11382,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
11220
11382
  if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
11221
11383
  return Reflect.get(target, prop);
11222
11384
  }
11223
- if (Object.hasOwn(target, prop)) {
11385
+ if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
11224
11386
  return target[prop];
11225
11387
  }
11226
11388
  let entry = cache.get(prop);
@@ -11262,7 +11424,7 @@ function createRequestLoaderContext(ctx) {
11262
11424
  get: (name) => headers.get(name),
11263
11425
  has: (name) => headers.has(name)
11264
11426
  }),
11265
- log: useLogger3(),
11427
+ log: getLogger(),
11266
11428
  params: ctx.params,
11267
11429
  path: ctx.path,
11268
11430
  query: ctx.query,
@@ -11387,7 +11549,7 @@ async function normalizeLoaderError(err, headers) {
11387
11549
  return { error: err, headers, message, status, type: "error" };
11388
11550
  }
11389
11551
  if (isFurinRscRenderError(err)) {
11390
- useLogger3().error(err);
11552
+ getLogger().error(err);
11391
11553
  return {
11392
11554
  error: err,
11393
11555
  headers,
@@ -11407,7 +11569,7 @@ async function normalizeLoaderError(err, headers) {
11407
11569
  async function runLoadersInternal(route, ctx, includeRequestData) {
11408
11570
  try {
11409
11571
  const requestData = includeRequestData ? runRequestLoaderData(route, ctx) : undefined;
11410
- const ctxRecord = includeRequestData ? { ...ctx, log: useLogger3() } : createPublicLoaderContext(ctx);
11572
+ const ctxRecord = includeRequestData ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, { log: getLogger() }) : createPublicLoaderContext(ctx);
11411
11573
  const loaderMap = new Map;
11412
11574
  let accumulatedParentPromise = Promise.resolve({});
11413
11575
  let loaderIndex = 0;
@@ -11422,7 +11584,7 @@ async function runLoadersInternal(route, ctx, includeRequestData) {
11422
11584
  if (IS_DEV) {
11423
11585
  for (const key of Object.keys(own)) {
11424
11586
  if (Object.hasOwn(acc, key)) {
11425
- useLogger3().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11587
+ getLogger().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11426
11588
  }
11427
11589
  }
11428
11590
  }
@@ -11466,7 +11628,7 @@ function createPublicLoaderContext(ctx) {
11466
11628
  Object.defineProperties(publicContext, {
11467
11629
  cookie: { enumerable: true, get: fail },
11468
11630
  headers: { enumerable: true, get: fail },
11469
- log: { enumerable: true, value: useLogger3() },
11631
+ log: { enumerable: true, value: getLogger() },
11470
11632
  params: { enumerable: true, value: ctx.params },
11471
11633
  path: { enumerable: true, value: ctx.path },
11472
11634
  query: { enumerable: true, value: ctx.query },
@@ -11884,7 +12046,7 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
11884
12046
  if (prepared instanceof Response) {
11885
12047
  return prepared;
11886
12048
  }
11887
- useLogger3().set({
12049
+ getLogger().set({
11888
12050
  furin: {
11889
12051
  cache: mode === "isr" ? "revalidated" : "miss",
11890
12052
  loader_ms: prepared.loader_ms,
@@ -11918,6 +12080,118 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
11918
12080
  `;
11919
12081
  }
11920
12082
 
12083
+ // src/server/render/static-params.ts
12084
+ import { dirname as dirname7, relative as relative4 } from "path";
12085
+ init_patterns();
12086
+ var STATIC_PARAMS_CONCURRENCY = 4;
12087
+ function collectStaticParamsStages(route) {
12088
+ const stages = [];
12089
+ for (const [index, entry] of route.routeChain.entries()) {
12090
+ if (entry.staticParams) {
12091
+ stages.push({ ancestors: route.routeChain.slice(0, index), run: entry.staticParams });
12092
+ }
12093
+ }
12094
+ if (route.page.staticParams) {
12095
+ stages.push({ ancestors: route.routeChain, run: route.page.staticParams });
12096
+ }
12097
+ return stages;
12098
+ }
12099
+ function ancestorPattern(route, ancestors) {
12100
+ const rootSourcePath = route.routeChain[0]?.sourcePath;
12101
+ const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
12102
+ if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12103
+ return route.pattern;
12104
+ }
12105
+ const pagesDir = dirname7(rootSourcePath);
12106
+ const ancestorDir = dirname7(ancestorSourcePath);
12107
+ if (ancestorDir === pagesDir) {
12108
+ return "/";
12109
+ }
12110
+ return filePathToPattern(`${relative4(pagesDir, ancestorDir)}/index.tsx`);
12111
+ }
12112
+ function createBuildContext(pattern, params, origin) {
12113
+ const path = resolvePath(pattern, params);
12114
+ return {
12115
+ cookie: {},
12116
+ headers: {},
12117
+ params,
12118
+ path,
12119
+ query: {},
12120
+ redirect: (url, status) => new Response(null, { headers: { Location: url }, status: status ?? 302 }),
12121
+ request: new Request(new URL(path, origin)),
12122
+ set: { headers: {} }
12123
+ };
12124
+ }
12125
+ async function runAncestorLoaders(route, ancestors, params, origin) {
12126
+ const pattern = ancestorPattern(route, ancestors);
12127
+ const result = await runPublicLoaders({
12128
+ ...route,
12129
+ page: { ...route.page, loader: undefined },
12130
+ pattern,
12131
+ routeChain: ancestors
12132
+ }, createBuildContext(pattern, params, origin));
12133
+ if (result.type === "redirect") {
12134
+ throw result.response;
12135
+ }
12136
+ if (result.type === "not-found") {
12137
+ throw result.error;
12138
+ }
12139
+ if (result.type === "error") {
12140
+ throw result.error;
12141
+ }
12142
+ const data = {};
12143
+ for (const [key, value] of Object.entries(result.syncData)) {
12144
+ if (key !== "params" && key !== "path" && key !== "query") {
12145
+ data[key] = value;
12146
+ }
12147
+ }
12148
+ Object.assign(data, result.deferredPromises);
12149
+ return data;
12150
+ }
12151
+ function createStaticParamsContext(route, ancestors, params, origin) {
12152
+ const target = { params };
12153
+ const fields = new Map;
12154
+ let parentData;
12155
+ return new Proxy(target, {
12156
+ get(context, property) {
12157
+ if (typeof property !== "string" || Object.hasOwn(context, property)) {
12158
+ return Reflect.get(context, property);
12159
+ }
12160
+ if (property === "then" || property === "catch" || property === "finally" || property === "toJSON") {
12161
+ return;
12162
+ }
12163
+ let field = fields.get(property);
12164
+ if (!field) {
12165
+ parentData ??= runAncestorLoaders(route, ancestors, params, origin);
12166
+ field = parentData.then((data) => data[property]);
12167
+ fields.set(property, field);
12168
+ }
12169
+ return field;
12170
+ }
12171
+ });
12172
+ }
12173
+ function hasStaticParams(route) {
12174
+ return route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined);
12175
+ }
12176
+ async function resolveStaticParams(route, origin) {
12177
+ const stages = collectStaticParamsStages(route);
12178
+ if (stages.length === 0) {
12179
+ return;
12180
+ }
12181
+ let branches = [{}];
12182
+ for (const stage of stages) {
12183
+ const branchValues = await mapWithConcurrency(branches, STATIC_PARAMS_CONCURRENCY, async (params) => {
12184
+ const values = await stage.run(createStaticParamsContext(route, stage.ancestors, params, origin));
12185
+ if (!Array.isArray(values)) {
12186
+ throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
12187
+ }
12188
+ return values.map((value) => ({ ...params, ...value }));
12189
+ });
12190
+ branches = branchValues.flat();
12191
+ }
12192
+ return branches;
12193
+ }
12194
+
11921
12195
  // src/server/render/ssg.ts
11922
12196
  async function prerenderRoute(route, params, root, origin, mode, basePath, searchRoutes, requestContext) {
11923
12197
  const renderResult = await renderForPath(route, params, root, origin, mode, basePath, searchRoutes, undefined, requestContext);
@@ -11970,12 +12244,8 @@ async function buildRoutePrerenders(routes, root, origin, basePath) {
11970
12244
  let paramSets;
11971
12245
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
11972
12246
  paramSets = [{}];
11973
- } else if (route.page.staticParams) {
11974
- const resolvedParams = await route.page.staticParams();
11975
- if (!Array.isArray(resolvedParams)) {
11976
- throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
11977
- }
11978
- paramSets = resolvedParams;
12247
+ } else if (hasStaticParams(route)) {
12248
+ paramSets = await resolveStaticParams(route, origin) ?? [];
11979
12249
  } else {
11980
12250
  continue;
11981
12251
  }
@@ -11998,10 +12268,10 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
11998
12268
  const snapshot = {};
11999
12269
  const searchRoutes = createSearchRouteMetadata(routes);
12000
12270
  for (const route of routes) {
12001
- if (route.mode !== "ssg" || !route.page.staticParams || hasRequestLoader(route)) {
12271
+ if (route.mode !== "ssg" || !hasStaticParams(route) || hasRequestLoader(route)) {
12002
12272
  continue;
12003
12273
  }
12004
- const paramSets = await route.page.staticParams();
12274
+ const paramSets = await resolveStaticParams(route, origin) ?? [];
12005
12275
  for (const params of paramSets) {
12006
12276
  const result = await prerenderSSG(route, params, root, origin, basePath, searchRoutes);
12007
12277
  if (!(result instanceof Response)) {
@@ -12013,8 +12283,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12013
12283
  }
12014
12284
 
12015
12285
  // src/rsc/build/index.ts
12016
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
12017
- import { basename as basename3, join as join6 } from "path";
12286
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
12287
+ import { basename as basename3, join as join7 } from "path";
12018
12288
  import { fileURLToPath as fileURLToPath4 } from "url";
12019
12289
 
12020
12290
  // src/rsc/version.ts
@@ -12062,7 +12332,7 @@ function assertInstalledRscVersions() {
12062
12332
  // src/rsc/build/index.ts
12063
12333
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12064
12334
  await assertInstalledRscVersions();
12065
- const graphDir = join6(outDir, "rsc");
12335
+ const graphDir = join7(outDir, "rsc");
12066
12336
  mkdirSync3(graphDir, { recursive: true });
12067
12337
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12068
12338
  const entrypoints = [
@@ -12124,13 +12394,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12124
12394
  }
12125
12395
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12126
12396
  const manifest = { buildId, clientReferences: [], css };
12127
- writeFileSync2(join6(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12397
+ writeFileSync3(join7(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12128
12398
  return manifest;
12129
12399
  }
12130
12400
 
12131
12401
  // src/adapter/runtime-build.ts
12132
- var _pkgRoot2 = dirname6(dirname6(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12133
- var _pkgSrcDir2 = existsSync6(join7(_pkgRoot2, "src", "furin.ts")) ? join7(_pkgRoot2, "src") : join7(_pkgRoot2, "dist");
12402
+ var _pkgRoot2 = dirname8(dirname8(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12403
+ var _pkgSrcDir2 = existsSync6(join8(_pkgRoot2, "src", "furin.ts")) ? join8(_pkgRoot2, "src") : join8(_pkgRoot2, "dist");
12134
12404
  var _ext2 = ".ts";
12135
12405
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12136
12406
  var ANY_MODULE_RE = /.*/;
@@ -12208,12 +12478,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12208
12478
  `);
12209
12479
  }
12210
12480
  function stableFingerprintPath(path, projectRoot) {
12211
- const projectPath = relative4(projectRoot, path);
12212
- if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12481
+ const projectPath = relative5(projectRoot, path);
12482
+ if (!isAbsolute2(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12213
12483
  return `app/${toPosixPath(projectPath)}`;
12214
12484
  }
12215
- const frameworkPath = relative4(_pkgRoot2, path);
12216
- if (frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12485
+ const frameworkPath = relative5(_pkgRoot2, path);
12486
+ if (!isAbsolute2(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12217
12487
  return `furin/${toPosixPath(frameworkPath)}`;
12218
12488
  }
12219
12489
  return `external/${basename4(path)}`;
@@ -12238,7 +12508,7 @@ function buildCompileMetadata(root, routes) {
12238
12508
  }
12239
12509
  function pprRuntimePlugin(apps) {
12240
12510
  const enabled = apps.some((app) => app.routes.some((route) => route.mode !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
12241
- const pprPath = resolve3(_pkgSrcDir2, "server/render/ppr-route.ts");
12511
+ const pprPath = resolve5(_pkgSrcDir2, "server/render/ppr-route.ts");
12242
12512
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
12243
12513
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
12244
12514
  return {
@@ -12250,7 +12520,7 @@ function pprRuntimePlugin(apps) {
12250
12520
  return;
12251
12521
  }
12252
12522
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12253
- const absolute = resolve3(dirname6(importer.split("?")[0]), path);
12523
+ const absolute = resolve5(dirname8(importer.split("?")[0]), path);
12254
12524
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12255
12525
  return;
12256
12526
  }
@@ -12270,7 +12540,7 @@ function isFrameworkRuntimeImporter(importer) {
12270
12540
  if (importer === "") {
12271
12541
  return false;
12272
12542
  }
12273
- const fromRuntimeRoot = relative4(_pkgSrcDir2, importer.split("?")[0]);
12543
+ const fromRuntimeRoot = relative5(_pkgSrcDir2, importer.split("?")[0]);
12274
12544
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12275
12545
  }
12276
12546
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12282,7 +12552,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12282
12552
  basePath: prefix,
12283
12553
  clientDirName,
12284
12554
  clientLogging: options.clientLogging ?? false,
12285
- metafilePath: options.analyze ? join7(dirname6(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12555
+ metafilePath: options.analyze ? join8(dirname8(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12286
12556
  optimizeImports: options.optimizeImports,
12287
12557
  outDir: targetDir,
12288
12558
  pagesDir: app.pagesDir,
@@ -12294,9 +12564,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12294
12564
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12295
12565
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12296
12566
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12297
- const clientDir = join7(targetDir, clientDirName);
12567
+ const clientDir = join8(targetDir, clientDirName);
12298
12568
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12299
- writeFileSync3(join7(clientDir, "index.html"), indexHtml);
12569
+ writeFileSync4(join8(clientDir, "index.html"), indexHtml);
12300
12570
  setProductionTemplateContent(indexHtml);
12301
12571
  ssgRouteCache().clear();
12302
12572
  let ssgCache;
@@ -12316,9 +12586,10 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12316
12586
  entryApp: {
12317
12587
  buildId,
12318
12588
  clientLogging: options.clientLogging ?? false,
12589
+ deploymentTarget: targetName === "vercel" ? "vercel" : undefined,
12319
12590
  embed: options.compile === "embed" ? { clientDir } : undefined,
12320
12591
  modulePaths,
12321
- nativeRoutes: routeModuleSpecifier(app),
12592
+ nativeRoutes: composableRouteModuleSpecifier(app),
12322
12593
  prefix,
12323
12594
  rootConventions,
12324
12595
  rootPath: root.path,
@@ -12353,15 +12624,10 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12353
12624
  }
12354
12625
 
12355
12626
  // src/adapter/bun.ts
12356
- function generateDiskEntry(options) {
12357
- ensureDir(options.outDir);
12358
- const source = buildEntrySource({
12359
- apps: options.apps.map(({ embed: _embed, ...context }) => context),
12360
- headerComment: "// Auto-generated by furin build - do not edit",
12361
- serverEntry: options.serverEntry
12362
- });
12363
- const entryPath = join8(options.outDir, "server.ts");
12364
- return createVirtualBuildEntry(entryPath, source, "ts");
12627
+ function generateBootEntry(appEntry, outDir, filename) {
12628
+ ensureDir(outDir);
12629
+ const entryPath = join9(outDir, filename);
12630
+ return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12365
12631
  }
12366
12632
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
12367
12633
  if (compile !== "embed") {
@@ -12373,6 +12639,34 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12373
12639
  }
12374
12640
  return assets;
12375
12641
  }
12642
+ function compiledServerFilename(platform) {
12643
+ return platform === "win32" ? "server.exe" : "server";
12644
+ }
12645
+ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12646
+ if (!serverEntry) {
12647
+ return;
12648
+ }
12649
+ const contexts = options.compile ? prepareCompileEntryApps({
12650
+ apps: entryApps,
12651
+ outDir: targetDir,
12652
+ publicDir,
12653
+ serverEntry
12654
+ }) : entryApps.map(({ embed: _embed, ...context }) => ({
12655
+ ...context,
12656
+ extraContext: [
12657
+ ...context.extraContext ?? [],
12658
+ ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12659
+ ],
12660
+ templateHtml: readFileSync4(join9(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12661
+ }));
12662
+ return await materializeServerAppEntry({
12663
+ apps: contexts,
12664
+ headerComment: "// Auto-generated by furin build - do not edit",
12665
+ instances: apps,
12666
+ outDir: targetDir,
12667
+ serverEntry
12668
+ });
12669
+ }
12376
12670
  async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12377
12671
  if (options.compile && !serverEntry) {
12378
12672
  throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
@@ -12382,27 +12676,24 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12382
12676
  }
12383
12677
  const target = "bun";
12384
12678
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12385
- const targetDir = resolve4(rootDir, targetManifest.targetDir);
12679
+ const targetDir = resolve6(rootDir, targetManifest.targetDir);
12386
12680
  rmSync2(targetDir, { force: true, recursive: true });
12387
12681
  ensureDir(targetDir);
12388
- const publicDir = existsSync7(join8(rootDir, "public")) ? join8(rootDir, "public") : undefined;
12682
+ const publicDir = existsSync7(join9(rootDir, "public")) ? join9(rootDir, "public") : undefined;
12389
12683
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12390
12684
  targetManifest.buildId = headlineBuildId;
12391
12685
  if (serverEntry) {
12392
- targetManifest.rscManifestPath = toPosixPath(join8(targetManifest.targetDir, "rsc", "manifest.json"));
12686
+ targetManifest.rscManifestPath = toPosixPath(join9(targetManifest.targetDir, "rsc", "manifest.json"));
12393
12687
  }
12394
- const targetPublicDir = publicDir ? join8(targetDir, "public") : undefined;
12688
+ const targetPublicDir = publicDir ? join9(targetDir, "public") : undefined;
12395
12689
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12396
12690
  copyDirRecursive(publicDir, targetPublicDir);
12397
12691
  }
12398
- if (options.compile && serverEntry) {
12399
- const outfile = join8(targetDir, "server");
12400
- const entry = generateCompileEntry({
12401
- apps: entryApps,
12402
- outDir: targetDir,
12403
- publicDir,
12404
- serverEntry
12405
- });
12692
+ const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12693
+ if (options.compile && serverEntry && appEntry) {
12694
+ const serverFilename = compiledServerFilename(process.platform);
12695
+ const outfile = join9(targetDir, serverFilename);
12696
+ const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12406
12697
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12407
12698
  await runBunBuild({
12408
12699
  bytecode: true,
@@ -12419,17 +12710,18 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12419
12710
  ...options.plugins ?? [],
12420
12711
  createRoutesPlugin({ instances: apps, target: "server" }),
12421
12712
  isomorphicTransformPlugin("server"),
12422
- environmentGuardPlugin("ssr")
12713
+ environmentGuardPlugin("ssr"),
12714
+ elysiaAot(appEntry)
12423
12715
  ],
12424
12716
  sourcemap: "none",
12425
12717
  splitting: true,
12426
12718
  target: "bun"
12427
12719
  });
12428
12720
  console.log(`[furin] Server binary: ${outfile}`);
12429
- targetManifest.serverPath = toPosixPath(join8(targetManifest.targetDir, "server"));
12721
+ targetManifest.serverPath = toPosixPath(join9(targetManifest.targetDir, serverFilename));
12430
12722
  if (options.compile === "embed") {
12431
12723
  for (const app of apps) {
12432
- rmSync2(join8(targetDir, clientDirNameForPrefix(app.prefix)), {
12724
+ rmSync2(join9(targetDir, clientDirNameForPrefix(app.prefix)), {
12433
12725
  force: true,
12434
12726
  recursive: true
12435
12727
  });
@@ -12437,12 +12729,8 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12437
12729
  targetManifest.clientDir = null;
12438
12730
  targetManifest.templatePath = null;
12439
12731
  }
12440
- } else if (serverEntry) {
12441
- const entry = generateDiskEntry({
12442
- apps: entryApps,
12443
- outDir: targetDir,
12444
- serverEntry
12445
- });
12732
+ } else if (serverEntry && appEntry) {
12733
+ const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12446
12734
  await runBunBuild({
12447
12735
  entrypoints: [entry.entrypoint],
12448
12736
  files: entry.files,
@@ -12456,30 +12744,31 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12456
12744
  ...options.plugins ?? [],
12457
12745
  createRoutesPlugin({ instances: apps, target: "server" }),
12458
12746
  isomorphicTransformPlugin("server"),
12459
- environmentGuardPlugin("ssr")
12747
+ environmentGuardPlugin("ssr"),
12748
+ elysiaAot(appEntry)
12460
12749
  ],
12461
12750
  sourcemap: "none",
12462
12751
  target: "bun"
12463
12752
  });
12464
- console.log(`[furin] Server bundle: ${toPosixPath(join8(targetManifest.targetDir, "server.js"))}`);
12465
- targetManifest.serverPath = toPosixPath(join8(targetManifest.targetDir, "server.js"));
12753
+ console.log(`[furin] Server bundle: ${toPosixPath(join9(targetManifest.targetDir, "server.js"))}`);
12754
+ targetManifest.serverPath = toPosixPath(join9(targetManifest.targetDir, "server.js"));
12466
12755
  }
12467
12756
  return targetManifest;
12468
12757
  }
12469
12758
 
12470
12759
  // src/adapter/package.ts
12471
- import { existsSync as existsSync8, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
12472
- import { join as join9, relative as relative5, resolve as resolve5 } from "path";
12760
+ import { existsSync as existsSync8, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
12761
+ import { join as join10, relative as relative6, resolve as resolve7 } from "path";
12473
12762
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12474
12763
  const { prefix, root, routes, pagesDir } = app;
12475
12764
  const modulePaths = routeSourcePaths(app);
12476
- const targetDir = join9(buildRoot, "package");
12765
+ const targetDir = join10(buildRoot, "package");
12477
12766
  rmSync3(targetDir, { force: true, recursive: true });
12478
12767
  ensureDir(targetDir);
12479
12768
  const { entryChunk, cssChunks } = await buildClient(routes, {
12480
12769
  basePath: prefix,
12481
12770
  clientLogging: options.clientLogging ?? false,
12482
- metafilePath: options.analyze ? join9(buildRoot, "analysis", "package-client.json") : undefined,
12771
+ metafilePath: options.analyze ? join10(buildRoot, "analysis", "package-client.json") : undefined,
12483
12772
  optimizeImports: options.optimizeImports,
12484
12773
  outDir: targetDir,
12485
12774
  pagesDir,
@@ -12491,13 +12780,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12491
12780
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12492
12781
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12493
12782
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12494
- const clientDir = join9(targetDir, "client");
12495
- const publicDir = join9(rootDir, "public");
12783
+ const clientDir = join10(targetDir, "client");
12784
+ const publicDir = join10(rootDir, "public");
12496
12785
  if (existsSync8(publicDir)) {
12497
- copyDirRecursive(publicDir, join9(targetDir, "public"));
12786
+ copyDirRecursive(publicDir, join10(targetDir, "public"));
12498
12787
  }
12499
12788
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12500
- writeFileSync4(join9(clientDir, "index.html"), indexHtml);
12789
+ writeFileSync5(join10(clientDir, "index.html"), indexHtml);
12501
12790
  setProductionTemplateContent(indexHtml);
12502
12791
  ssgRouteCache().clear();
12503
12792
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12522,7 +12811,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12522
12811
  buildId,
12523
12812
  clientLogging: options.clientLogging ?? false,
12524
12813
  modulePaths,
12525
- nativeRoutes: routeModuleSpecifier(app),
12814
+ nativeRoutes: composableRouteModuleSpecifier(app),
12526
12815
  prefix,
12527
12816
  rootConventions,
12528
12817
  rootPath: root.path,
@@ -12534,7 +12823,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12534
12823
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12535
12824
  mode: "register"
12536
12825
  });
12537
- const registerEntry = join9(targetDir, "register.ts");
12826
+ const registerEntry = join10(targetDir, "register.ts");
12538
12827
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12539
12828
  const result = await runBunBuild({
12540
12829
  entrypoints: [register.entrypoint],
@@ -12554,7 +12843,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12554
12843
  if (!result.success) {
12555
12844
  throw new AggregateError(result.logs, "[furin] package register build failed");
12556
12845
  }
12557
- const relativePagesDir = toPosixPath(relative5(targetDir, resolve5(rootDir, pagesDir)));
12846
+ const relativePagesDir = toPosixPath(relative6(targetDir, resolve7(rootDir, pagesDir)));
12558
12847
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12559
12848
  import { fileURLToPath } from "node:url";
12560
12849
  import { furin } from "@teyik0/furin";
@@ -12581,7 +12870,7 @@ export function createFurinApp(options = {}) {
12581
12870
 
12582
12871
  export const prefix = ${JSON.stringify(prefix)};
12583
12872
  `;
12584
- writeFileSync4(join9(targetDir, "index.js"), factorySource);
12873
+ writeFileSync5(join10(targetDir, "index.js"), factorySource);
12585
12874
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12586
12875
 
12587
12876
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12589,29 +12878,29 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12589
12878
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12590
12879
  export declare const prefix: string;
12591
12880
  `;
12592
- writeFileSync4(join9(targetDir, "index.d.ts"), dtsSource);
12593
- console.log(`[furin] Package artifact: ${toPosixPath(relative5(rootDir, targetDir))}`);
12881
+ writeFileSync5(join10(targetDir, "index.d.ts"), dtsSource);
12882
+ console.log(`[furin] Package artifact: ${toPosixPath(relative6(rootDir, targetDir))}`);
12594
12883
  return {
12595
12884
  buildId,
12596
12885
  generatedAt: new Date().toISOString(),
12597
12886
  prefix,
12598
- targetDir: toPosixPath(relative5(rootDir, targetDir))
12887
+ targetDir: toPosixPath(relative6(rootDir, targetDir))
12599
12888
  };
12600
12889
  }
12601
12890
 
12602
12891
  // src/adapter/static.ts
12603
- import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "fs";
12604
- import { dirname as dirname7, isAbsolute as isAbsolute2, join as join10, relative as relative6, resolve as resolve6, sep as sep2 } from "path";
12892
+ import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
12893
+ import { dirname as dirname9, isAbsolute as isAbsolute3, join as join11, parse as parse3, relative as relative7, resolve as resolve8, sep as sep2, win32 } from "path";
12605
12894
  var STATIC_CONCURRENCY = 4;
12606
12895
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
12607
12896
  var TRAILING_SLASHES_RE = /\/+$/;
12608
12897
  var STATIC_RENDER_ORIGIN = "http://localhost";
12609
12898
  function pathToOutputFile(urlPath, outDir, fileName) {
12610
- const normalizedOutDir = resolve6(outDir);
12899
+ const normalizedOutDir = resolve8(outDir);
12611
12900
  if (urlPath === "/" || urlPath === "") {
12612
- return join10(normalizedOutDir, fileName);
12901
+ return join11(normalizedOutDir, fileName);
12613
12902
  }
12614
- const resolved = resolve6(normalizedOutDir, urlPath.slice(1), fileName);
12903
+ const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
12615
12904
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
12616
12905
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
12617
12906
  }
@@ -12684,22 +12973,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
12684
12973
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
12685
12974
  }
12686
12975
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
12687
- ensureDir(dirname7(htmlOutputFile));
12688
- writeFileSync5(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12976
+ ensureDir(dirname9(htmlOutputFile));
12977
+ writeFileSync6(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12689
12978
  if (staticLocation.spa !== null) {
12690
12979
  const serializedRedirect = await toCrossJSONAsync({
12691
12980
  __furinRedirect: staticLocation.spa
12692
12981
  });
12693
- writeFileSync5(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12982
+ writeFileSync6(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12694
12983
  `);
12695
12984
  }
12696
12985
  renderedRoutes.push(urlPath);
12697
12986
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
12698
12987
  return;
12699
12988
  }
12700
- ensureDir(dirname7(htmlOutputFile));
12701
- writeFileSync5(htmlOutputFile, entry.html);
12702
- writeFileSync5(dataOutputFile, entry.ndjson);
12989
+ ensureDir(dirname9(htmlOutputFile));
12990
+ writeFileSync6(htmlOutputFile, entry.html);
12991
+ writeFileSync6(dataOutputFile, entry.ndjson);
12703
12992
  renderedRoutes.push(urlPath);
12704
12993
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
12705
12994
  } catch (err) {
@@ -12732,13 +13021,13 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
12732
13021
  if (!DYNAMIC_SEGMENT_RE2.test(route.pattern)) {
12733
13022
  return { paramSets: [{}], route };
12734
13023
  }
12735
- if (!route.page.staticParams) {
13024
+ if (!hasStaticParams(route)) {
12736
13025
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
12737
13026
  skippedRoutes.push(route.pattern);
12738
13027
  return { paramSets: null, route };
12739
13028
  }
12740
13029
  try {
12741
- const paramSets = await route.page.staticParams() ?? [];
13030
+ const paramSets = await resolveStaticParams(route, STATIC_RENDER_ORIGIN) ?? [];
12742
13031
  return { paramSets, route };
12743
13032
  } catch (err) {
12744
13033
  return { error: err, paramSets: null, route };
@@ -12805,15 +13094,16 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12805
13094
  if (basePath && !basePath.startsWith("/")) {
12806
13095
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
12807
13096
  }
12808
- const outDir = resolve6(rootDir, staticConfig.outDir ?? "dist");
12809
- const normalizedRoot = resolve6(rootDir);
12810
- const normalizedBuildRoot = resolve6(buildRoot);
12811
- if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
13097
+ const rawOutDir = staticConfig.outDir ?? "dist";
13098
+ const outDir = resolve8(rootDir, rawOutDir);
13099
+ const normalizedRoot = resolve8(rootDir);
13100
+ const normalizedBuildRoot = resolve8(buildRoot);
13101
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
12812
13102
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
12813
13103
  }
12814
13104
  function isOutsideOutDir(target) {
12815
- const rel = relative6(outDir, target);
12816
- return rel.startsWith("..") || isAbsolute2(rel);
13105
+ const rel = relative7(outDir, target);
13106
+ return rel.startsWith("..") || isAbsolute3(rel);
12817
13107
  }
12818
13108
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
12819
13109
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -12829,36 +13119,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12829
13119
  const afterQueueCount = skippedRoutes.length;
12830
13120
  rmSync4(outDir, { force: true, recursive: true });
12831
13121
  ensureDir(outDir);
12832
- const targetDir = join10(buildRoot, "static");
13122
+ const targetDir = join11(buildRoot, "static");
12833
13123
  rmSync4(targetDir, { force: true, recursive: true });
12834
13124
  ensureDir(targetDir);
12835
13125
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
12836
13126
  basePath,
12837
13127
  clientLogging: Boolean(options.clientLogging),
12838
- metafilePath: options.analyze ? join10(buildRoot, "analysis", "static-client.json") : undefined,
13128
+ metafilePath: options.analyze ? join11(buildRoot, "analysis", "static-client.json") : undefined,
12839
13129
  optimizeImports: options.optimizeImports,
12840
13130
  outDir: targetDir,
12841
- pagesDir: dirname7(root.path),
13131
+ pagesDir: dirname9(root.path),
12842
13132
  plugins: options.plugins,
12843
13133
  publicPath,
12844
13134
  reactCompiler: options.reactCompiler,
12845
13135
  rootLayout: root.path
12846
13136
  });
12847
- const publicFavicon = join10(rootDir, "public", "favicon.ico");
13137
+ const publicFavicon = join11(rootDir, "public", "favicon.ico");
12848
13138
  const faviconHref = existsSync9(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
12849
13139
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
12850
13140
  setProductionTemplateContent(shellHtml);
12851
- const publicSrcDir = join10(rootDir, "public");
13141
+ const publicSrcDir = join11(rootDir, "public");
12852
13142
  if (existsSync9(publicSrcDir)) {
12853
13143
  cpSync2(publicSrcDir, outDir, { recursive: true });
12854
13144
  }
12855
- const clientSrcDir = join10(targetDir, "client");
13145
+ const clientSrcDir = join11(targetDir, "client");
12856
13146
  if (existsSync9(clientSrcDir)) {
12857
- cpSync2(clientSrcDir, join10(outDir, "_client"), { recursive: true });
13147
+ cpSync2(clientSrcDir, join11(outDir, "_client"), { recursive: true });
12858
13148
  }
12859
13149
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
12860
13150
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
12861
- writeFileSync5(join10(outDir, "404.html"), shellHtml);
13151
+ writeFileSync6(join11(outDir, "404.html"), shellHtml);
12862
13152
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
12863
13153
  rmSync4(targetDir, { force: true, recursive: true });
12864
13154
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -12872,32 +13162,24 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12872
13162
  }
12873
13163
 
12874
13164
  // src/adapter/vercel.ts
12875
- import {
12876
- cpSync as cpSync3,
12877
- existsSync as existsSync10,
12878
- readFileSync as readFileSync4,
12879
- rmSync as rmSync5,
12880
- statSync as statSync3,
12881
- symlinkSync,
12882
- writeFileSync as writeFileSync6
12883
- } from "fs";
12884
- import { basename as basename5, dirname as dirname8, extname as extname3, join as join11, relative as relative7 } from "path";
13165
+ import { cpSync as cpSync3, existsSync as existsSync10, readFileSync as readFileSync5, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync7 } from "fs";
13166
+ import { basename as basename5, dirname as dirname10, extname as extname3, join as join12, relative as relative8 } from "path";
12885
13167
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
12886
13168
  init_patterns();
12887
13169
  var ISR_PATH_PARAM = "__furin_path";
12888
13170
  var DYNAMIC_SEGMENT_RE3 = /\/:[^/]+|\/\*/;
12889
- var ELYSIA_STATIC_IMPORT_RE = /^@elysiajs\/static$/;
13171
+ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
12890
13172
  var MATCH_ALL_RE = /.*/;
12891
13173
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
12892
13174
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
12893
13175
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
12894
13176
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
12895
- var FURIN_RUNTIME_ROOT2 = dirname8(import.meta.dir);
13177
+ var FURIN_RUNTIME_ROOT2 = dirname10(import.meta.dir);
12896
13178
  function isFurinRuntimeImporter(importer) {
12897
13179
  if (importer === "") {
12898
13180
  return false;
12899
13181
  }
12900
- const fromRuntimeRoot = relative7(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13182
+ const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
12901
13183
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12902
13184
  }
12903
13185
  function vercelRuntimePlugin() {
@@ -12906,11 +13188,11 @@ function vercelRuntimePlugin() {
12906
13188
  setup(build) {
12907
13189
  build.onResolve({ filter: ELYSIA_STATIC_IMPORT_RE }, ({ importer }) => {
12908
13190
  if (!isFurinRuntimeImporter(importer)) {
12909
- throw new Error("[furin] Application @elysiajs/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
13191
+ throw new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
12910
13192
  }
12911
13193
  return {
12912
13194
  namespace: VERCEL_RUNTIME_STUB_NAMESPACE,
12913
- path: "@elysiajs/static"
13195
+ path: "@elysia/static"
12914
13196
  };
12915
13197
  });
12916
13198
  build.onLoad({ filter: MATCH_ALL_RE, namespace: VERCEL_RUNTIME_STUB_NAMESPACE }, () => ({
@@ -12923,8 +13205,8 @@ function vercelRuntimePlugin() {
12923
13205
  };
12924
13206
  }
12925
13207
  function frameworkVersion() {
12926
- const packageRoot = dirname8(dirname8(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
12927
- const packageJson = JSON.parse(readFileSync4(join11(packageRoot, "package.json"), "utf8"));
13208
+ const packageRoot = dirname10(dirname10(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13209
+ const packageJson = JSON.parse(readFileSync5(join12(packageRoot, "package.json"), "utf8"));
12928
13210
  return packageJson.version;
12929
13211
  }
12930
13212
  function serverEntryLoader(serverEntry) {
@@ -12942,10 +13224,15 @@ function serverEntryLoader(serverEntry) {
12942
13224
  }
12943
13225
  function assertDefaultServerExport(serverEntry) {
12944
13226
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
12945
- const { exports } = transpiler.scan(readFileSync4(serverEntry, "utf8"));
13227
+ const { exports, imports } = transpiler.scan(readFileSync5(serverEntry, "utf8"));
12946
13228
  if (!exports.includes("default")) {
12947
13229
  throw new Error(`[furin] Vercel server entry "${toPosixPath(serverEntry)}" must export the Elysia app as default. ` + "Guard app.listen() with `if (import.meta.main)` so the same entry also runs locally.");
12948
13230
  }
13231
+ if (imports.some(({ path }) => ELYSIA_STATIC_IMPORT_RE.test(path))) {
13232
+ throw new AggregateError([
13233
+ new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.")
13234
+ ], "[furin] Vercel build rejected application static mounts.");
13235
+ }
12949
13236
  }
12950
13237
  function escapeRegex(value) {
12951
13238
  let escaped = "";
@@ -13035,9 +13322,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13035
13322
  body = result.html;
13036
13323
  ({ status } = result);
13037
13324
  }
13038
- const fallbackPath = join11(dirname8(join11(functionsDir, spec.functionName)), fallback);
13039
- ensureDir(dirname8(fallbackPath));
13040
- writeFileSync6(fallbackPath, body);
13325
+ const fallbackPath = join12(dirname10(join12(functionsDir, spec.functionName)), fallback);
13326
+ ensureDir(dirname10(fallbackPath));
13327
+ writeFileSync7(fallbackPath, body);
13041
13328
  spec.config.fallback = fallback;
13042
13329
  spec.config.initialHeaders = {
13043
13330
  "content-type": contentType,
@@ -13048,9 +13335,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13048
13335
  spec.config.initialStatus = status;
13049
13336
  }
13050
13337
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13051
- const aliasPath = join11(functionsDir, `${functionName}.func`);
13052
- ensureDir(dirname8(aliasPath));
13053
- const target = relative7(dirname8(aliasPath), serverFunctionDir);
13338
+ const aliasPath = join12(functionsDir, `${functionName}.func`);
13339
+ ensureDir(dirname10(aliasPath));
13340
+ const target = relative8(dirname10(aliasPath), serverFunctionDir);
13054
13341
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13055
13342
  }
13056
13343
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13120,7 +13407,7 @@ async function createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey) {
13120
13407
  return compareRouteSpecificity(right.pattern, left.pattern);
13121
13408
  });
13122
13409
  }
13123
- function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey) {
13410
+ function vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey) {
13124
13411
  const routeCount = builds.reduce((count, build) => count + build.entryApp.routes.length, 0);
13125
13412
  const prerenderAliases = prerenderSpecs.map((spec) => [
13126
13413
  `/${spec.functionName}`,
@@ -13137,15 +13424,6 @@ function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeK
13137
13424
  source: `^(?:${routePatternSource(app.prefix, route.pattern)})$`,
13138
13425
  tags: route.tags ?? []
13139
13426
  }))).sort((left, right) => compareRouteSpecificity(right.pattern, left.pattern)).map(({ source, tags }) => [source, tags]);
13140
- const contextSource = buildEntrySource({
13141
- apps: builds.map(({ entryApp, indexHtml }) => ({
13142
- ...entryApp,
13143
- embed: undefined,
13144
- serveAssets: false,
13145
- templateHtml: indexHtml
13146
- })),
13147
- headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit"
13148
- });
13149
13427
  return `import {
13150
13428
  addCacheTag,
13151
13429
  getCache as getVercelCache,
@@ -13158,12 +13436,11 @@ import {
13158
13436
  markExternalPrerenderRequest,
13159
13437
  restorePprResumeRequest,
13160
13438
  setCacheTagPurger,
13439
+ setRuntimeEvlogWaitUntil,
13161
13440
  setRuntimeCacheProvider,
13162
13441
  waitForPendingISRRevalidations,
13163
13442
  } from "@teyik0/furin/internal";
13164
13443
 
13165
- ${contextSource}
13166
-
13167
13444
  const prerenderAliases = new Map(
13168
13445
  ${JSON.stringify(prerenderAliases)}.map(([alias, source]) => [alias, new RegExp(source)])
13169
13446
  );
@@ -13183,6 +13460,7 @@ function encodeCacheTag(value) {
13183
13460
  setRuntimeCacheProvider({
13184
13461
  getCache: (options) => getVercelCache(options),
13185
13462
  });
13463
+ setRuntimeEvlogWaitUntil(waitUntil);
13186
13464
 
13187
13465
  async function purgeCacheTags(paths) {
13188
13466
  const purge = Promise.all([
@@ -13196,7 +13474,7 @@ setCachePurger(purgeCacheTags);
13196
13474
  setCacheTagPurger(purgeCacheTags);
13197
13475
 
13198
13476
  const serverInitStartedAt = performance.now();
13199
- const serverModule = await import(${JSON.stringify(toPosixPath(serverEntry))});
13477
+ const serverModule = await import(${JSON.stringify(toPosixPath(appEntry))});
13200
13478
  const app = serverModule.default;
13201
13479
  if (!app || typeof app.handle !== "function") {
13202
13480
  throw new TypeError("[furin] Vercel server entry must export the Elysia app as default.");
@@ -13281,10 +13559,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13281
13559
  if (jobs.length === 0) {
13282
13560
  return;
13283
13561
  }
13284
- const resultPath = join11(targetDir, "ppr-results.json");
13562
+ const resultPath = join12(targetDir, "ppr-results.json");
13285
13563
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13286
13564
  const script = `
13287
- const handler = (await import(${JSON.stringify(pathToFileURL2(join11(functionsDir, "__server.func/index.js")).href)})).default;
13565
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join12(functionsDir, "__server.func/index.js")).href)})).default;
13288
13566
  const results = [];
13289
13567
  for (const url of ${JSON.stringify(requests)}) {
13290
13568
  const response = await handler.fetch(new Request(url));
@@ -13311,7 +13589,7 @@ process.exit(0);
13311
13589
  ${stderr}
13312
13590
  ${stdout}`);
13313
13591
  }
13314
- const results = JSON.parse(readFileSync4(resultPath, "utf8"));
13592
+ const results = JSON.parse(readFileSync5(resultPath, "utf8"));
13315
13593
  for (const [index, job] of jobs.entries()) {
13316
13594
  const result = results[index];
13317
13595
  await addPrerenderFallback(job.spec, job.path, {
@@ -13383,6 +13661,7 @@ async function handle(request) {
13383
13661
  \`furin_server_init;dur=\${initialization.server_init_ms}\`,
13384
13662
  \`furin_handler_wait;dur=\${requestWaitMs}\`,
13385
13663
  \`furin_handler;dur=\${handlerMs}\`,
13664
+ ...(isFirstRequest ? ["furin_instance_first_request"] : []),
13386
13665
  ].join(", ");
13387
13666
  return appendServerTiming(response, serverTiming);
13388
13667
  }
@@ -13392,32 +13671,53 @@ export default { fetch: handle };
13392
13671
  }
13393
13672
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13394
13673
  assertDefaultServerExport(serverEntry);
13395
- const targetDir = join11(buildRoot, "vercel");
13396
- const outputDir = join11(rootDir, ".vercel", "output");
13397
- const staticDir = join11(outputDir, "static");
13398
- const functionsDir = join11(outputDir, "functions");
13399
- const serverFunctionDir = join11(functionsDir, "__server.func");
13674
+ const targetDir = join12(buildRoot, "vercel");
13675
+ const outputDir = join12(rootDir, ".vercel", "output");
13676
+ const staticDir = join12(outputDir, "static");
13677
+ const functionsDir = join12(outputDir, "functions");
13678
+ const serverFunctionDir = join12(functionsDir, "__server.func");
13400
13679
  rmSync5(targetDir, { force: true, recursive: true });
13401
13680
  rmSync5(outputDir, { force: true, recursive: true });
13402
13681
  ensureDir(targetDir);
13403
13682
  ensureDir(staticDir);
13404
13683
  ensureDir(serverFunctionDir);
13405
13684
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
13406
- cpSync3(join11(targetDir, "server-codec.js"), join11(serverFunctionDir, "server-codec.js"));
13407
- const publicDir = join11(rootDir, "public");
13685
+ cpSync3(join12(targetDir, "server-codec.js"), join12(serverFunctionDir, "server-codec.js"));
13686
+ const publicDir = join12(rootDir, "public");
13408
13687
  if (existsSync10(publicDir)) {
13409
13688
  cpSync3(publicDir, staticDir, { recursive: true });
13689
+ for (const app of apps) {
13690
+ const appStaticDir = join12(staticDir, app.prefix.slice(1));
13691
+ const appPublicDir = join12(appStaticDir, "public");
13692
+ cpSync3(publicDir, appPublicDir, { recursive: true });
13693
+ const favicon = join12(publicDir, "favicon.ico");
13694
+ if (app.prefix !== "" && existsSync10(favicon)) {
13695
+ cpSync3(favicon, join12(appStaticDir, "favicon.ico"));
13696
+ }
13697
+ }
13410
13698
  }
13411
13699
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13412
13700
  const app = apps[appIndex];
13413
13701
  const build = builds[appIndex];
13414
- const clientOutputDir = join11(staticDir, app.prefix.slice(1), "_client");
13702
+ const clientOutputDir = join12(staticDir, app.prefix.slice(1), "_client");
13415
13703
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13416
13704
  }
13417
13705
  const pprResumeKey = crypto.randomUUID();
13418
13706
  const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
13419
- const entryPath = join11(serverFunctionDir, "_vercel-handler.ts");
13420
- const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey), "ts");
13707
+ const appEntry = await materializeServerAppEntry({
13708
+ apps: builds.map(({ entryApp, indexHtml }) => ({
13709
+ ...entryApp,
13710
+ embed: undefined,
13711
+ serveAssets: false,
13712
+ templateHtml: indexHtml
13713
+ })),
13714
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
13715
+ instances: apps,
13716
+ outDir: serverFunctionDir,
13717
+ serverEntry
13718
+ });
13719
+ const entryPath = join12(serverFunctionDir, "_vercel-handler.ts");
13720
+ const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13421
13721
  const serverBuild = await runBunBuild({
13422
13722
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
13423
13723
  entrypoints: [entry.entrypoint],
@@ -13435,26 +13735,27 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13435
13735
  ...options.plugins ?? [],
13436
13736
  createRoutesPlugin({ instances: apps, target: "server" }),
13437
13737
  isomorphicTransformPlugin("server"),
13438
- environmentGuardPlugin("ssr")
13738
+ environmentGuardPlugin("ssr"),
13739
+ elysiaAot(appEntry)
13439
13740
  ],
13440
13741
  sourcemap: "none",
13742
+ splitting: true,
13441
13743
  target: "bun"
13442
13744
  });
13443
13745
  if (options.analyze) {
13444
13746
  if (serverBuild.metafile === undefined) {
13445
13747
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13446
13748
  }
13447
- const metafilePath = join11(buildRoot, "analysis", "vercel-server.json");
13448
- ensureDir(dirname8(metafilePath));
13449
- writeFileSync6(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13749
+ const metafilePath = join12(buildRoot, "analysis", "vercel-server.json");
13750
+ ensureDir(dirname10(metafilePath));
13751
+ writeFileSync7(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13450
13752
  `);
13451
13753
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13452
13754
  }
13453
- const handlerPath = join11(serverFunctionDir, "handler.js");
13454
- const serverBundleBytes = existsSync10(handlerPath) ? statSync3(handlerPath).size : 0;
13455
- writeFileSync6(join11(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13755
+ const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13756
+ writeFileSync7(join12(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13456
13757
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13457
- writeFileSync6(join11(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13758
+ writeFileSync7(join12(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13458
13759
  handler: "index.js",
13459
13760
  launcherType: "Nodejs",
13460
13761
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13465,7 +13766,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13465
13766
  `);
13466
13767
  for (const spec of prerenderSpecs) {
13467
13768
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13468
- writeFileSync6(join11(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13769
+ writeFileSync7(join12(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13469
13770
  `);
13470
13771
  }
13471
13772
  const assetRoutes = apps.map((app) => ({
@@ -13495,24 +13796,24 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13495
13796
  ],
13496
13797
  version: 3
13497
13798
  };
13498
- writeFileSync6(join11(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13799
+ writeFileSync7(join12(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13499
13800
  `);
13500
13801
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13501
13802
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
13502
- console.log(`[furin] Vercel output: ${toPosixPath(relative7(rootDir, outputDir))}`);
13803
+ console.log(`[furin] Vercel output: ${toPosixPath(relative8(rootDir, outputDir))}`);
13503
13804
  return {
13504
13805
  buildId: headlineBuildId,
13505
13806
  generatedAt: new Date().toISOString(),
13506
13807
  isrRoutes,
13507
- outputDir: toPosixPath(relative7(rootDir, outputDir)),
13508
- serverPath: toPosixPath(relative7(rootDir, serverFunctionDir)),
13808
+ outputDir: toPosixPath(relative8(rootDir, outputDir)),
13809
+ serverPath: toPosixPath(relative8(rootDir, serverFunctionDir)),
13509
13810
  ssgRoutes
13510
13811
  };
13511
13812
  }
13512
13813
 
13513
13814
  // src/config.ts
13514
13815
  import { t as t2 } from "elysia";
13515
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static", "package"];
13816
+ var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
13516
13817
  var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13517
13818
  var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13518
13819
  var configSchema = t2.Object({
@@ -13549,7 +13850,7 @@ init_instance();
13549
13850
  // src/server/router/discovery.ts
13550
13851
  import { existsSync as existsSync11 } from "fs";
13551
13852
  import { readdir } from "fs/promises";
13552
- import { join as join12, parse as parse3 } from "path";
13853
+ import { join as join13, parse as parse4 } from "path";
13553
13854
 
13554
13855
  // src/server/internal.ts
13555
13856
  var _compileContexts = new Map;
@@ -13634,6 +13935,7 @@ function adaptDefinedLayout(route, parent, sourcePath) {
13634
13935
  requestLoader: route.requestLoader,
13635
13936
  revalidate: route.revalidate,
13636
13937
  sourcePath,
13938
+ staticParams: route.staticParams,
13637
13939
  tags: copyTags(route.tags)
13638
13940
  };
13639
13941
  }
@@ -13757,7 +14059,7 @@ async function scanPageFiles(pagesDir, root) {
13757
14059
  continue;
13758
14060
  }
13759
14061
  const relativePath = routeRelativePath(pagesDir, absolutePath);
13760
- const fileName = parse3(relativePath).name;
14062
+ const fileName = parse4(relativePath).name;
13761
14063
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
13762
14064
  continue;
13763
14065
  }
@@ -13922,7 +14224,7 @@ async function collectPageFilePaths(dir) {
13922
14224
  const files = [];
13923
14225
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
13924
14226
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
13925
- const absolutePath = toPosixPath2(join12(dir, entry.name));
14227
+ const absolutePath = toPosixPath2(join13(dir, entry.name));
13926
14228
  if (entry.isDirectory()) {
13927
14229
  return await collectPageFilePaths(absolutePath);
13928
14230
  }
@@ -13939,9 +14241,9 @@ async function collectPageFilePaths(dir) {
13939
14241
 
13940
14242
  // src/build/scan-server.ts
13941
14243
  init_instance();
13942
- import { readFileSync as readFileSync5 } from "fs";
14244
+ import { readFileSync as readFileSync6 } from "fs";
13943
14245
  function scanFurinInstances(serverEntryPath) {
13944
- const code = readFileSync5(serverEntryPath, "utf8");
14246
+ const code = readFileSync6(serverEntryPath, "utf8");
13945
14247
  const lang = detectLangFromPath(serverEntryPath);
13946
14248
  if (lang === "dts") {
13947
14249
  return [];
@@ -14022,38 +14324,38 @@ function registerIsomorphicRuntimePlugin() {
14022
14324
  function resolveAppSpecs(options, serverEntry, rootDir) {
14023
14325
  if (options.apps && options.apps.length > 0) {
14024
14326
  return options.apps.map((app) => ({
14025
- pagesDir: resolve7(rootDir, app.pagesDir),
14327
+ pagesDir: resolve9(rootDir, app.pagesDir),
14026
14328
  prefix: normalizePrefix(app.prefix)
14027
14329
  }));
14028
14330
  }
14029
14331
  if (options.pagesDir) {
14030
- return [{ pagesDir: resolve7(rootDir, options.pagesDir), prefix: "" }];
14332
+ return [{ pagesDir: resolve9(rootDir, options.pagesDir), prefix: "" }];
14031
14333
  }
14032
14334
  if (serverEntry) {
14033
14335
  const detected = scanFurinInstances(serverEntry);
14034
14336
  if (detected.length > 0) {
14035
14337
  return detected.map((app) => ({
14036
- pagesDir: resolve7(rootDir, app.pagesDir),
14338
+ pagesDir: resolve9(rootDir, app.pagesDir),
14037
14339
  prefix: app.prefix
14038
14340
  }));
14039
14341
  }
14040
14342
  }
14041
- return [{ pagesDir: resolve7(rootDir, "src/pages"), prefix: "" }];
14343
+ return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14042
14344
  }
14043
14345
  async function buildApp(options) {
14044
- const rootDir = resolve7(options.rootDir ?? process.cwd());
14045
- const buildRoot = join13(rootDir, BUILD_OUTPUT_DIR);
14346
+ const rootDir = resolve9(options.rootDir ?? process.cwd());
14347
+ const buildRoot = join14(rootDir, BUILD_OUTPUT_DIR);
14046
14348
  const serverEntry = (() => {
14047
14349
  if (options.target === "static" || options.target === "package") {
14048
14350
  return null;
14049
14351
  }
14050
14352
  if (options.serverEntry) {
14051
- const resolved = resolve7(rootDir, options.serverEntry);
14353
+ const resolved = resolve9(rootDir, options.serverEntry);
14052
14354
  if (existsSync12(resolved)) {
14053
14355
  return resolved;
14054
14356
  }
14055
14357
  }
14056
- const entry = resolve7(rootDir, "src/server.ts");
14358
+ const entry = resolve9(rootDir, "src/server.ts");
14057
14359
  if (!existsSync12(entry)) {
14058
14360
  throw new Error("[furin] Entrypoint server.ts not found");
14059
14361
  }
@@ -14094,12 +14396,12 @@ async function buildApp(options) {
14094
14396
  version: 1,
14095
14397
  generatedAt: new Date().toISOString(),
14096
14398
  rootDir: toPosixPath(rootDir),
14097
- pagesDir: toPosixPath(relative8(rootDir, primaryApp.pagesDir)),
14098
- rootPath: toPosixPath(relative8(rootDir, primaryApp.root.path)),
14099
- serverEntry: serverEntry ? toPosixPath(relative8(rootDir, serverEntry)) : null,
14399
+ pagesDir: toPosixPath(relative9(rootDir, primaryApp.pagesDir)),
14400
+ rootPath: toPosixPath(relative9(rootDir, primaryApp.root.path)),
14401
+ serverEntry: serverEntry ? toPosixPath(relative9(rootDir, serverEntry)) : null,
14100
14402
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14101
14403
  apps: apps.map((app) => ({
14102
- pagesDir: toPosixPath(relative8(rootDir, app.pagesDir)),
14404
+ pagesDir: toPosixPath(relative9(rootDir, app.pagesDir)),
14103
14405
  prefix: app.prefix,
14104
14406
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14105
14407
  })),
@@ -14131,14 +14433,11 @@ async function buildApp(options) {
14131
14433
  }
14132
14434
  manifest.targets.vercel = await buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options);
14133
14435
  break;
14134
- case "node":
14135
- case "cloudflare":
14136
- throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
14137
14436
  default:
14138
14437
  throw new Error(`[furin] Unsupported build target "${target}"`);
14139
14438
  }
14140
14439
  }
14141
- writeFileSync7(join13(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14440
+ writeFileSync8(join14(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14142
14441
  `);
14143
14442
  return {
14144
14443
  manifest,
@@ -14151,17 +14450,18 @@ init_instance();
14151
14450
 
14152
14451
  // src/cli/config.ts
14153
14452
  import { existsSync as existsSync13 } from "fs";
14154
- import { resolve as resolve8 } from "path";
14453
+ import { resolve as resolve10 } from "path";
14155
14454
  import { pathToFileURL as pathToFileURL3 } from "url";
14156
- var compiledConfigSchema = TypeCompiler.Compile(configSchema);
14455
+ import { Validator as Validator2 } from "elysia";
14456
+ var compiledConfigSchema = Validator2.create(configSchema);
14157
14457
  var DEFAULT_CONFIG_FILENAMES = [
14158
14458
  "furin.config.ts",
14159
14459
  "furin.config.js",
14160
14460
  "furin.config.mjs"
14161
14461
  ];
14162
14462
  async function loadCliConfig(cwd, explicitConfigPath) {
14163
- const rootDir = resolve8(cwd);
14164
- const configPath = explicitConfigPath ? resolve8(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve8(rootDir, filename)).find((path) => existsSync13(path));
14463
+ const rootDir = resolve10(cwd);
14464
+ const configPath = explicitConfigPath ? resolve10(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve10(rootDir, filename)).find((path) => existsSync13(path));
14165
14465
  if (!configPath) {
14166
14466
  return {
14167
14467
  configPath: null,
@@ -14176,13 +14476,13 @@ async function loadCliConfig(cwd, explicitConfigPath) {
14176
14476
  }
14177
14477
  if (!compiledConfigSchema.Check(configToValidate)) {
14178
14478
  const [firstError] = compiledConfigSchema.Errors(configToValidate);
14179
- throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
14479
+ throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.instancePath ?? "/"})`);
14180
14480
  }
14181
- const resolvedRootDir = resolve8(rootDir, configToValidate.rootDir ?? ".");
14481
+ const resolvedRootDir = resolve10(rootDir, configToValidate.rootDir ?? ".");
14182
14482
  return {
14183
14483
  ...configToValidate,
14184
14484
  configPath,
14185
- pagesDir: configToValidate.pagesDir ? resolve8(resolvedRootDir, configToValidate.pagesDir) : undefined,
14485
+ pagesDir: configToValidate.pagesDir ? resolve10(resolvedRootDir, configToValidate.pagesDir) : undefined,
14186
14486
  plugins,
14187
14487
  rootDir: resolvedRootDir
14188
14488
  };
@@ -14190,7 +14490,7 @@ async function loadCliConfig(cwd, explicitConfigPath) {
14190
14490
 
14191
14491
  // src/cli/preview.ts
14192
14492
  import { existsSync as existsSync14 } from "fs";
14193
- import { isAbsolute as isAbsolute3, join as join14, relative as relative9, resolve as resolve9 } from "path";
14493
+ import { isAbsolute as isAbsolute4, join as join15, relative as relative10, resolve as resolve11 } from "path";
14194
14494
  var LEADING_SLASHES_RE = /^\/+/;
14195
14495
  var TRAILING_SLASHES_RE2 = /\/+$/;
14196
14496
  function normalizeStaticPreviewBasePath(basePath) {
@@ -14208,15 +14508,15 @@ function startStaticPreview({
14208
14508
  port
14209
14509
  }) {
14210
14510
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
14211
- const distDir = resolve9(rawDistDir);
14212
- const indexPath = join14(distDir, "index.html");
14213
- const notFoundPath = join14(distDir, "404.html");
14214
- const faviconPath = join14(distDir, "favicon.ico");
14511
+ const distDir = resolve11(rawDistDir);
14512
+ const indexPath = join15(distDir, "index.html");
14513
+ const notFoundPath = join15(distDir, "404.html");
14514
+ const faviconPath = join15(distDir, "favicon.ico");
14215
14515
  if (!(existsSync14(indexPath) && existsSync14(notFoundPath))) {
14216
14516
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
14217
14517
  }
14218
14518
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
14219
- const clientDir = join14(distDir, "_client");
14519
+ const clientDir = join15(distDir, "_client");
14220
14520
  const fetchStaticFile = async (request) => {
14221
14521
  const encodedPathname = new URL(request.url).pathname;
14222
14522
  let pathname;
@@ -14229,16 +14529,16 @@ function startStaticPreview({
14229
14529
  return notFound();
14230
14530
  }
14231
14531
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
14232
- const exactPath = resolve9(distDir, logicalPath);
14233
- const relativePath = relative9(distDir, exactPath);
14234
- if (relativePath.startsWith("..") || isAbsolute3(relativePath)) {
14532
+ const exactPath = resolve11(distDir, logicalPath);
14533
+ const relativePath = relative10(distDir, exactPath);
14534
+ if (relativePath.startsWith("..") || isAbsolute4(relativePath)) {
14235
14535
  return notFound();
14236
14536
  }
14237
14537
  const exactFile = Bun.file(exactPath);
14238
14538
  if (!pathname.endsWith("/") && await exactFile.exists()) {
14239
14539
  return new Response(exactFile);
14240
14540
  }
14241
- const indexFile = Bun.file(join14(exactPath, "index.html"));
14541
+ const indexFile = Bun.file(join15(exactPath, "index.html"));
14242
14542
  if (await indexFile.exists()) {
14243
14543
  return new Response(indexFile);
14244
14544
  }
@@ -14329,10 +14629,10 @@ if (command === "preview") {
14329
14629
  const values = rawValues;
14330
14630
  const config = await loadCliConfig(process.cwd(), values.config);
14331
14631
  const port = values.port === undefined ? 3000 : Number(values.port);
14332
- if (!(Number.isInteger(port) && port > 0 && port <= 65535)) {
14333
- bail(`Invalid preview port "${values.port}". Expected an integer between 1 and 65535.`);
14632
+ if (values.port !== undefined && !/^\d+$/.test(values.port) || !(Number.isInteger(port) && port >= 0 && port <= 65535)) {
14633
+ bail(`Invalid preview port "${values.port}". Expected an integer between 0 and 65535.`);
14334
14634
  }
14335
- const distDir = resolve10(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
14635
+ const distDir = resolve12(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
14336
14636
  const basePath = normalizeStaticPreviewBasePath(values.basePath ?? config.static?.basePath ?? "");
14337
14637
  const server = startStaticPreview({ basePath, distDir, port });
14338
14638
  log("Static preview ready");
@@ -14367,7 +14667,7 @@ if (command === "preview") {
14367
14667
  const config = await loadCliConfig(process.cwd(), values.config);
14368
14668
  const isServerlessTarget = target === "static" || target === "package";
14369
14669
  const resolvedServerEntry = isServerlessTarget ? undefined : (() => {
14370
- const entry = resolve10(config.rootDir, config.serverEntry ?? "src/server.ts");
14670
+ const entry = resolve12(config.rootDir, config.serverEntry ?? "src/server.ts");
14371
14671
  if (!existsSync15(entry)) {
14372
14672
  const expected = config.serverEntry ?? "src/server.ts";
14373
14673
  throw new Error(`[furin] Entrypoint ${expected} not found`);