@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.15

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 (69) hide show
  1. package/README.md +14 -232
  2. package/dist/auto-invalidate/index.d.ts +4 -0
  3. package/dist/auto-invalidate/plugin.d.ts +38 -0
  4. package/dist/auto-invalidate/registry.d.ts +9 -0
  5. package/dist/auto-invalidate/runtime.d.ts +9 -0
  6. package/dist/auto-invalidate/types.d.ts +12 -0
  7. package/dist/await.d.ts +67 -0
  8. package/dist/build/index.js +2095 -185
  9. package/dist/cli/index.js +2070 -182
  10. package/dist/client.d.ts +51 -4
  11. package/dist/client.js +65 -1
  12. package/dist/deferred-ndjson.d.ts +32 -0
  13. package/dist/error.d.ts +14 -0
  14. package/dist/furin.d.ts +8 -0
  15. package/dist/furin.js +2927 -319
  16. package/dist/lang-detect.d.ts +5 -0
  17. package/dist/link.d.ts +1 -0
  18. package/dist/link.js +1453 -95
  19. package/dist/plugin/index.js +96 -25
  20. package/dist/plugin/transform-client.d.ts +2 -1
  21. package/dist/render/assemble.d.ts +32 -0
  22. package/dist/render/cache.d.ts +7 -0
  23. package/dist/render/element.d.ts +17 -1
  24. package/dist/render/index.d.ts +10 -1
  25. package/dist/render/index.ts +250 -44
  26. package/dist/render/loaders.d.ts +46 -3
  27. package/dist/render/shell.d.ts +16 -6
  28. package/dist/render/shell.ts +27 -12
  29. package/dist/router-provider.d.ts +86 -18
  30. package/dist/router.d.ts +66 -0
  31. package/dist/router.js +2909 -374
  32. package/dist/router.ts +586 -54
  33. package/dist/server-error.d.ts +12 -0
  34. package/dist/utils.d.ts +7 -0
  35. package/package.json +8 -7
  36. package/src/adapter/bun.ts +3 -3
  37. package/src/adapter/static.ts +73 -31
  38. package/src/auto-invalidate/index.ts +10 -0
  39. package/src/auto-invalidate/plugin.ts +25 -0
  40. package/src/auto-invalidate/registry.ts +60 -0
  41. package/src/auto-invalidate/runtime.ts +133 -0
  42. package/src/auto-invalidate/types.ts +16 -0
  43. package/src/await.tsx +175 -0
  44. package/src/build/client.ts +4 -8
  45. package/src/build/hydrate.ts +67 -1
  46. package/src/build/route-types.ts +29 -3
  47. package/src/build/scan-server.ts +6 -23
  48. package/src/client.ts +80 -3
  49. package/src/deferred-ndjson.ts +212 -0
  50. package/src/dev-page-plugin.ts +2 -0
  51. package/src/error.ts +18 -1
  52. package/src/furin.ts +19 -2
  53. package/src/lang-detect.ts +46 -0
  54. package/src/link.tsx +16 -3
  55. package/src/plugin/index.ts +7 -8
  56. package/src/plugin/transform-client.ts +108 -39
  57. package/src/render/assemble.ts +67 -0
  58. package/src/render/boundaries.tsx +23 -5
  59. package/src/render/cache.ts +14 -0
  60. package/src/render/default-screens.tsx +4 -11
  61. package/src/render/dev-cache.ts +5 -0
  62. package/src/render/element.tsx +26 -3
  63. package/src/render/index.ts +250 -44
  64. package/src/render/loaders.ts +219 -18
  65. package/src/render/shell.ts +27 -12
  66. package/src/router-provider.tsx +414 -122
  67. package/src/router.ts +586 -54
  68. package/src/server-error.ts +47 -0
  69. package/src/utils.ts +31 -0
@@ -263,7 +263,7 @@ function getBtoa() {
263
263
  };
264
264
  }
265
265
  }
266
- var btoa = /* @__PURE__ */ getBtoa();
266
+ var btoa2 = /* @__PURE__ */ getBtoa();
267
267
 
268
268
  class SourceMap {
269
269
  constructor(properties) {
@@ -284,7 +284,7 @@ class SourceMap {
284
284
  return JSON.stringify(this);
285
285
  }
286
286
  toUrl() {
287
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
287
+ return "data:application/json;charset=utf-8;base64," + btoa2(this.toString());
288
288
  }
289
289
  }
290
290
  function guessIndent(code) {
@@ -1151,16 +1151,41 @@ class MagicString {
1151
1151
 
1152
1152
  // src/plugin/transform-client.ts
1153
1153
  import { parse } from "yuku-parser";
1154
- var bunTranspiler = new Bun.Transpiler({
1155
- loader: "tsx",
1156
- tsconfig: {
1157
- compilerOptions: {
1158
- jsx: "react",
1159
- jsxFactory: "React.createElement",
1160
- jsxFragmentFactory: "React.Fragment"
1161
- }
1154
+
1155
+ // src/lang-detect.ts
1156
+ function detectLangFromPath(filePath) {
1157
+ if (filePath.endsWith(".d.ts")) {
1158
+ return "dts";
1162
1159
  }
1163
- });
1160
+ const ext = filePath.split(".").pop()?.toLowerCase();
1161
+ switch (ext) {
1162
+ case "ts":
1163
+ return "ts";
1164
+ case "tsx":
1165
+ return "tsx";
1166
+ case "jsx":
1167
+ return "jsx";
1168
+ default:
1169
+ return "js";
1170
+ }
1171
+ }
1172
+ var TS_WRAPPER_TYPES = new Set([
1173
+ "TSAsExpression",
1174
+ "TSSatisfiesExpression",
1175
+ "TSTypeAssertion",
1176
+ "TSNonNullExpression",
1177
+ "TSInstantiationExpression",
1178
+ "ParenthesizedExpression"
1179
+ ]);
1180
+ function unwrapTSExpression(node) {
1181
+ let current = node;
1182
+ while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
1183
+ current = current.expression;
1184
+ }
1185
+ return current;
1186
+ }
1187
+
1188
+ // src/plugin/transform-client.ts
1164
1189
  var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1165
1190
  function walk(node, visitor) {
1166
1191
  if (!node || typeof node !== "object") {
@@ -1244,6 +1269,45 @@ function removeServerProperties(s, source, obj) {
1244
1269
  }
1245
1270
  return true;
1246
1271
  }
1272
+ var TYPE_SCOPE_NODES = new Set([
1273
+ "TSTypeAnnotation",
1274
+ "TSTypeParameterDeclaration",
1275
+ "TSTypeParameterInstantiation",
1276
+ "TSInterfaceDeclaration",
1277
+ "TSTypeAliasDeclaration",
1278
+ "TSTypePredicate",
1279
+ "TSClassImplements"
1280
+ ]);
1281
+ function markTypeDescendants(node, excluded) {
1282
+ if (!node || typeof node !== "object") {
1283
+ return;
1284
+ }
1285
+ if (Array.isArray(node)) {
1286
+ for (const item of node) {
1287
+ markTypeDescendants(item, excluded);
1288
+ }
1289
+ return;
1290
+ }
1291
+ const n2 = node;
1292
+ if (n2.type === "Identifier" || n2.type === "JSXIdentifier") {
1293
+ excluded.add(n2);
1294
+ }
1295
+ for (const key of Object.keys(n2)) {
1296
+ if (key === "type" || key === "start" || key === "end") {
1297
+ continue;
1298
+ }
1299
+ markTypeDescendants(n2[key], excluded);
1300
+ }
1301
+ }
1302
+ function excludeTypePositionIdentifiers(node, excluded) {
1303
+ if (TYPE_SCOPE_NODES.has(node.type)) {
1304
+ markTypeDescendants(node, excluded);
1305
+ return;
1306
+ }
1307
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSTypeAssertion") {
1308
+ markTypeDescendants(node.typeAnnotation, excluded);
1309
+ }
1310
+ }
1247
1311
  function collectReferencedNames(program) {
1248
1312
  const refs = new Set;
1249
1313
  const excluded = new Set;
@@ -1258,6 +1322,13 @@ function collectReferencedNames(program) {
1258
1322
  if (node.type === "MemberExpression" && !node.computed) {
1259
1323
  excluded.add(node.property);
1260
1324
  }
1325
+ if (node.type === "JSXAttribute") {
1326
+ excluded.add(node.name);
1327
+ }
1328
+ if (node.type === "JSXMemberExpression") {
1329
+ excluded.add(node.property);
1330
+ }
1331
+ excludeTypePositionIdentifiers(node, excluded);
1261
1332
  });
1262
1333
  }
1263
1334
  for (const stmt of program.body ?? []) {
@@ -1268,7 +1339,7 @@ function collectReferencedNames(program) {
1268
1339
  if (excluded.has(node)) {
1269
1340
  return;
1270
1341
  }
1271
- if (node.type === "Identifier" && typeof node.name === "string") {
1342
+ if ((node.type === "Identifier" || node.type === "JSXIdentifier") && typeof node.name === "string") {
1272
1343
  refs.add(node.name);
1273
1344
  }
1274
1345
  });
@@ -1299,9 +1370,9 @@ function removeUnusedSpecifiers(s, code, decl, refs) {
1299
1370
  s.remove(removeStart, removeEnd);
1300
1371
  }
1301
1372
  }
1302
- function deadCodeElimination(s) {
1373
+ function deadCodeElimination(s, lang) {
1303
1374
  const code = s.toString();
1304
- const { program, diagnostics } = parse(code, { sourceType: "module" });
1375
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1305
1376
  const firstError = diagnostics.find((d) => d.severity === "error");
1306
1377
  if (firstError) {
1307
1378
  console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
@@ -1342,7 +1413,7 @@ function removeServerExports(s, source, program) {
1342
1413
  if (!isTargetCall(call)) {
1343
1414
  return;
1344
1415
  }
1345
- const arg = call.arguments[0];
1416
+ const arg = call.arguments[0] ? unwrapTSExpression(call.arguments[0]) : undefined;
1346
1417
  if (!arg || arg.type !== "ObjectExpression") {
1347
1418
  return;
1348
1419
  }
@@ -1353,16 +1424,19 @@ function removeServerExports(s, source, program) {
1353
1424
  return removedServerCode;
1354
1425
  }
1355
1426
  function transformForClient(code, filename) {
1356
- const plainJs = bunTranspiler.transformSync(code);
1357
- const { program, diagnostics } = parse(plainJs, { sourceType: "module" });
1427
+ const lang = detectLangFromPath(filename);
1428
+ if (lang === "dts") {
1429
+ return { code, map: null, removedServerCode: false };
1430
+ }
1431
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1358
1432
  const firstError = diagnostics.find((d) => d.severity === "error");
1359
1433
  if (firstError) {
1360
1434
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
1361
1435
  }
1362
- let s = new MagicString(plainJs);
1363
- const removedServerCode = removeServerExports(s, plainJs, program);
1436
+ let s = new MagicString(code);
1437
+ const removedServerCode = removeServerExports(s, code, program);
1364
1438
  if (removedServerCode) {
1365
- s = deadCodeElimination(s);
1439
+ s = deadCodeElimination(s, lang);
1366
1440
  }
1367
1441
  return {
1368
1442
  code: s.toString(),
@@ -1397,7 +1471,13 @@ function safeJson(value) {
1397
1471
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1398
1472
  }
1399
1473
  function renderAttrs(obj) {
1400
- return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1474
+ const parts = [];
1475
+ for (const [k, v] of Object.entries(obj)) {
1476
+ if (v !== undefined) {
1477
+ parts.push(`${k}="${escapeHtml(String(v))}"`);
1478
+ }
1479
+ }
1480
+ return parts.join(" ");
1401
1481
  }
1402
1482
  function buildMetaParts(meta) {
1403
1483
  const parts = [];
@@ -1470,13 +1550,15 @@ function generateIndexHtml() {
1470
1550
  </html>
1471
1551
  `;
1472
1552
  }
1473
- function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1553
+ function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref, staticMode) {
1474
1554
  const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
1475
1555
  `);
1476
1556
  const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
1477
1557
  const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
1478
1558
  ` : "";
1479
1559
  const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
1560
+ ` : "";
1561
+ const modeMeta = staticMode ? ` <meta name="furin-mode" content="static">
1480
1562
  ` : "";
1481
1563
  return `<!DOCTYPE html>
1482
1564
  <html lang="en">
@@ -1484,7 +1566,7 @@ function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1484
1566
  <meta charset="UTF-8">
1485
1567
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1486
1568
  ${THEME_INIT_SCRIPT}
1487
- ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
1569
+ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
1488
1570
  ` : ""} <!--ssr-head-->
1489
1571
  </head>
1490
1572
  <body>
@@ -1508,7 +1590,12 @@ function schemaToTypeString(schema) {
1508
1590
  }
1509
1591
  const s = schema;
1510
1592
  if (s.anyOf && Array.isArray(s.anyOf)) {
1511
- const parts = s.anyOf.map(schemaToTypeString).filter((t) => t !== "null");
1593
+ const parts = [];
1594
+ for (const item of s.anyOf) {
1595
+ const t = schemaToTypeString(item);
1596
+ if (t !== "null")
1597
+ parts.push(t);
1598
+ }
1512
1599
  return parts.join(" | ") || "unknown";
1513
1600
  }
1514
1601
  switch (s.type) {
@@ -1533,14 +1620,31 @@ function schemaToTypeString(schema) {
1533
1620
  return "unknown";
1534
1621
  }
1535
1622
  }
1623
+ function tagKeyToPropertyName(tag) {
1624
+ return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
1625
+ }
1626
+ function tagToStringLiteral(tag) {
1627
+ const json = JSON.stringify(tag);
1628
+ return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
1629
+ }
1536
1630
  function writeRouteTypes(routes, projectRoot) {
1537
- const entries = routes.map((r) => {
1631
+ const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
1632
+ const entries = sortedRoutes.map((r) => {
1538
1633
  const typeKey = patternToTypeString(r.pattern);
1539
1634
  const isDynamic = typeKey.startsWith("`");
1540
1635
  const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
1541
1636
  const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
1542
1637
  return isDynamic ? ` [key: ${typeKey}]: { search?: ${searchType} }` : ` ${typeKey}: { search?: ${searchType} }`;
1543
1638
  });
1639
+ const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
1640
+ const tagBlock = sortedTags.length > 0 ? `
1641
+
1642
+ declare module "@teyik0/furin" {
1643
+ interface FurinCacheTags {
1644
+ ${sortedTags.map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`).join(`
1645
+ `)}
1646
+ }
1647
+ }` : "";
1544
1648
  const content = `// Auto-generated by Furin. Do not edit manually.
1545
1649
  /// <reference types="@teyik0/furin/env" />
1546
1650
  import "@teyik0/furin/link";
@@ -1550,7 +1654,7 @@ declare module "@teyik0/furin/link" {
1550
1654
  ${entries.join(`;
1551
1655
  `)};
1552
1656
  }
1553
- }
1657
+ }${tagBlock}
1554
1658
  `;
1555
1659
  const typesPath = join(projectRoot, "furin-env.d.ts");
1556
1660
  const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
@@ -1616,6 +1720,8 @@ import { createElement } from "react";
1616
1720
  import { initLogger, log } from "evlog";
1617
1721
  import { createHttpLogDrain } from "evlog/http";
1618
1722
  import { RouterProvider } from "@teyik0/furin/link";
1723
+ import { fromCrossJSON } from "@teyik0/furin/link";
1724
+ import type { SerovalNode } from "seroval";
1619
1725
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
1620
1726
 
1621
1727
  initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
@@ -1637,6 +1743,70 @@ const _match = routes.find((r) => r.regex.test(pathname));
1637
1743
  // former does not \u2014 so the two cases fork on _match below.
1638
1744
  const dataEl = document.getElementById("__FURIN_DATA__");
1639
1745
  const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
1746
+
1747
+ // \u2500\u2500 Deferred data hydration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1748
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
1749
+ // defer(). It carries:
1750
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
1751
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
1752
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
1753
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
1754
+ interface FurinDeferredRegistry {
1755
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
1756
+ _deferredKeys: string[];
1757
+ _resolvers: Record<string, {
1758
+ promise: Promise<unknown>;
1759
+ reject: (reason: unknown) => void;
1760
+ resolve: (value: unknown) => void;
1761
+ }>;
1762
+ getPromise: (key: string) => Promise<unknown>;
1763
+ reject: (key: string, chunk: SerovalNode) => void;
1764
+ resolve: (key: string, chunk: SerovalNode) => void;
1765
+ }
1766
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
1767
+ .__FURIN_DEFERRED__;
1768
+ const deferredData: Record<string, Promise<unknown>> = {};
1769
+ if (__deferred && __deferred._chunks) {
1770
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
1771
+ // settle immediately. The previous version stored late chunks in _chunks
1772
+ // when no resolver was registered yet, but the drain loop below only runs
1773
+ // ONCE at hydrate time \u2014 so any chunk landing after the drain would stay
1774
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
1775
+ // the resolver via getPromise() fixes the race.
1776
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
1777
+ __deferred.getPromise(key);
1778
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
1779
+ };
1780
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
1781
+ __deferred.getPromise(key);
1782
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
1783
+ };
1784
+ for (const key of Object.keys(__deferred._chunks)) {
1785
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
1786
+ const p = __deferred.getPromise(key) as Promise<unknown>;
1787
+ const resolver = __deferred._resolvers[key];
1788
+ const value = fromCrossJSON(entry.v, {});
1789
+ if (entry.a === 0) {
1790
+ resolver.resolve(value);
1791
+ } else {
1792
+ resolver.reject(value);
1793
+ }
1794
+ deferredData[key] = p;
1795
+ }
1796
+ for (const key of __deferred._deferredKeys ?? []) {
1797
+ if (!(key in deferredData)) {
1798
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
1799
+ }
1800
+ }
1801
+ // Keys that have a resolver (getPromise was called by <Await>) but no
1802
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
1803
+ // so the hydration data record is complete.
1804
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
1805
+ if (!(key in deferredData)) {
1806
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
1807
+ }
1808
+ }
1809
+ }
1640
1810
  const rootEl = document.getElementById("root") as HTMLElement;
1641
1811
 
1642
1812
  // Eagerly load only the current page module for initial hydration.
@@ -1655,7 +1825,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1655
1825
  routes,
1656
1826
  root,
1657
1827
  initialMatch: match,
1658
- initialData: loaderData,
1828
+ initialData: { ...loaderData, ...deferredData },
1659
1829
  initialDigest: loaderData.__furinError?.digest,
1660
1830
  initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
1661
1831
  } as any);
@@ -1801,7 +1971,6 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1801
1971
 
1802
1972
  // src/build/client.ts
1803
1973
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
1804
- var REACT_IMPORT_RE = /import\s+React\b/;
1805
1974
  async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1806
1975
  const clientDir = join4(outDir, "client");
1807
1976
  if (!existsSync4(outDir)) {
@@ -1825,12 +1994,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
1825
1994
  const code = await Bun.file(path).text();
1826
1995
  try {
1827
1996
  const result2 = transformForClient(code, path);
1828
- let transformed = result2.code;
1829
- if (transformed.includes("React.createElement") && !REACT_IMPORT_RE.test(transformed)) {
1830
- transformed = `import React from "react";
1831
- ${transformed}`;
1832
- }
1833
- transformed = transformed.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));
1997
+ const transformed = result2.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));
1834
1998
  return {
1835
1999
  contents: transformed,
1836
2000
  loader: path.endsWith(".tsx") ? "tsx" : "ts"
@@ -2111,12 +2275,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
2111
2275
  }
2112
2276
  fingerprintPaths.add(path);
2113
2277
  }
2114
- const fileParts = await Promise.all([...fingerprintPaths].sort().map(async (path) => {
2278
+ const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
2115
2279
  const content = existsSync7(path) ? await Bun.file(path).text() : "";
2116
2280
  return `${toPosixPath(path)}:${content}`;
2117
2281
  }));
2118
2282
  const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath(route.path), pattern: route.pattern })).sort();
2119
- return [entryChunk, ...[...cssChunks].sort(), ...routeParts, ...fileParts].join(`
2283
+ return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join(`
2120
2284
  `);
2121
2285
  }
2122
2286
  function buildCompileMetadata(root, routes) {
@@ -2157,7 +2321,7 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2157
2321
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
2158
2322
  targetManifest.buildId = buildId;
2159
2323
  const clientDir = join8(targetDir, "client");
2160
- writeFileSync6(join8(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
2324
+ writeFileSync6(join8(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false));
2161
2325
  const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
2162
2326
  const publicDir = existsSync7(join8(rootDir, "public")) ? join8(rootDir, "public") : undefined;
2163
2327
  const targetPublicDir = publicDir ? join8(targetDir, "public") : undefined;
@@ -2271,6 +2435,1045 @@ function assembleHTML(template, headData, reactHtml, data) {
2271
2435
  import { createElement as createElement3 } from "react";
2272
2436
  import { renderToReadableStream } from "react-dom/server";
2273
2437
 
2438
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
2439
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
2440
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2441
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
2442
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
2443
+ var SYM_ITERATOR = Symbol.iterator;
2444
+ var SYM_MATCH = Symbol.match;
2445
+ var SYM_MATCH_ALL = Symbol.matchAll;
2446
+ var SYM_REPLACE = Symbol.replace;
2447
+ var SYM_SEARCH = Symbol.search;
2448
+ var SYM_SPECIES = Symbol.species;
2449
+ var SYM_SPLIT = Symbol.split;
2450
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
2451
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
2452
+ var SYM_UNSCOPABLES = Symbol.unscopables;
2453
+ var INV_SYMBOL_REF = {
2454
+ [SYM_ASYNC_ITERATOR]: 0,
2455
+ [SYM_HAS_INSTANCE]: 1,
2456
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
2457
+ [SYM_ITERATOR]: 3,
2458
+ [SYM_MATCH]: 4,
2459
+ [SYM_MATCH_ALL]: 5,
2460
+ [SYM_REPLACE]: 6,
2461
+ [SYM_SEARCH]: 7,
2462
+ [SYM_SPECIES]: 8,
2463
+ [SYM_SPLIT]: 9,
2464
+ [SYM_TO_PRIMITIVE]: 10,
2465
+ [SYM_TO_STRING_TAG]: 11,
2466
+ [SYM_UNSCOPABLES]: 12
2467
+ };
2468
+ var NIL = undefined;
2469
+ var CONSTANT_VAL = {
2470
+ [2]: true,
2471
+ [3]: false,
2472
+ [1]: NIL,
2473
+ [0]: null,
2474
+ [4]: -0,
2475
+ [5]: Number.POSITIVE_INFINITY,
2476
+ [6]: Number.NEGATIVE_INFINITY,
2477
+ [7]: Number.NaN
2478
+ };
2479
+ var ERROR_CONSTRUCTOR_STRING = {
2480
+ [0]: "Error",
2481
+ [1]: "EvalError",
2482
+ [2]: "RangeError",
2483
+ [3]: "ReferenceError",
2484
+ [4]: "SyntaxError",
2485
+ [5]: "TypeError",
2486
+ [6]: "URIError"
2487
+ };
2488
+ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
2489
+ return {
2490
+ t,
2491
+ i,
2492
+ s,
2493
+ c,
2494
+ m,
2495
+ p,
2496
+ e,
2497
+ a,
2498
+ f,
2499
+ b,
2500
+ o,
2501
+ l
2502
+ };
2503
+ }
2504
+ function createConstantNode(value) {
2505
+ return createSerovalNode(2, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2506
+ }
2507
+ var TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
2508
+ var FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
2509
+ var UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
2510
+ var NULL_NODE = /* @__PURE__ */ createConstantNode(0);
2511
+ var NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
2512
+ var INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
2513
+ var NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
2514
+ var NAN_NODE = /* @__PURE__ */ createConstantNode(7);
2515
+ function serializeChar(str) {
2516
+ switch (str) {
2517
+ case '"':
2518
+ return "\\\"";
2519
+ case "\\":
2520
+ return "\\\\";
2521
+ case `
2522
+ `:
2523
+ return "\\n";
2524
+ case "\r":
2525
+ return "\\r";
2526
+ case "\b":
2527
+ return "\\b";
2528
+ case "\t":
2529
+ return "\\t";
2530
+ case "\f":
2531
+ return "\\f";
2532
+ case "<":
2533
+ return "\\x3C";
2534
+ case "\u2028":
2535
+ return "\\u2028";
2536
+ case "\u2029":
2537
+ return "\\u2029";
2538
+ default:
2539
+ return NIL;
2540
+ }
2541
+ }
2542
+ function serializeString(str) {
2543
+ let result = "";
2544
+ let lastPos = 0;
2545
+ let replacement;
2546
+ for (let i = 0, len = str.length;i < len; i++) {
2547
+ replacement = serializeChar(str[i]);
2548
+ if (replacement) {
2549
+ result += str.slice(lastPos, i) + replacement;
2550
+ lastPos = i + 1;
2551
+ }
2552
+ }
2553
+ if (lastPos === 0) {
2554
+ result = str;
2555
+ } else {
2556
+ result += str.slice(lastPos);
2557
+ }
2558
+ return result;
2559
+ }
2560
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
2561
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
2562
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
2563
+ var REFERENCE = /* @__PURE__ */ new Map;
2564
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
2565
+ function hasReferenceID(value) {
2566
+ return REFERENCE.has(value);
2567
+ }
2568
+ function getReferenceID(value) {
2569
+ if (hasReferenceID(value)) {
2570
+ return REFERENCE.get(value);
2571
+ }
2572
+ throw new SerovalMissingReferenceError(value);
2573
+ }
2574
+ if (typeof globalThis !== "undefined") {
2575
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
2576
+ value: INV_REFERENCE,
2577
+ configurable: true,
2578
+ writable: false,
2579
+ enumerable: false
2580
+ });
2581
+ } else if (typeof window !== "undefined") {
2582
+ Object.defineProperty(window, REFERENCES_KEY, {
2583
+ value: INV_REFERENCE,
2584
+ configurable: true,
2585
+ writable: false,
2586
+ enumerable: false
2587
+ });
2588
+ } else if (typeof self !== "undefined") {
2589
+ Object.defineProperty(self, REFERENCES_KEY, {
2590
+ value: INV_REFERENCE,
2591
+ configurable: true,
2592
+ writable: false,
2593
+ enumerable: false
2594
+ });
2595
+ } else if (typeof global !== "undefined") {
2596
+ Object.defineProperty(global, REFERENCES_KEY, {
2597
+ value: INV_REFERENCE,
2598
+ configurable: true,
2599
+ writable: false,
2600
+ enumerable: false
2601
+ });
2602
+ }
2603
+ function getErrorConstructor(error) {
2604
+ if (error instanceof EvalError) {
2605
+ return 1;
2606
+ }
2607
+ if (error instanceof RangeError) {
2608
+ return 2;
2609
+ }
2610
+ if (error instanceof ReferenceError) {
2611
+ return 3;
2612
+ }
2613
+ if (error instanceof SyntaxError) {
2614
+ return 4;
2615
+ }
2616
+ if (error instanceof TypeError) {
2617
+ return 5;
2618
+ }
2619
+ if (error instanceof URIError) {
2620
+ return 6;
2621
+ }
2622
+ return 0;
2623
+ }
2624
+ function getInitialErrorOptions(error) {
2625
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
2626
+ if (error.name !== construct) {
2627
+ return { name: error.name };
2628
+ }
2629
+ if (error.constructor.name !== construct) {
2630
+ return { name: error.constructor.name };
2631
+ }
2632
+ return {};
2633
+ }
2634
+ function getErrorOptions(error, features) {
2635
+ let options = getInitialErrorOptions(error);
2636
+ const names = Object.getOwnPropertyNames(error);
2637
+ for (let i = 0, len = names.length, name;i < len; i++) {
2638
+ name = names[i];
2639
+ if (name !== "name" && name !== "message") {
2640
+ if (name === "stack") {
2641
+ if (features & 4) {
2642
+ options = options || {};
2643
+ options[name] = error[name];
2644
+ }
2645
+ } else {
2646
+ options = options || {};
2647
+ options[name] = error[name];
2648
+ }
2649
+ }
2650
+ }
2651
+ return options;
2652
+ }
2653
+ function getObjectFlag(obj) {
2654
+ if (Object.isFrozen(obj)) {
2655
+ return 3;
2656
+ }
2657
+ if (Object.isSealed(obj)) {
2658
+ return 2;
2659
+ }
2660
+ if (Object.isExtensible(obj)) {
2661
+ return 0;
2662
+ }
2663
+ return 1;
2664
+ }
2665
+ function createNumberNode(value) {
2666
+ switch (value) {
2667
+ case Number.POSITIVE_INFINITY:
2668
+ return INFINITY_NODE;
2669
+ case Number.NEGATIVE_INFINITY:
2670
+ return NEG_INFINITY_NODE;
2671
+ }
2672
+ if (value !== value) {
2673
+ return NAN_NODE;
2674
+ }
2675
+ if (Object.is(value, -0)) {
2676
+ return NEG_ZERO_NODE;
2677
+ }
2678
+ return createSerovalNode(0, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2679
+ }
2680
+ function createStringNode(value) {
2681
+ return createSerovalNode(1, NIL, serializeString(value), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2682
+ }
2683
+ function createBigIntNode(current) {
2684
+ return createSerovalNode(3, NIL, "" + current, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2685
+ }
2686
+ function createIndexedValueNode(id) {
2687
+ return createSerovalNode(4, id, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2688
+ }
2689
+ function createDateNode(id, current) {
2690
+ const timestamp = current.valueOf();
2691
+ return createSerovalNode(5, id, timestamp !== timestamp ? "" : current.toISOString(), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2692
+ }
2693
+ function createRegExpNode(id, current) {
2694
+ return createSerovalNode(6, id, NIL, serializeString(current.source), current.flags, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2695
+ }
2696
+ function createWKSymbolNode(id, current) {
2697
+ return createSerovalNode(17, id, INV_SYMBOL_REF[current], NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2698
+ }
2699
+ function createReferenceNode(id, ref) {
2700
+ return createSerovalNode(18, id, serializeString(getReferenceID(ref)), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2701
+ }
2702
+ function createPluginNode(id, tag, value) {
2703
+ return createSerovalNode(25, id, value, serializeString(tag), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2704
+ }
2705
+ function createArrayNode(id, current, parsedItems) {
2706
+ return createSerovalNode(9, id, NIL, NIL, NIL, NIL, NIL, parsedItems, NIL, NIL, getObjectFlag(current), NIL);
2707
+ }
2708
+ function createBoxedNode(id, boxed) {
2709
+ return createSerovalNode(21, id, NIL, NIL, NIL, NIL, NIL, NIL, boxed, NIL, NIL, NIL);
2710
+ }
2711
+ function createTypedArrayNode(id, current, buffer) {
2712
+ return createSerovalNode(15, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.length);
2713
+ }
2714
+ function createBigIntTypedArrayNode(id, current, buffer) {
2715
+ return createSerovalNode(16, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
2716
+ }
2717
+ function createDataViewNode(id, current, buffer) {
2718
+ return createSerovalNode(20, id, NIL, NIL, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
2719
+ }
2720
+ function createErrorNode(id, current, options) {
2721
+ return createSerovalNode(13, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
2722
+ }
2723
+ function createAggregateErrorNode(id, current, options) {
2724
+ return createSerovalNode(14, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
2725
+ }
2726
+ function createSetNode(id, items) {
2727
+ return createSerovalNode(7, id, NIL, NIL, NIL, NIL, NIL, items, NIL, NIL, NIL, NIL);
2728
+ }
2729
+ function createIteratorFactoryInstanceNode(factory, items) {
2730
+ return createSerovalNode(28, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
2731
+ }
2732
+ function createAsyncIteratorFactoryInstanceNode(factory, items) {
2733
+ return createSerovalNode(30, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
2734
+ }
2735
+ function createStreamConstructorNode(id, factory, sequence) {
2736
+ return createSerovalNode(31, id, NIL, NIL, NIL, NIL, NIL, sequence, factory, NIL, NIL, NIL);
2737
+ }
2738
+ function createStreamNextNode(id, parsed) {
2739
+ return createSerovalNode(32, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2740
+ }
2741
+ function createStreamThrowNode(id, parsed) {
2742
+ return createSerovalNode(33, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2743
+ }
2744
+ function createStreamReturnNode(id, parsed) {
2745
+ return createSerovalNode(34, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2746
+ }
2747
+ function createSequenceNode(id, sequence, throwAt, doneAt) {
2748
+ return createSerovalNode(35, id, throwAt, NIL, NIL, NIL, NIL, sequence, NIL, NIL, NIL, doneAt);
2749
+ }
2750
+ var { toString: objectToString } = Object.prototype;
2751
+ function getErrorMessageDev(type, cause) {
2752
+ if (cause instanceof Error) {
2753
+ return `Seroval caught an error during the ${type} process.
2754
+
2755
+ ${cause.name}
2756
+ ${cause.message}
2757
+
2758
+ - For more information, please check the "cause" property of this error.
2759
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
2760
+ }
2761
+ return `Seroval caught an error during the ${type} process.
2762
+
2763
+ "${objectToString.call(cause)}"
2764
+
2765
+ For more information, please check the "cause" property of this error.`;
2766
+ }
2767
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
2768
+ var SerovalError = class extends Error {
2769
+ constructor(type, cause) {
2770
+ super(getErrorMessage(type, cause));
2771
+ this.cause = cause;
2772
+ }
2773
+ };
2774
+ var SerovalParserError = class extends SerovalError {
2775
+ constructor(cause) {
2776
+ super("parsing", cause);
2777
+ }
2778
+ };
2779
+ var SerovalUnsupportedTypeError = class extends Error {
2780
+ constructor(value) {
2781
+ super(`The value ${objectToString.call(value)} of type "${typeof value}" cannot be parsed/serialized.
2782
+
2783
+ There are few workarounds for this problem:
2784
+ - Transform the value in a way that it can be serialized.
2785
+ - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`);
2786
+ this.value = value;
2787
+ }
2788
+ };
2789
+ var SerovalMissingReferenceError = class extends Error {
2790
+ constructor(value) {
2791
+ super('Missing reference for the value "' + objectToString.call(value) + '" of type "' + typeof value + '"');
2792
+ this.value = value;
2793
+ }
2794
+ };
2795
+ var OpaqueReference = class {
2796
+ constructor(value, replacement) {
2797
+ this.value = value;
2798
+ this.replacement = replacement;
2799
+ }
2800
+ };
2801
+ var PROMISE_CONSTRUCTOR = () => {
2802
+ const resolver = {
2803
+ p: 0,
2804
+ s: 0,
2805
+ f: 0
2806
+ };
2807
+ resolver.p = new Promise((resolve2, reject) => {
2808
+ resolver.s = resolve2;
2809
+ resolver.f = reject;
2810
+ });
2811
+ return resolver;
2812
+ };
2813
+ var STREAM_CONSTRUCTOR = () => {
2814
+ const buffer = [];
2815
+ const listeners = [];
2816
+ let alive = true;
2817
+ let success = false;
2818
+ let count = 0;
2819
+ const flush = (value, mode, x) => {
2820
+ for (x = 0;x < count; x++) {
2821
+ if (listeners[x]) {
2822
+ listeners[x][mode](value);
2823
+ }
2824
+ }
2825
+ };
2826
+ const up = (listener, x, z, current) => {
2827
+ for (x = 0, z = buffer.length;x < z; x++) {
2828
+ current = buffer[x];
2829
+ if (!alive && x === z - 1) {
2830
+ listener[success ? "return" : "throw"](current);
2831
+ } else {
2832
+ listener.next(current);
2833
+ }
2834
+ }
2835
+ };
2836
+ const on = (listener, temp) => {
2837
+ if (alive) {
2838
+ temp = count++;
2839
+ listeners[temp] = listener;
2840
+ }
2841
+ up(listener);
2842
+ return () => {
2843
+ if (alive) {
2844
+ listeners[temp] = listeners[count];
2845
+ listeners[count--] = undefined;
2846
+ }
2847
+ };
2848
+ };
2849
+ return {
2850
+ __SEROVAL_STREAM__: true,
2851
+ on: (listener) => on(listener),
2852
+ next: (value) => {
2853
+ if (alive) {
2854
+ buffer.push(value);
2855
+ flush(value, "next");
2856
+ }
2857
+ },
2858
+ throw: (value) => {
2859
+ if (alive) {
2860
+ buffer.push(value);
2861
+ flush(value, "throw");
2862
+ alive = false;
2863
+ success = false;
2864
+ listeners.length = 0;
2865
+ }
2866
+ },
2867
+ return: (value) => {
2868
+ if (alive) {
2869
+ buffer.push(value);
2870
+ flush(value, "return");
2871
+ alive = false;
2872
+ success = true;
2873
+ listeners.length = 0;
2874
+ }
2875
+ }
2876
+ };
2877
+ };
2878
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
2879
+ let index = 0;
2880
+ const instance = {
2881
+ [symbol]: () => instance,
2882
+ next: () => {
2883
+ if (index > sequence.d) {
2884
+ return {
2885
+ done: true,
2886
+ value: undefined
2887
+ };
2888
+ }
2889
+ const currentIndex = index++;
2890
+ const data = sequence.v[currentIndex];
2891
+ if (currentIndex === sequence.t) {
2892
+ throw data;
2893
+ }
2894
+ return {
2895
+ done: currentIndex === sequence.d,
2896
+ value: data
2897
+ };
2898
+ }
2899
+ };
2900
+ return instance;
2901
+ };
2902
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
2903
+ let count = 0;
2904
+ let doneAt = -1;
2905
+ let isThrow = false;
2906
+ const buffer = [];
2907
+ const pending = [];
2908
+ const finalize = (i = 0, len = pending.length) => {
2909
+ for (;i < len; i++) {
2910
+ pending[i].s({
2911
+ done: true,
2912
+ value: undefined
2913
+ });
2914
+ }
2915
+ };
2916
+ stream.on({
2917
+ next: (value) => {
2918
+ const temp = pending.shift();
2919
+ if (temp) {
2920
+ temp.s({ done: false, value });
2921
+ }
2922
+ buffer.push(value);
2923
+ },
2924
+ throw: (value) => {
2925
+ const temp = pending.shift();
2926
+ if (temp) {
2927
+ temp.f(value);
2928
+ }
2929
+ finalize();
2930
+ doneAt = buffer.length;
2931
+ isThrow = true;
2932
+ buffer.push(value);
2933
+ },
2934
+ return: (value) => {
2935
+ const temp = pending.shift();
2936
+ if (temp) {
2937
+ temp.s({ done: true, value });
2938
+ }
2939
+ finalize();
2940
+ doneAt = buffer.length;
2941
+ buffer.push(value);
2942
+ }
2943
+ });
2944
+ const instance = {
2945
+ [symbol]: () => instance,
2946
+ next: () => {
2947
+ if (doneAt === -1) {
2948
+ const index2 = count++;
2949
+ if (index2 >= buffer.length) {
2950
+ const temp = createPromise();
2951
+ pending.push(temp);
2952
+ return temp.p;
2953
+ }
2954
+ return {
2955
+ done: false,
2956
+ value: buffer[index2]
2957
+ };
2958
+ }
2959
+ if (count > doneAt) {
2960
+ return {
2961
+ done: true,
2962
+ value: undefined
2963
+ };
2964
+ }
2965
+ const index = count++;
2966
+ const value = buffer[index];
2967
+ if (index !== doneAt) {
2968
+ return {
2969
+ done: false,
2970
+ value
2971
+ };
2972
+ }
2973
+ if (isThrow) {
2974
+ throw value;
2975
+ }
2976
+ return {
2977
+ done: true,
2978
+ value
2979
+ };
2980
+ }
2981
+ };
2982
+ return instance;
2983
+ };
2984
+ function isSequence(value) {
2985
+ return "__SEROVAL_SEQUENCE__" in value;
2986
+ }
2987
+ function createSequence(values, throwAt, doneAt) {
2988
+ return {
2989
+ __SEROVAL_SEQUENCE__: true,
2990
+ v: values,
2991
+ t: throwAt,
2992
+ d: doneAt
2993
+ };
2994
+ }
2995
+ function createSequenceFromIterable(source) {
2996
+ const values = [];
2997
+ let throwsAt = -1;
2998
+ let doneAt = -1;
2999
+ const iterator = source[SYM_ITERATOR]();
3000
+ while (true) {
3001
+ try {
3002
+ const value = iterator.next();
3003
+ values.push(value.value);
3004
+ if (value.done) {
3005
+ doneAt = values.length - 1;
3006
+ break;
3007
+ }
3008
+ } catch (error) {
3009
+ throwsAt = values.length;
3010
+ values.push(error);
3011
+ }
3012
+ }
3013
+ return createSequence(values, throwsAt, doneAt);
3014
+ }
3015
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
3016
+ var ITERATOR = {};
3017
+ var ASYNC_ITERATOR = {};
3018
+ var SPECIAL_REFS = {
3019
+ [0]: {},
3020
+ [1]: {},
3021
+ [2]: {},
3022
+ [3]: {},
3023
+ [4]: {},
3024
+ [5]: {}
3025
+ };
3026
+ function isStream(value) {
3027
+ return "__SEROVAL_STREAM__" in value;
3028
+ }
3029
+ function createStream() {
3030
+ return STREAM_CONSTRUCTOR();
3031
+ }
3032
+ function createStreamFromAsyncIterable(iterable) {
3033
+ const stream = createStream();
3034
+ const iterator = iterable[SYM_ASYNC_ITERATOR]();
3035
+ async function push() {
3036
+ try {
3037
+ const value = await iterator.next();
3038
+ if (value.done) {
3039
+ stream.return(value.value);
3040
+ } else {
3041
+ stream.next(value.value);
3042
+ await push();
3043
+ }
3044
+ } catch (error) {
3045
+ stream.throw(error);
3046
+ }
3047
+ }
3048
+ push().catch(() => {});
3049
+ return stream;
3050
+ }
3051
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
3052
+ async function promiseToResult(current) {
3053
+ try {
3054
+ return [1, await current];
3055
+ } catch (e) {
3056
+ return [0, e];
3057
+ }
3058
+ }
3059
+ function createBaseParserContext(mode, options) {
3060
+ return {
3061
+ plugins: options.plugins,
3062
+ mode,
3063
+ marked: /* @__PURE__ */ new Set,
3064
+ features: ALL_ENABLED ^ (options.disabledFeatures || 0),
3065
+ refs: options.refs || /* @__PURE__ */ new Map,
3066
+ depthLimit: options.depthLimit || 1000
3067
+ };
3068
+ }
3069
+ function markParserRef(ctx, id) {
3070
+ ctx.marked.add(id);
3071
+ }
3072
+ function createIndexForValue(ctx, current) {
3073
+ const id = ctx.refs.size;
3074
+ ctx.refs.set(current, id);
3075
+ return id;
3076
+ }
3077
+ function getNodeForIndexedValue(ctx, current) {
3078
+ const registeredId = ctx.refs.get(current);
3079
+ if (registeredId != null) {
3080
+ markParserRef(ctx, registeredId);
3081
+ return {
3082
+ type: 1,
3083
+ value: createIndexedValueNode(registeredId)
3084
+ };
3085
+ }
3086
+ return {
3087
+ type: 0,
3088
+ value: createIndexForValue(ctx, current)
3089
+ };
3090
+ }
3091
+ function getReferenceNode(ctx, current) {
3092
+ const indexed = getNodeForIndexedValue(ctx, current);
3093
+ if (indexed.type === 1) {
3094
+ return indexed;
3095
+ }
3096
+ if (hasReferenceID(current)) {
3097
+ return {
3098
+ type: 2,
3099
+ value: createReferenceNode(indexed.value, current)
3100
+ };
3101
+ }
3102
+ return indexed;
3103
+ }
3104
+ function parseWellKnownSymbol(ctx, current) {
3105
+ const ref = getReferenceNode(ctx, current);
3106
+ if (ref.type !== 0) {
3107
+ return ref.value;
3108
+ }
3109
+ if (current in INV_SYMBOL_REF) {
3110
+ return createWKSymbolNode(ref.value, current);
3111
+ }
3112
+ throw new SerovalUnsupportedTypeError(current);
3113
+ }
3114
+ function parseSpecialReference(ctx, ref) {
3115
+ const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
3116
+ if (result.type === 1) {
3117
+ return result.value;
3118
+ }
3119
+ return createSerovalNode(26, result.value, ref, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
3120
+ }
3121
+ function parseIteratorFactory(ctx) {
3122
+ const result = getNodeForIndexedValue(ctx, ITERATOR);
3123
+ if (result.type === 1) {
3124
+ return result.value;
3125
+ }
3126
+ return createSerovalNode(27, result.value, NIL, NIL, NIL, NIL, NIL, NIL, parseWellKnownSymbol(ctx, SYM_ITERATOR), NIL, NIL, NIL);
3127
+ }
3128
+ function parseAsyncIteratorFactory(ctx) {
3129
+ const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
3130
+ if (result.type === 1) {
3131
+ return result.value;
3132
+ }
3133
+ return createSerovalNode(29, result.value, NIL, NIL, NIL, NIL, NIL, [
3134
+ parseSpecialReference(ctx, 1),
3135
+ parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)
3136
+ ], NIL, NIL, NIL, NIL);
3137
+ }
3138
+ function createObjectNode(id, current, empty, record) {
3139
+ return createSerovalNode(empty ? 11 : 10, id, NIL, NIL, NIL, record, NIL, NIL, NIL, NIL, getObjectFlag(current), NIL);
3140
+ }
3141
+ function createMapNode(ctx, id, k, v) {
3142
+ return createSerovalNode(8, id, NIL, NIL, NIL, NIL, { k, v }, NIL, parseSpecialReference(ctx, 0), NIL, NIL, NIL);
3143
+ }
3144
+ function createArrayBufferNode(ctx, id, current) {
3145
+ const bytes = new Uint8Array(current);
3146
+ let result = "";
3147
+ for (let i = 0, len = bytes.length;i < len; i++) {
3148
+ result += String.fromCharCode(bytes[i]);
3149
+ }
3150
+ return createSerovalNode(19, id, serializeString(btoa(result)), NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 5), NIL, NIL, NIL);
3151
+ }
3152
+ function createAsyncParserContext(mode, options) {
3153
+ return {
3154
+ base: createBaseParserContext(mode, options),
3155
+ child: undefined
3156
+ };
3157
+ }
3158
+ var AsyncParsePluginContext = class {
3159
+ constructor(_p, depth) {
3160
+ this._p = _p;
3161
+ this.depth = depth;
3162
+ }
3163
+ parse(current) {
3164
+ return parseAsync(this._p, this.depth, current);
3165
+ }
3166
+ };
3167
+ async function parseItems(ctx, depth, current) {
3168
+ const nodes = [];
3169
+ for (let i = 0, len = current.length;i < len; i++) {
3170
+ if (i in current) {
3171
+ nodes[i] = await parseAsync(ctx, depth, current[i]);
3172
+ } else {
3173
+ nodes[i] = 0;
3174
+ }
3175
+ }
3176
+ return nodes;
3177
+ }
3178
+ async function parseArray(ctx, depth, id, current) {
3179
+ return createArrayNode(id, current, await parseItems(ctx, depth, current));
3180
+ }
3181
+ async function parseProperties(ctx, depth, properties) {
3182
+ const entries = Object.entries(properties);
3183
+ const keyNodes = [];
3184
+ const valueNodes = [];
3185
+ for (let i = 0, len = entries.length;i < len; i++) {
3186
+ keyNodes.push(serializeString(entries[i][0]));
3187
+ valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
3188
+ }
3189
+ if (SYM_ITERATOR in properties) {
3190
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
3191
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
3192
+ }
3193
+ if (SYM_ASYNC_ITERATOR in properties) {
3194
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
3195
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
3196
+ }
3197
+ if (SYM_TO_STRING_TAG in properties) {
3198
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
3199
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
3200
+ }
3201
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
3202
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
3203
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
3204
+ }
3205
+ return {
3206
+ k: keyNodes,
3207
+ v: valueNodes
3208
+ };
3209
+ }
3210
+ async function parsePlainObject(ctx, depth, id, current, empty) {
3211
+ return createObjectNode(id, current, empty, await parseProperties(ctx, depth, current));
3212
+ }
3213
+ async function parseBoxed(ctx, depth, id, current) {
3214
+ return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
3215
+ }
3216
+ async function parseTypedArray(ctx, depth, id, current) {
3217
+ return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3218
+ }
3219
+ async function parseBigIntTypedArray(ctx, depth, id, current) {
3220
+ return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3221
+ }
3222
+ async function parseDataView(ctx, depth, id, current) {
3223
+ return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
3224
+ }
3225
+ async function parseError(ctx, depth, id, current) {
3226
+ const options = getErrorOptions(current, ctx.base.features);
3227
+ return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
3228
+ }
3229
+ async function parseAggregateError(ctx, depth, id, current) {
3230
+ const options = getErrorOptions(current, ctx.base.features);
3231
+ return createAggregateErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
3232
+ }
3233
+ async function parseMap(ctx, depth, id, current) {
3234
+ const keyNodes = [];
3235
+ const valueNodes = [];
3236
+ for (const [key, value] of current.entries()) {
3237
+ keyNodes.push(await parseAsync(ctx, depth, key));
3238
+ valueNodes.push(await parseAsync(ctx, depth, value));
3239
+ }
3240
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
3241
+ }
3242
+ async function parseSet(ctx, depth, id, current) {
3243
+ const items = [];
3244
+ for (const item of current.keys()) {
3245
+ items.push(await parseAsync(ctx, depth, item));
3246
+ }
3247
+ return createSetNode(id, items);
3248
+ }
3249
+ async function parsePlugin(ctx, depth, id, current) {
3250
+ const currentPlugins = ctx.base.plugins;
3251
+ if (currentPlugins) {
3252
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
3253
+ const plugin = currentPlugins[i];
3254
+ if (plugin.parse.async && plugin.test(current)) {
3255
+ return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), {
3256
+ id
3257
+ }));
3258
+ }
3259
+ }
3260
+ }
3261
+ return NIL;
3262
+ }
3263
+ async function parsePromise(ctx, depth, id, current) {
3264
+ const [status, result] = await promiseToResult(current);
3265
+ return createSerovalNode(12, id, status, NIL, NIL, NIL, NIL, NIL, await parseAsync(ctx, depth, result), NIL, NIL, NIL);
3266
+ }
3267
+ function parseStreamHandle(depth, id, current, resolve2, reject) {
3268
+ const sequence = [];
3269
+ const cleanup = current.on({
3270
+ next: (value) => {
3271
+ markParserRef(this.base, id);
3272
+ parseAsync(this, depth, value).then((data) => {
3273
+ sequence.push(createStreamNextNode(id, data));
3274
+ }, (data) => {
3275
+ reject(data);
3276
+ cleanup();
3277
+ });
3278
+ },
3279
+ throw: (value) => {
3280
+ markParserRef(this.base, id);
3281
+ parseAsync(this, depth, value).then((data) => {
3282
+ sequence.push(createStreamThrowNode(id, data));
3283
+ resolve2(sequence);
3284
+ cleanup();
3285
+ }, (data) => {
3286
+ reject(data);
3287
+ cleanup();
3288
+ });
3289
+ },
3290
+ return: (value) => {
3291
+ markParserRef(this.base, id);
3292
+ parseAsync(this, depth, value).then((data) => {
3293
+ sequence.push(createStreamReturnNode(id, data));
3294
+ resolve2(sequence);
3295
+ cleanup();
3296
+ }, (data) => {
3297
+ reject(data);
3298
+ cleanup();
3299
+ });
3300
+ }
3301
+ });
3302
+ }
3303
+ async function parseStream(ctx, depth, id, current) {
3304
+ return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
3305
+ }
3306
+ async function parseSequence(ctx, depth, id, current) {
3307
+ const nodes = [];
3308
+ for (let i = 0, len = current.v.length;i < len; i++) {
3309
+ nodes[i] = await parseAsync(ctx, depth, current.v[i]);
3310
+ }
3311
+ return createSequenceNode(id, nodes, current.t, current.d);
3312
+ }
3313
+ async function parseObjectAsync(ctx, depth, id, current) {
3314
+ if (Array.isArray(current)) {
3315
+ return parseArray(ctx, depth, id, current);
3316
+ }
3317
+ if (isStream(current)) {
3318
+ return parseStream(ctx, depth, id, current);
3319
+ }
3320
+ if (isSequence(current)) {
3321
+ return parseSequence(ctx, depth, id, current);
3322
+ }
3323
+ const currentClass = current.constructor;
3324
+ if (currentClass === OpaqueReference) {
3325
+ return parseAsync(ctx, depth, current.replacement);
3326
+ }
3327
+ const parsed = await parsePlugin(ctx, depth, id, current);
3328
+ if (parsed) {
3329
+ return parsed;
3330
+ }
3331
+ switch (currentClass) {
3332
+ case Object:
3333
+ return parsePlainObject(ctx, depth, id, current, false);
3334
+ case NIL:
3335
+ return parsePlainObject(ctx, depth, id, current, true);
3336
+ case Date:
3337
+ return createDateNode(id, current);
3338
+ case Error:
3339
+ case EvalError:
3340
+ case RangeError:
3341
+ case ReferenceError:
3342
+ case SyntaxError:
3343
+ case TypeError:
3344
+ case URIError:
3345
+ return parseError(ctx, depth, id, current);
3346
+ case Number:
3347
+ case Boolean:
3348
+ case String:
3349
+ case BigInt:
3350
+ return parseBoxed(ctx, depth, id, current);
3351
+ case ArrayBuffer:
3352
+ return createArrayBufferNode(ctx.base, id, current);
3353
+ case Int8Array:
3354
+ case Int16Array:
3355
+ case Int32Array:
3356
+ case Uint8Array:
3357
+ case Uint16Array:
3358
+ case Uint32Array:
3359
+ case Uint8ClampedArray:
3360
+ case Float32Array:
3361
+ case Float64Array:
3362
+ return parseTypedArray(ctx, depth, id, current);
3363
+ case DataView:
3364
+ return parseDataView(ctx, depth, id, current);
3365
+ case Map:
3366
+ return parseMap(ctx, depth, id, current);
3367
+ case Set:
3368
+ return parseSet(ctx, depth, id, current);
3369
+ default:
3370
+ break;
3371
+ }
3372
+ if (currentClass === Promise || current instanceof Promise) {
3373
+ return parsePromise(ctx, depth, id, current);
3374
+ }
3375
+ const currentFeatures = ctx.base.features;
3376
+ if (currentFeatures & 32 && currentClass === RegExp) {
3377
+ return createRegExpNode(id, current);
3378
+ }
3379
+ if (currentFeatures & 16) {
3380
+ switch (currentClass) {
3381
+ case BigInt64Array:
3382
+ case BigUint64Array:
3383
+ return parseBigIntTypedArray(ctx, depth, id, current);
3384
+ default:
3385
+ break;
3386
+ }
3387
+ }
3388
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
3389
+ return parseAggregateError(ctx, depth, id, current);
3390
+ }
3391
+ if (current instanceof Error) {
3392
+ return parseError(ctx, depth, id, current);
3393
+ }
3394
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
3395
+ return parsePlainObject(ctx, depth, id, current, !!currentClass);
3396
+ }
3397
+ throw new SerovalUnsupportedTypeError(current);
3398
+ }
3399
+ async function parseFunctionAsync(ctx, depth, current) {
3400
+ const ref = getReferenceNode(ctx.base, current);
3401
+ if (ref.type !== 0) {
3402
+ return ref.value;
3403
+ }
3404
+ const plugin = await parsePlugin(ctx, depth, ref.value, current);
3405
+ if (plugin) {
3406
+ return plugin;
3407
+ }
3408
+ throw new SerovalUnsupportedTypeError(current);
3409
+ }
3410
+ async function parseAsync(ctx, depth, current) {
3411
+ switch (typeof current) {
3412
+ case "boolean":
3413
+ return current ? TRUE_NODE : FALSE_NODE;
3414
+ case "undefined":
3415
+ return UNDEFINED_NODE;
3416
+ case "string":
3417
+ return createStringNode(current);
3418
+ case "number":
3419
+ return createNumberNode(current);
3420
+ case "bigint":
3421
+ return createBigIntNode(current);
3422
+ case "object": {
3423
+ if (current) {
3424
+ const ref = getReferenceNode(ctx.base, current);
3425
+ return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
3426
+ }
3427
+ return NULL_NODE;
3428
+ }
3429
+ case "symbol":
3430
+ return parseWellKnownSymbol(ctx.base, current);
3431
+ case "function":
3432
+ return parseFunctionAsync(ctx, depth, current);
3433
+ default:
3434
+ throw new SerovalUnsupportedTypeError(current);
3435
+ }
3436
+ }
3437
+ async function parseTopAsync(ctx, current) {
3438
+ try {
3439
+ return await parseAsync(ctx, 0, current);
3440
+ } catch (error) {
3441
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3442
+ }
3443
+ }
3444
+ function dedupePlugins(deduped, plugins) {
3445
+ for (let i = 0, len = plugins.length;i < len; i++) {
3446
+ const current = plugins[i];
3447
+ if (!deduped.has(current)) {
3448
+ deduped.add(current);
3449
+ if (current.extends) {
3450
+ dedupePlugins(deduped, current.extends);
3451
+ }
3452
+ }
3453
+ }
3454
+ }
3455
+ function resolvePlugins(plugins) {
3456
+ if (plugins) {
3457
+ const deduped = /* @__PURE__ */ new Set;
3458
+ dedupePlugins(deduped, plugins);
3459
+ return [...deduped];
3460
+ }
3461
+ return;
3462
+ }
3463
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
3464
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
3465
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
3466
+ var REF_CHARS_LEN = REF_CHARS.length;
3467
+ async function toCrossJSONAsync(source, options = {}) {
3468
+ const plugins = resolvePlugins(options.plugins);
3469
+ const ctx = createAsyncParserContext(2, {
3470
+ plugins,
3471
+ disabledFeatures: options.disabledFeatures,
3472
+ refs: options.refs
3473
+ });
3474
+ return await parseTopAsync(ctx, source);
3475
+ }
3476
+
2274
3477
  // src/not-found.ts
2275
3478
  var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
2276
3479
 
@@ -2286,7 +3489,7 @@ function isNotFoundError(err) {
2286
3489
  return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
2287
3490
  }
2288
3491
 
2289
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
3492
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/utils.mjs
2290
3493
  function formatDuration(ms) {
2291
3494
  if (ms < 1000)
2292
3495
  return `${Math.round(ms)}ms`;
@@ -2374,6 +3577,21 @@ function getCssLevelColor(level) {
2374
3577
  function escapeFormatString(str) {
2375
3578
  return str.replace(/%/g, "%%");
2376
3579
  }
3580
+ var SENSITIVE_HEADERS = [
3581
+ "authorization",
3582
+ "cookie",
3583
+ "set-cookie",
3584
+ "x-api-key",
3585
+ "x-auth-token",
3586
+ "proxy-authorization"
3587
+ ];
3588
+ function filterSafeHeaders(headers) {
3589
+ const safeHeaders = {};
3590
+ for (const [key, value] of Object.entries(headers))
3591
+ if (!SENSITIVE_HEADERS.includes(key.toLowerCase()))
3592
+ safeHeaders[key] = value;
3593
+ return safeHeaders;
3594
+ }
2377
3595
  var patternCache = /* @__PURE__ */ new Map;
2378
3596
  function matchesPattern(path, pattern) {
2379
3597
  let regex = patternCache.get(pattern);
@@ -2385,7 +3603,25 @@ function matchesPattern(path, pattern) {
2385
3603
  return regex.test(path);
2386
3604
  }
2387
3605
 
2388
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
3606
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/headers-CU-QqnYg.mjs
3607
+ function extractSafeHeaders(headers) {
3608
+ const raw = {};
3609
+ headers.forEach((value, key) => {
3610
+ raw[key] = value;
3611
+ });
3612
+ return filterSafeHeaders(raw);
3613
+ }
3614
+ function extractSafeNodeHeaders(headers) {
3615
+ const raw = {};
3616
+ for (const [key, value] of Object.entries(headers)) {
3617
+ if (value === undefined)
3618
+ continue;
3619
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
3620
+ }
3621
+ return filterSafeHeaders(raw);
3622
+ }
3623
+
3624
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/audit-pV5aLGP0.mjs
2389
3625
  var DEFAULT_REPLACEMENT = "[REDACTED]";
2390
3626
  var builtinPatterns = {
2391
3627
  creditCard: {
@@ -2536,6 +3772,117 @@ function applyMaskers(value, maskers) {
2536
3772
  }
2537
3773
  return result;
2538
3774
  }
3775
+ function logPluginError(name, hook, err) {
3776
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
3777
+ }
3778
+ function createPluginRunner(plugins = []) {
3779
+ const byName = /* @__PURE__ */ new Map;
3780
+ for (const plugin of plugins)
3781
+ byName.set(plugin.name, plugin);
3782
+ const list = Array.from(byName.values());
3783
+ return {
3784
+ plugins: list,
3785
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
3786
+ hasDrain: list.some((p) => typeof p.drain === "function"),
3787
+ hasKeep: list.some((p) => typeof p.keep === "function"),
3788
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
3789
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
3790
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
3791
+ applyExtendLogger(logger) {
3792
+ for (const plugin of list) {
3793
+ if (!plugin.extendLogger)
3794
+ continue;
3795
+ try {
3796
+ plugin.extendLogger(logger);
3797
+ } catch (err) {
3798
+ logPluginError(plugin.name, "extendLogger", err);
3799
+ }
3800
+ }
3801
+ },
3802
+ runOnRequestStart(ctx) {
3803
+ for (const plugin of list) {
3804
+ if (!plugin.onRequestStart)
3805
+ continue;
3806
+ try {
3807
+ plugin.onRequestStart(ctx);
3808
+ } catch (err) {
3809
+ logPluginError(plugin.name, "onRequestStart", err);
3810
+ }
3811
+ }
3812
+ },
3813
+ runOnRequestFinish(ctx) {
3814
+ for (const plugin of list) {
3815
+ if (!plugin.onRequestFinish)
3816
+ continue;
3817
+ try {
3818
+ plugin.onRequestFinish(ctx);
3819
+ } catch (err) {
3820
+ logPluginError(plugin.name, "onRequestFinish", err);
3821
+ }
3822
+ }
3823
+ },
3824
+ async runEnrich(ctx) {
3825
+ for (const plugin of list) {
3826
+ if (!plugin.enrich)
3827
+ continue;
3828
+ try {
3829
+ await plugin.enrich(ctx);
3830
+ } catch (err) {
3831
+ logPluginError(plugin.name, "enrich", err);
3832
+ }
3833
+ }
3834
+ },
3835
+ async runDrain(ctx) {
3836
+ const drains = list.filter((p) => typeof p.drain === "function");
3837
+ if (drains.length === 0)
3838
+ return;
3839
+ await Promise.allSettled(drains.map(async (plugin) => {
3840
+ try {
3841
+ await plugin.drain(ctx);
3842
+ } catch (err) {
3843
+ logPluginError(plugin.name, "drain", err);
3844
+ }
3845
+ }));
3846
+ },
3847
+ async runKeep(ctx) {
3848
+ for (const plugin of list) {
3849
+ if (!plugin.keep)
3850
+ continue;
3851
+ try {
3852
+ await plugin.keep(ctx);
3853
+ } catch (err) {
3854
+ logPluginError(plugin.name, "keep", err);
3855
+ }
3856
+ }
3857
+ },
3858
+ runOnClientLog(ctx) {
3859
+ for (const plugin of list) {
3860
+ if (!plugin.onClientLog)
3861
+ continue;
3862
+ try {
3863
+ plugin.onClientLog(ctx);
3864
+ } catch (err) {
3865
+ logPluginError(plugin.name, "onClientLog", err);
3866
+ }
3867
+ }
3868
+ },
3869
+ async runSetup(ctx) {
3870
+ for (const plugin of list) {
3871
+ if (!plugin.setup)
3872
+ continue;
3873
+ try {
3874
+ await plugin.setup(ctx);
3875
+ } catch (err) {
3876
+ logPluginError(plugin.name, "setup", err);
3877
+ }
3878
+ }
3879
+ }
3880
+ };
3881
+ }
3882
+ var emptyRunner = createPluginRunner([]);
3883
+ function getEmptyPluginRunner() {
3884
+ return emptyRunner;
3885
+ }
2539
3886
  function isPlainObject(val) {
2540
3887
  return val !== null && typeof val === "object" && !Array.isArray(val);
2541
3888
  }
@@ -2574,6 +3921,7 @@ var globalRedact;
2574
3921
  var globalEnabled = true;
2575
3922
  var globalSilent = false;
2576
3923
  var globalMinLevel = "debug";
3924
+ var globalPluginRunner = getEmptyPluginRunner();
2577
3925
  function initLogger(config = {}) {
2578
3926
  globalEnabled = config.enabled ?? true;
2579
3927
  const detected = detectEnvironment();
@@ -2591,9 +3939,22 @@ function initLogger(config = {}) {
2591
3939
  globalRedact = resolveRedactConfig(config.redact ?? !isDev());
2592
3940
  globalSilent = config.silent ?? false;
2593
3941
  globalMinLevel = config.minLevel ?? "debug";
2594
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
3942
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
3943
+ if (globalPluginRunner.plugins.length > 0)
3944
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
3945
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
3946
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
2595
3947
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
2596
3948
  }
3949
+ function getGlobalPluginRunner() {
3950
+ return globalPluginRunner;
3951
+ }
3952
+ function isEnabled() {
3953
+ return globalEnabled;
3954
+ }
3955
+ function getGlobalDrain() {
3956
+ return globalDrain;
3957
+ }
2597
3958
  function shouldSample(level) {
2598
3959
  const { rates } = globalSampling;
2599
3960
  if (!rates)
@@ -2661,12 +4022,20 @@ function emitWideEvent(level, event, options = {}) {
2661
4022
  console[getConsoleMethod(level)](JSON.stringify(formatted));
2662
4023
  else
2663
4024
  console[getConsoleMethod(level)](formatted);
2664
- if (globalDrain && !deferDrain) {
2665
- const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2666
- console.error("[evlog] drain failed:", err);
2667
- });
2668
- if (waitUntil)
2669
- waitUntil(drainPromise);
4025
+ if (!deferDrain) {
4026
+ const drainPromises = [];
4027
+ if (globalDrain)
4028
+ drainPromises.push((async () => {
4029
+ try {
4030
+ await globalDrain({ event: formatted });
4031
+ } catch (err) {
4032
+ console.error("[evlog] drain failed:", err);
4033
+ }
4034
+ })());
4035
+ if (globalPluginRunner.hasDrain)
4036
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
4037
+ if (drainPromises.length > 0 && waitUntil)
4038
+ waitUntil(Promise.all(drainPromises));
2670
4039
  }
2671
4040
  return formatted;
2672
4041
  }
@@ -3035,6 +4404,7 @@ function createLogger(initialContext = {}, internalOptions) {
3035
4404
  };
3036
4405
  const errRecord = err;
3037
4406
  for (const k of [
4407
+ "code",
3038
4408
  "status",
3039
4409
  "statusText",
3040
4410
  "statusCode",
@@ -3117,6 +4487,20 @@ function createLogger(initialContext = {}, internalOptions) {
3117
4487
  }
3118
4488
  };
3119
4489
  }
4490
+ function createRequestLogger(options = {}, internalOptions) {
4491
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
4492
+ const initial = {};
4493
+ if (method !== undefined)
4494
+ initial.method = method;
4495
+ if (path !== undefined)
4496
+ initial.path = path;
4497
+ if (requestId !== undefined)
4498
+ initial.requestId = requestId;
4499
+ return createLogger(initial, {
4500
+ ...internalOptions,
4501
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
4502
+ });
4503
+ }
3120
4504
  if (typeof __EVLOG_CONFIG__ !== "undefined")
3121
4505
  initLogger(__EVLOG_CONFIG__);
3122
4506
  function stableStringify(value) {
@@ -3191,6 +4575,16 @@ function finalizeAudit(event) {
3191
4575
  return;
3192
4576
  event.audit = decorateAudit(a, String(event.timestamp));
3193
4577
  }
4578
+
4579
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
4580
+ function extractErrorStatus(error) {
4581
+ if (error === null || typeof error !== "object")
4582
+ return 500;
4583
+ const raw = error.status ?? error.statusCode;
4584
+ const status = Number(raw);
4585
+ return Number.isFinite(status) ? status : 500;
4586
+ }
4587
+
3194
4588
  // src/router-provider.tsx
3195
4589
  import {
3196
4590
  createContext,
@@ -3210,12 +4604,29 @@ import { Component, Fragment } from "react";
3210
4604
  // src/error.ts
3211
4605
  function getPublicErrorMessage(error) {
3212
4606
  const branded = error;
3213
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
4607
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
3214
4608
  return error.message;
3215
4609
  }
3216
4610
  return "Something went wrong";
3217
4611
  }
3218
4612
 
4613
+ // src/server-error.ts
4614
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
4615
+
4616
+ class FurinServerError extends Error {
4617
+ __furinBrand = SERVER_ERROR_BRAND;
4618
+ digest;
4619
+ status;
4620
+ constructor(args) {
4621
+ super(args.message);
4622
+ this.status = args.status;
4623
+ this.digest = args.digest;
4624
+ }
4625
+ }
4626
+ function isFurinServerError(err) {
4627
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
4628
+ }
4629
+
3219
4630
  // src/link.tsx
3220
4631
  import { createElement, useCallback, useEffect, useRef } from "react";
3221
4632
  function computeLinkView({
@@ -3265,9 +4676,10 @@ function LinkInteractive({
3265
4676
  const effectivePreload = preload ?? router.defaultPreload;
3266
4677
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3267
4678
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
4679
+ const { prefetch } = router;
3268
4680
  const triggerPrefetch = useCallback(() => {
3269
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3270
- }, [router, logicalHref, effectiveStaleTime]);
4681
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
4682
+ }, [prefetch, logicalHref, effectiveStaleTime]);
3271
4683
  useEffect(() => {
3272
4684
  if (effectivePreload === "render") {
3273
4685
  triggerPrefetch();
@@ -3318,6 +4730,10 @@ function LinkInteractive({
3318
4730
  return;
3319
4731
  }
3320
4732
  e.preventDefault();
4733
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
4734
+ window.location.href = href;
4735
+ return;
4736
+ }
3321
4737
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3322
4738
  };
3323
4739
  const handleMouseEnter = (e) => {
@@ -3480,11 +4896,6 @@ var BADGE_STYLE = {
3480
4896
  marginBottom: "16px",
3481
4897
  padding: "12px 36px"
3482
4898
  };
3483
- var NOT_FOUND_BADGE_STYLE = {
3484
- ...BADGE_STYLE,
3485
- border: 0,
3486
- padding: 0
3487
- };
3488
4899
  var HEADING_STYLE = {
3489
4900
  color: COLOR_TEXT,
3490
4901
  fontFamily: FONT_SANS,
@@ -3572,7 +4983,7 @@ function ScreenFrame({ badge, children }) {
3572
4983
  style: PAGE_STYLE,
3573
4984
  children: [
3574
4985
  /* @__PURE__ */ jsxDEV("style", {
3575
- dangerouslySetInnerHTML: { __html: RESET_CSS }
4986
+ children: RESET_CSS
3576
4987
  }, undefined, false, undefined, this),
3577
4988
  /* @__PURE__ */ jsxDEV("div", {
3578
4989
  style: FRAME_STYLE,
@@ -3653,7 +5064,7 @@ function DefaultErrorScreen({ message, digest, reset }) {
3653
5064
  function DefaultNotFoundScreen({ message }) {
3654
5065
  return /* @__PURE__ */ jsxDEV(ScreenFrame, {
3655
5066
  badge: /* @__PURE__ */ jsxDEV("div", {
3656
- style: NOT_FOUND_BADGE_STYLE,
5067
+ style: BADGE_STYLE,
3657
5068
  children: "404 \u2014 NOT FOUND"
3658
5069
  }, undefined, false, undefined, this),
3659
5070
  children: [
@@ -3719,6 +5130,7 @@ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(Default
3719
5130
  message: error.message,
3720
5131
  reset
3721
5132
  }, undefined, false, undefined, this);
5133
+ var DEFAULT_ERROR_STATUS = 500;
3722
5134
  var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
3723
5135
  message: error.message
3724
5136
  }, undefined, false, undefined, this);
@@ -3750,10 +5162,12 @@ class FurinErrorBoundary extends Component {
3750
5162
  throw error;
3751
5163
  }
3752
5164
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
3753
- const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
5165
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
5166
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
3754
5167
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
5168
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
3755
5169
  return /* @__PURE__ */ jsxDEV2(Fallback, {
3756
- error: { message, digest: finalDigest },
5170
+ error: { message, digest: finalDigest, status },
3757
5171
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
3758
5172
  }, undefined, false, undefined, this);
3759
5173
  }
@@ -3842,23 +5256,432 @@ function normalizeHref(href) {
3842
5256
  return pathname + url.search + url.hash;
3843
5257
  }
3844
5258
 
5259
+ // src/utils.ts
5260
+ function isFurinPage(value) {
5261
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
5262
+ }
5263
+ function isFurinRoute(value) {
5264
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
5265
+ }
5266
+ function collectRouteChainFromRoute(route) {
5267
+ const chain = [];
5268
+ let current = route;
5269
+ while (current) {
5270
+ chain.unshift(current);
5271
+ current = current.parent;
5272
+ }
5273
+ return chain;
5274
+ }
5275
+ function hasCycle(route) {
5276
+ const visited = new Set;
5277
+ let current = route;
5278
+ while (current) {
5279
+ if (visited.has(current)) {
5280
+ return true;
5281
+ }
5282
+ visited.add(current);
5283
+ current = current.parent;
5284
+ }
5285
+ return false;
5286
+ }
5287
+ async function mapWithConcurrency(items, concurrency, fn) {
5288
+ if (items.length === 0) {
5289
+ return [];
5290
+ }
5291
+ const results = new Array(items.length);
5292
+ let cursor = 0;
5293
+ const workerCount = Math.min(Math.max(concurrency, 1), items.length);
5294
+ await Promise.all(Array.from({ length: workerCount }, async () => {
5295
+ while (true) {
5296
+ const index = cursor++;
5297
+ if (index >= items.length) {
5298
+ return;
5299
+ }
5300
+ results[index] = await fn(items[index], index);
5301
+ }
5302
+ }));
5303
+ return results;
5304
+ }
5305
+ function validateRouteChain(chain, root, pagePath) {
5306
+ const hasRoot = chain.some((r) => r === root);
5307
+ if (!hasRoot) {
5308
+ const location = pagePath ? `in ${pagePath}` : "";
5309
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
5310
+ }
5311
+ for (const route of chain) {
5312
+ if (hasCycle(route)) {
5313
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
5314
+ }
5315
+ }
5316
+ }
5317
+
3845
5318
  // src/render/cache.ts
3846
5319
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3847
5320
 
5321
+ // src/auto-invalidate/registry.ts
5322
+ class AutoInvalidateRegistry {
5323
+ pathToTags = new Map;
5324
+ tagToPaths = new Map;
5325
+ registerLoaderTags(urlPath, tags) {
5326
+ if (!tags || tags.length === 0) {
5327
+ this.unregisterPath(urlPath);
5328
+ return;
5329
+ }
5330
+ this.unregisterPath(urlPath);
5331
+ const uniqueTags = new Set(tags);
5332
+ this.pathToTags.set(urlPath, uniqueTags);
5333
+ for (const tag of uniqueTags) {
5334
+ let paths = this.tagToPaths.get(tag);
5335
+ if (!paths) {
5336
+ paths = new Set;
5337
+ this.tagToPaths.set(tag, paths);
5338
+ }
5339
+ paths.add(urlPath);
5340
+ }
5341
+ }
5342
+ pathsForTags(tags) {
5343
+ const paths = new Set;
5344
+ for (const tag of tags) {
5345
+ for (const path of this.tagToPaths.get(tag) ?? []) {
5346
+ paths.add(path);
5347
+ }
5348
+ }
5349
+ return [...paths];
5350
+ }
5351
+ unregisterPath(urlPath) {
5352
+ const tags = this.pathToTags.get(urlPath);
5353
+ if (!tags) {
5354
+ return;
5355
+ }
5356
+ for (const tag of tags) {
5357
+ const paths = this.tagToPaths.get(tag);
5358
+ if (!paths) {
5359
+ continue;
5360
+ }
5361
+ paths.delete(urlPath);
5362
+ if (paths.size === 0) {
5363
+ this.tagToPaths.delete(tag);
5364
+ }
5365
+ }
5366
+ this.pathToTags.delete(urlPath);
5367
+ }
5368
+ reset() {
5369
+ this.pathToTags.clear();
5370
+ this.tagToPaths.clear();
5371
+ }
5372
+ }
5373
+ var autoInvalidateRegistry = new AutoInvalidateRegistry;
5374
+
3848
5375
  // src/context-logger.ts
3849
5376
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3850
5377
 
3851
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/elysia/index.mjs
5378
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/routes-CnIgYWf8.mjs
5379
+ function shouldLog(path, include, exclude) {
5380
+ if (exclude && exclude.length > 0) {
5381
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
5382
+ return false;
5383
+ }
5384
+ if (!include || include.length === 0)
5385
+ return true;
5386
+ return include.some((pattern) => matchesPattern(path, pattern));
5387
+ }
5388
+ function getServiceForPath(path, routes) {
5389
+ if (!routes)
5390
+ return;
5391
+ for (const [pattern, config] of Object.entries(routes))
5392
+ if (matchesPattern(path, pattern))
5393
+ return config.service;
5394
+ }
5395
+
5396
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/fork-8u_zFOJq.mjs
5397
+ var noopResult = {
5398
+ logger: {
5399
+ set() {},
5400
+ error() {},
5401
+ info() {},
5402
+ warn() {},
5403
+ emit() {
5404
+ return null;
5405
+ },
5406
+ getContext() {
5407
+ return {};
5408
+ }
5409
+ },
5410
+ finish: () => Promise.resolve(null),
5411
+ skipped: true
5412
+ };
5413
+ var runnerCache = /* @__PURE__ */ new WeakMap;
5414
+ function resolveMiddlewarePluginRunner(options) {
5415
+ const global2 = getGlobalPluginRunner();
5416
+ const local = options.plugins;
5417
+ if (!local || local.length === 0)
5418
+ return global2;
5419
+ const cached = runnerCache.get(local);
5420
+ if (cached && cached.global === global2)
5421
+ return cached.merged;
5422
+ const merged = /* @__PURE__ */ new Map;
5423
+ for (const plugin of global2.plugins)
5424
+ merged.set(plugin.name, plugin);
5425
+ for (const plugin of local)
5426
+ merged.set(plugin.name, plugin);
5427
+ if (merged.size === 0)
5428
+ return getEmptyPluginRunner();
5429
+ const runner = createPluginRunner(Array.from(merged.values()));
5430
+ runnerCache.set(local, {
5431
+ global: global2,
5432
+ merged: runner
5433
+ });
5434
+ return runner;
5435
+ }
5436
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
5437
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
5438
+ const resolvedRedact = resolveRedactConfig(options.redact);
5439
+ if (resolvedRedact)
5440
+ redactEvent(emittedEvent, resolvedRedact);
5441
+ if (options.enrich || runner.hasEnrich) {
5442
+ const enrichCtx = {
5443
+ event: emittedEvent,
5444
+ request: requestInfo,
5445
+ headers: options.headers,
5446
+ response: { status: responseStatus }
5447
+ };
5448
+ if (options.enrich)
5449
+ try {
5450
+ await options.enrich(enrichCtx);
5451
+ } catch (err) {
5452
+ console.error("[evlog] enrich failed:", err);
5453
+ }
5454
+ if (runner.hasEnrich)
5455
+ await runner.runEnrich(enrichCtx);
5456
+ }
5457
+ const drain = options.drain ?? getGlobalDrain();
5458
+ const hasUserDrain = !!drain;
5459
+ const hasPluginDrain = runner.hasDrain;
5460
+ if (hasUserDrain || hasPluginDrain) {
5461
+ const drainCtx = {
5462
+ event: emittedEvent,
5463
+ request: requestInfo,
5464
+ headers: options.headers
5465
+ };
5466
+ const tasks = [];
5467
+ if (hasUserDrain)
5468
+ tasks.push((async () => {
5469
+ try {
5470
+ await drain(drainCtx);
5471
+ } catch (err) {
5472
+ console.error("[evlog] drain failed:", err);
5473
+ }
5474
+ })());
5475
+ if (hasPluginDrain)
5476
+ tasks.push(runner.runDrain(drainCtx));
5477
+ await Promise.all(tasks);
5478
+ }
5479
+ }
5480
+ function createMiddlewareLogger(options) {
5481
+ if (!isEnabled())
5482
+ return noopResult;
5483
+ const { method, path, requestId, include, exclude, routes, keep } = options;
5484
+ if (!shouldLog(path, include, exclude))
5485
+ return noopResult;
5486
+ const resolvedRequestId = requestId || crypto.randomUUID();
5487
+ const logger = createRequestLogger({
5488
+ method,
5489
+ path,
5490
+ requestId: resolvedRequestId
5491
+ }, { _deferDrain: true });
5492
+ const routeService = getServiceForPath(path, routes);
5493
+ if (routeService)
5494
+ logger.set({ service: routeService });
5495
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
5496
+ if (pluginRunner.hasExtendLogger)
5497
+ pluginRunner.applyExtendLogger(logger);
5498
+ const startTime = Date.now();
5499
+ const requestInfo = {
5500
+ method,
5501
+ path,
5502
+ requestId: resolvedRequestId
5503
+ };
5504
+ if (pluginRunner.hasRequestLifecycle)
5505
+ pluginRunner.runOnRequestStart({
5506
+ logger,
5507
+ request: requestInfo,
5508
+ headers: options.headers
5509
+ });
5510
+ const finish = async (opts) => {
5511
+ const { status, error } = opts ?? {};
5512
+ if (error) {
5513
+ logger.error(error);
5514
+ const errorStatus = extractErrorStatus(error);
5515
+ logger.set({ status: errorStatus });
5516
+ } else if (status !== undefined)
5517
+ logger.set({ status });
5518
+ const durationMs = Date.now() - startTime;
5519
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? logger.getContext().status;
5520
+ const tailCtx = {
5521
+ status: resolvedStatus,
5522
+ duration: durationMs,
5523
+ path,
5524
+ method,
5525
+ context: logger.getContext(),
5526
+ shouldKeep: false
5527
+ };
5528
+ if (keep)
5529
+ await keep(tailCtx);
5530
+ if (pluginRunner.hasKeep)
5531
+ await pluginRunner.runKeep(tailCtx);
5532
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
5533
+ const emittedEvent = logger.emit({ _forceKeep: forceKeep });
5534
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
5535
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
5536
+ if (pluginRunner.hasRequestLifecycle)
5537
+ pluginRunner.runOnRequestFinish({
5538
+ logger,
5539
+ request: requestInfo,
5540
+ headers: options.headers,
5541
+ event: emittedEvent,
5542
+ status: resolvedStatus,
5543
+ durationMs,
5544
+ error
5545
+ });
5546
+ return emittedEvent;
5547
+ };
5548
+ return {
5549
+ logger,
5550
+ finish,
5551
+ skipped: false
5552
+ };
5553
+ }
5554
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
5555
+ const log = parent;
5556
+ log.fork = (label, fn) => {
5557
+ forkBackgroundLogger({
5558
+ storage,
5559
+ parent,
5560
+ middlewareOptions,
5561
+ label,
5562
+ fn,
5563
+ lifecycle
5564
+ });
5565
+ };
5566
+ }
5567
+ function forkBackgroundLogger(options) {
5568
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
5569
+ const parentCtx = parent.getContext();
5570
+ const parentRequestId = parentCtx.requestId;
5571
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
5572
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
5573
+ const method = String(parentCtx.method ?? middlewareOptions.method);
5574
+ const path = String(parentCtx.path ?? middlewareOptions.path);
5575
+ const child = createRequestLogger({
5576
+ method,
5577
+ path,
5578
+ requestId: crypto.randomUUID()
5579
+ }, { _deferDrain: true });
5580
+ child.set({
5581
+ operation: label,
5582
+ _parentRequestId: parentRequestId
5583
+ });
5584
+ const childRequestInfo = {
5585
+ method,
5586
+ path,
5587
+ requestId: child.getContext().requestId
5588
+ };
5589
+ storage.run(child, () => {
5590
+ lifecycle?.onChildEnter?.(child);
5591
+ Promise.resolve().then(() => fn()).then(async () => {
5592
+ const emittedEvent = child.emit();
5593
+ const ctxStatus = child.getContext().status;
5594
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
5595
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
5596
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
5597
+ }).catch(async (err) => {
5598
+ const error = err instanceof Error ? err : new Error(String(err));
5599
+ child.error(error);
5600
+ child.set({ status: extractErrorStatus(error) });
5601
+ const emittedEvent = child.emit();
5602
+ const status = extractErrorStatus(error);
5603
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
5604
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
5605
+ }).finally(() => {
5606
+ lifecycle?.onChildExit?.(child);
5607
+ });
5608
+ });
5609
+ }
5610
+
5611
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/integration-DTZtjSqh.mjs
5612
+ function normalizeHeaders(headers) {
5613
+ if (!headers)
5614
+ return;
5615
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
5616
+ return extractSafeHeaders(headers);
5617
+ return extractSafeNodeHeaders(headers);
5618
+ }
5619
+ function defineFrameworkIntegration(spec) {
5620
+ return { start(ctx, options = {}) {
5621
+ const extracted = spec.extractRequest(ctx);
5622
+ const headers = normalizeHeaders(extracted.headers);
5623
+ const middlewareOptions = {
5624
+ method: extracted.method,
5625
+ path: extracted.path,
5626
+ requestId: extracted.requestId || crypto.randomUUID(),
5627
+ headers,
5628
+ ...options
5629
+ };
5630
+ const result = createMiddlewareLogger(middlewareOptions);
5631
+ if (!result.skipped) {
5632
+ if (spec.storage)
5633
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
5634
+ spec.attachLogger(ctx, result.logger);
5635
+ }
5636
+ const { storage } = spec;
5637
+ const runWith = async (fn) => {
5638
+ if (!storage || result.skipped)
5639
+ return await fn();
5640
+ return await storage.run(result.logger, fn);
5641
+ };
5642
+ return {
5643
+ ...result,
5644
+ middlewareOptions,
5645
+ runWith
5646
+ };
5647
+ } };
5648
+ }
5649
+
5650
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/elysia/index.mjs
3852
5651
  import { AsyncLocalStorage } from "async_hooks";
3853
5652
  import { Elysia } from "elysia";
3854
5653
  var storage = new AsyncLocalStorage;
3855
5654
  var activeLoggers = /* @__PURE__ */ new WeakSet;
3856
- function useLogger2() {
5655
+ function useLogger() {
3857
5656
  const logger = storage.getStore();
3858
5657
  if (!logger || !activeLoggers.has(logger))
3859
5658
  throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
3860
5659
  return logger;
3861
5660
  }
5661
+ var integration = defineFrameworkIntegration({
5662
+ name: "elysia",
5663
+ extractRequest: ({ request, path, headers }) => ({
5664
+ method: request.method,
5665
+ path,
5666
+ headers,
5667
+ requestId: headers["x-request-id"]
5668
+ }),
5669
+ attachLogger: ({ request, path, headers }, logger) => {
5670
+ attachForkToLogger(storage, logger, {
5671
+ method: request.method,
5672
+ path,
5673
+ requestId: headers["x-request-id"]
5674
+ }, {
5675
+ onChildEnter: (child) => {
5676
+ activeLoggers.add(child);
5677
+ },
5678
+ onChildExit: (child) => {
5679
+ activeLoggers.delete(child);
5680
+ }
5681
+ });
5682
+ activeLoggers.add(logger);
5683
+ }
5684
+ });
3862
5685
 
3863
5686
  // src/context-logger.ts
3864
5687
  var noopLogger2 = {
@@ -3871,9 +5694,9 @@ var noopLogger2 = {
3871
5694
  fork: (_label, fn) => fn()
3872
5695
  };
3873
5696
  var syntheticRenderStorage = new AsyncLocalStorage2;
3874
- function useLogger3() {
5697
+ function useLogger2() {
3875
5698
  try {
3876
- return useLogger2();
5699
+ return useLogger();
3877
5700
  } catch {
3878
5701
  return syntheticRenderStorage.getStore() ?? noopLogger2;
3879
5702
  }
@@ -3986,11 +5809,17 @@ var MAX_ISR_CACHE_SIZE = 1000;
3986
5809
  var MAX_SSG_CACHE_SIZE = 1000;
3987
5810
  var isrRouteCache = createRouteCache({
3988
5811
  maxSize: MAX_ISR_CACHE_SIZE,
3989
- name: "render:isr-html"
5812
+ name: "render:isr-html",
5813
+ onDelete: (key) => {
5814
+ autoInvalidateRegistry.unregisterPath(key);
5815
+ }
3990
5816
  });
3991
5817
  var ssgRouteCache = createRouteCache({
3992
5818
  maxSize: MAX_SSG_CACHE_SIZE,
3993
- name: "render:ssg-html"
5819
+ name: "render:ssg-html",
5820
+ onDelete: (key) => {
5821
+ autoInvalidateRegistry.unregisterPath(key);
5822
+ }
3994
5823
  });
3995
5824
  var isrCache = isrRouteCache.store;
3996
5825
  var ssgCache = ssgRouteCache.store;
@@ -4100,16 +5929,42 @@ function errorMessageOf(err) {
4100
5929
  return "";
4101
5930
  }
4102
5931
  var SERVER_RESET_NOOP2 = () => {};
4103
- function buildErrorElement(component, error, digest) {
5932
+ function buildErrorElement(component, error, digest, messageOverride, status) {
4104
5933
  const ErrorView = component ?? DefaultErrorComponent;
4105
- const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
5934
+ let message;
5935
+ if (component) {
5936
+ message = messageOverride ?? errorMessageOf(error);
5937
+ } else {
5938
+ message = "An unexpected error occurred.";
5939
+ }
4106
5940
  return /* @__PURE__ */ jsxDEV4(ErrorView, {
4107
- error: { message, digest },
5941
+ error: { message, digest, status },
4108
5942
  reset: SERVER_RESET_NOOP2
4109
5943
  }, undefined, false, undefined, this);
4110
5944
  }
4111
5945
 
5946
+ // src/client.ts
5947
+ var DEFERRED_BRAND = "__isDeferred";
5948
+ function isDeferred(v) {
5949
+ return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
5950
+ }
5951
+
4112
5952
  // src/render/loaders.ts
5953
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5954
+ function isHttpRedirect(res) {
5955
+ return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
5956
+ }
5957
+ async function readResponseMessage(res) {
5958
+ if (res.body === null) {
5959
+ return res.statusText;
5960
+ }
5961
+ try {
5962
+ const body = await res.text();
5963
+ return body || res.statusText;
5964
+ } catch {
5965
+ return res.statusText;
5966
+ }
5967
+ }
4113
5968
  function createLoaderCtx(ctx, accumulatedParentPromise) {
4114
5969
  const cache = new Map;
4115
5970
  return new Proxy(ctx, {
@@ -4132,9 +5987,44 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
4132
5987
  }
4133
5988
  });
4134
5989
  }
4135
- async function runLoaders(route, ctx, _rootLayout) {
5990
+ function splitOneLoaderResult(result) {
5991
+ const sync = {};
5992
+ const deferred = {};
5993
+ const isDef = isDeferred(result);
5994
+ for (const [key, value] of Object.entries(result)) {
5995
+ if (key === "__isDeferred") {
5996
+ continue;
5997
+ }
5998
+ if (isDef && isPromiseLike(value)) {
5999
+ deferred[key] = Promise.resolve(value);
6000
+ } else {
6001
+ sync[key] = value;
6002
+ }
6003
+ }
6004
+ return { sync, deferred };
6005
+ }
6006
+ function isPromiseLike(value) {
6007
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
6008
+ }
6009
+ function mergeLoaderResults(results) {
6010
+ const allSync = {};
6011
+ const allDeferred = {};
6012
+ for (const result of results) {
6013
+ const { sync, deferred } = splitOneLoaderResult(result);
6014
+ for (const k of Object.keys(sync)) {
6015
+ delete allDeferred[k];
6016
+ }
6017
+ for (const k of Object.keys(deferred)) {
6018
+ delete allSync[k];
6019
+ }
6020
+ Object.assign(allSync, sync);
6021
+ Object.assign(allDeferred, deferred);
6022
+ }
6023
+ return { allSync, allDeferred };
6024
+ }
6025
+ async function runLoaders(route, ctx) {
4136
6026
  try {
4137
- const ctxRecord = { ...ctx, log: useLogger3() };
6027
+ const ctxRecord = { ...ctx, log: useLogger2() };
4138
6028
  const loaderMap = new Map;
4139
6029
  let accumulatedParentPromise = Promise.resolve({});
4140
6030
  for (const r of route.routeChain) {
@@ -4153,22 +6043,39 @@ async function runLoaders(route, ctx, _rootLayout) {
4153
6043
  const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
4154
6044
  const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
4155
6045
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
4156
- const data = Object.assign({}, ...results);
4157
6046
  const headers = {};
4158
6047
  Object.assign(headers, ctx.set.headers);
4159
- return { type: "data", data, headers };
6048
+ const { allSync, allDeferred } = mergeLoaderResults(results);
6049
+ const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
6050
+ return {
6051
+ type: "data",
6052
+ syncData: { ...allSync, ...routeCtx },
6053
+ deferredPromises: Object.keys(allDeferred).length > 0 ? allDeferred : undefined,
6054
+ headers
6055
+ };
4160
6056
  } catch (err) {
6057
+ const headers = {};
6058
+ Object.assign(headers, ctx.set.headers);
4161
6059
  if (isNotFoundError(err)) {
4162
- const headers2 = {};
4163
- Object.assign(headers2, ctx.set.headers);
4164
- return { type: "not-found", error: err, headers: headers2 };
6060
+ return { type: "not-found", error: err, headers };
4165
6061
  }
4166
6062
  if (err instanceof Response) {
4167
- return { type: "redirect", response: err };
6063
+ if (isHttpRedirect(err)) {
6064
+ return { type: "redirect", response: err };
6065
+ }
6066
+ const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
6067
+ const status = isMalformedRedirect ? 500 : err.status;
6068
+ const body = await readResponseMessage(err);
6069
+ const message = body || "Something went wrong";
6070
+ return { type: "error", error: err, status, message, headers };
4168
6071
  }
4169
- const headers = {};
4170
- Object.assign(headers, ctx.set.headers);
4171
- return { type: "error", error: err, headers };
6072
+ return {
6073
+ type: "error",
6074
+ error: err,
6075
+ status: 500,
6076
+ message: "Something went wrong",
6077
+ headers
6078
+ };
4172
6079
  }
4173
6080
  }
4174
6081
 
@@ -4216,9 +6123,14 @@ var IS_DEV = true;
4216
6123
  function withSSRRouterContext(element, contextValue) {
4217
6124
  return createElement3(RouterContext.Provider, { value: contextValue }, element);
4218
6125
  }
6126
+ function assertDeferredModeAllowed(route, deferredPromises) {
6127
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
6128
+ throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
6129
+ }
6130
+ }
4219
6131
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
4220
6132
  const loaderStart = Date.now();
4221
- const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx, root.route);
6133
+ const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
4222
6134
  const loader_ms = Date.now() - loaderStart;
4223
6135
  if (loaderResult.type === "redirect") {
4224
6136
  return loaderResult.response;
@@ -4229,10 +6141,13 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4229
6141
  const isNotFound = loaderResult.type === "not-found";
4230
6142
  const isError = loaderResult.type === "error";
4231
6143
  const isFallback = isNotFound || isError;
4232
- const data = isFallback ? {} : loaderResult.data;
6144
+ const syncData = isFallback ? {} : loaderResult.syncData;
6145
+ const deferredPromises = !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
6146
+ assertDeferredModeAllowed(route, deferredPromises);
4233
6147
  const headers = loaderResult.headers;
4234
6148
  const componentProps = {
4235
- ...data,
6149
+ ...syncData,
6150
+ ...deferredPromises ?? {},
4236
6151
  params: ctx.params,
4237
6152
  query: ctx.query,
4238
6153
  path: ctx.path
@@ -4250,8 +6165,8 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4250
6165
  notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
4251
6166
  } else if (loaderResult.type === "error") {
4252
6167
  errorDigest = computeErrorDigest(loaderResult.error);
4253
- element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
4254
- status = 500;
6168
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest, loaderResult.message, loaderResult.status);
6169
+ status = loaderResult.status;
4255
6170
  } else {
4256
6171
  element = buildElement(route, componentProps, root.route);
4257
6172
  }
@@ -4270,12 +6185,14 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4270
6185
  element = withSSRRouterContext(element, ssrContext);
4271
6186
  return {
4272
6187
  componentProps,
6188
+ deferredPromises,
4273
6189
  element,
4274
6190
  errorDigest,
4275
6191
  headData,
4276
6192
  headers,
4277
6193
  loader_ms,
4278
6194
  notFoundError,
6195
+ syncData,
4279
6196
  ssrContext,
4280
6197
  status,
4281
6198
  template
@@ -4298,7 +6215,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
4298
6215
  if (prepared instanceof Response) {
4299
6216
  return prepared;
4300
6217
  }
4301
- useLogger3().set({
6218
+ useLogger2().set({
4302
6219
  furin: {
4303
6220
  render: mode,
4304
6221
  route: route.pattern,
@@ -4307,17 +6224,27 @@ function renderForPath(route, params, root, origin, mode, basePath) {
4307
6224
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
4308
6225
  }
4309
6226
  });
4310
- const { componentProps, element, headData, headers, status, template } = prepared;
6227
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
4311
6228
  const stream = await renderToReadableStream(element);
4312
6229
  await stream.allReady;
4313
6230
  const reactHtml = await streamToString(stream);
4314
6231
  return {
4315
- html: assembleHTML(template, headData, reactHtml, componentProps),
6232
+ html: assembleHTML(template, headData, reactHtml, syncData),
4316
6233
  headers,
6234
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
4317
6235
  status
4318
6236
  };
4319
6237
  }, { route: route.pattern, render: mode });
4320
6238
  }
6239
+ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
6240
+ const payload = {
6241
+ ...syncData,
6242
+ ...deferredPromises ?? {}
6243
+ };
6244
+ const serialized = await toCrossJSONAsync(payload);
6245
+ return `${JSON.stringify(serialized)}
6246
+ `;
6247
+ }
4321
6248
  async function prerenderSSG(route, params, root, origin, basePath) {
4322
6249
  const resolvedPath = resolvePath(route.pattern, params);
4323
6250
  const cached = getSSGCache(resolvedPath);
@@ -4329,8 +6256,14 @@ async function prerenderSSG(route, params, root, origin, basePath) {
4329
6256
  return renderResult;
4330
6257
  }
4331
6258
  const result = renderResult;
4332
- const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
6259
+ const entry = {
6260
+ cachedAt: Date.now(),
6261
+ html: result.html,
6262
+ ndjson: result.ndjson,
6263
+ status: result.status
6264
+ };
4333
6265
  setSSGCache(resolvedPath, entry);
6266
+ autoInvalidateRegistry.registerLoaderTags(resolvedPath, route.tags);
4334
6267
  return entry;
4335
6268
  }
4336
6269
  var pendingRevalidations = new Set;
@@ -4339,12 +6272,12 @@ var pendingRevalidations = new Set;
4339
6272
  var STATIC_CONCURRENCY = 4;
4340
6273
  var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
4341
6274
  var TRAILING_SLASHES_RE = /\/+$/;
4342
- function pathToOutputFile(urlPath, outDir) {
6275
+ function pathToOutputFile(urlPath, outDir, fileName) {
4343
6276
  const normalizedOutDir = resolve2(outDir);
4344
6277
  if (urlPath === "/" || urlPath === "") {
4345
- return join9(normalizedOutDir, "index.html");
6278
+ return join9(normalizedOutDir, fileName);
4346
6279
  }
4347
- const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
6280
+ const resolved = resolve2(normalizedOutDir, urlPath.slice(1), fileName);
4348
6281
  if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
4349
6282
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
4350
6283
  }
@@ -4352,17 +6285,19 @@ function pathToOutputFile(urlPath, outDir) {
4352
6285
  }
4353
6286
  async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4354
6287
  const urlPath = resolvePath(route.pattern, params);
4355
- const outputFile = pathToOutputFile(urlPath, outDir);
6288
+ const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
6289
+ const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
4356
6290
  try {
4357
6291
  const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
4358
6292
  if (entry instanceof Response) {
4359
6293
  console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
4360
6294
  return;
4361
6295
  }
4362
- ensureDir(dirname3(outputFile));
4363
- writeFileSync7(outputFile, entry.html);
6296
+ ensureDir(dirname3(htmlOutputFile));
6297
+ writeFileSync7(htmlOutputFile, entry.html);
6298
+ writeFileSync7(dataOutputFile, entry.ndjson);
4364
6299
  renderedRoutes.push(urlPath);
4365
- console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
6300
+ console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
4366
6301
  } catch (err) {
4367
6302
  console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
4368
6303
  skippedRoutes.push(urlPath);
@@ -4389,24 +6324,38 @@ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
4389
6324
  }
4390
6325
  async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4391
6326
  const tasks = [];
4392
- for (const route of ssgRoutes) {
6327
+ const staticParamsResults = await mapWithConcurrency(ssgRoutes, STATIC_CONCURRENCY, async (route) => {
4393
6328
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
4394
- tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
4395
- continue;
6329
+ return { route, paramSets: [{}] };
4396
6330
  }
4397
6331
  if (!route.page.staticParams) {
4398
6332
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
4399
6333
  skippedRoutes.push(route.pattern);
4400
- continue;
6334
+ return { route, paramSets: null };
4401
6335
  }
4402
6336
  try {
4403
6337
  const paramSets = await route.page.staticParams() ?? [];
4404
- for (const params of paramSets) {
4405
- tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
4406
- }
6338
+ return { route, paramSets };
4407
6339
  } catch (err) {
4408
- console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
4409
- skippedRoutes.push(route.pattern);
6340
+ return { error: err, paramSets: null, route };
6341
+ }
6342
+ });
6343
+ for (const result of staticParamsResults) {
6344
+ if ("error" in result) {
6345
+ console.error(`[furin] static: staticParams() failed for "${result.route.pattern}":`, result.error);
6346
+ skippedRoutes.push(result.route.pattern);
6347
+ continue;
6348
+ }
6349
+ if (result.paramSets === null) {
6350
+ continue;
6351
+ }
6352
+ if (!Array.isArray(result.paramSets)) {
6353
+ console.error(`[furin] static: staticParams() for "${result.route.pattern}" returned a non-array value; skipping route.`);
6354
+ skippedRoutes.push(result.route.pattern);
6355
+ continue;
6356
+ }
6357
+ for (const params of result.paramSets) {
6358
+ tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
4410
6359
  }
4411
6360
  }
4412
6361
  return tasks;
@@ -4466,7 +6415,7 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4466
6415
  });
4467
6416
  const publicFavicon = join9(rootDir, "public", "favicon.ico");
4468
6417
  const faviconHref = existsSync8(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
4469
- const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
6418
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
4470
6419
  setProductionTemplateContent(shellHtml);
4471
6420
  const publicSrcDir = join9(rootDir, "public");
4472
6421
  if (existsSync8(publicSrcDir)) {
@@ -4532,48 +6481,19 @@ function getCompileContext() {
4532
6481
  return _compileCtx;
4533
6482
  }
4534
6483
 
4535
- // src/utils.ts
4536
- function isFurinPage(value) {
4537
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
4538
- }
4539
- function isFurinRoute(value) {
4540
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
4541
- }
4542
- function collectRouteChainFromRoute(route) {
4543
- const chain = [];
4544
- let current = route;
4545
- while (current) {
4546
- chain.unshift(current);
4547
- current = current.parent;
4548
- }
4549
- return chain;
4550
- }
4551
- function hasCycle(route) {
4552
- const visited = new Set;
4553
- let current = route;
4554
- while (current) {
4555
- if (visited.has(current)) {
4556
- return true;
6484
+ // src/router.ts
6485
+ function collectRouteTags(routeChain, page) {
6486
+ const tags = new Set;
6487
+ for (const route of routeChain) {
6488
+ for (const tag of route.tags ?? []) {
6489
+ tags.add(tag);
4557
6490
  }
4558
- visited.add(current);
4559
- current = current.parent;
4560
- }
4561
- return false;
4562
- }
4563
- function validateRouteChain(chain, root, pagePath) {
4564
- const hasRoot = chain.some((r) => r === root);
4565
- if (!hasRoot) {
4566
- const location = pagePath ? `in ${pagePath}` : "";
4567
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
4568
6491
  }
4569
- for (const route of chain) {
4570
- if (hasCycle(route)) {
4571
- throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
4572
- }
6492
+ for (const tag of page?.tags ?? []) {
6493
+ tags.add(tag);
4573
6494
  }
6495
+ return tags.size > 0 ? [...tags] : undefined;
4574
6496
  }
4575
-
4576
- // src/router.ts
4577
6497
  async function scanPages(pagesDir) {
4578
6498
  const root = await scanRootLayout(pagesDir);
4579
6499
  const routes = await scanPageFiles(pagesDir, root);
@@ -4593,8 +6513,10 @@ async function scanRootLayout(pagesDir) {
4593
6513
  if (!rootExport.layout) {
4594
6514
  throw new Error("[furin] root.tsx: createRoute() has no layout.");
4595
6515
  }
4596
- const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
4597
- const errorEntry = await loadConventionComponent(pagesDir, "error");
6516
+ const [notFoundEntry, errorEntry] = await Promise.all([
6517
+ loadConventionComponent(pagesDir, "not-found"),
6518
+ loadConventionComponent(pagesDir, "error")
6519
+ ]);
4598
6520
  return {
4599
6521
  path: rootPath,
4600
6522
  route: rootExport,
@@ -4637,9 +6559,11 @@ async function scanPageFiles(pagesDir, root) {
4637
6559
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
4638
6560
  continue;
4639
6561
  }
4640
- const notFound = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
4641
- const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
4642
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
6562
+ const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
6563
+ resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
6564
+ resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
6565
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
6566
+ ]);
4643
6567
  if (IS_DEV) {
4644
6568
  const devRoute = await buildDevRoute(absolutePath, relativePath, root);
4645
6569
  devRoute.notFound = notFound;
@@ -4664,7 +6588,8 @@ async function scanPageFiles(pagesDir, root) {
4664
6588
  mode: resolveMode(page, routeChain),
4665
6589
  notFound,
4666
6590
  error: errorComponent,
4667
- segmentBoundaries
6591
+ segmentBoundaries,
6592
+ tags: collectRouteTags(routeChain, page)
4668
6593
  });
4669
6594
  }
4670
6595
  return routes;
@@ -4684,14 +6609,16 @@ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCach
4684
6609
  const boundaries = [];
4685
6610
  for (let depth = 0;depth < dirs.length; depth++) {
4686
6611
  const dir = dirs[depth];
4687
- if (!errorCache.has(dir)) {
4688
- errorCache.set(dir, await loadConventionComponent(dir, "error"));
4689
- }
4690
- if (!notFoundCache.has(dir)) {
4691
- notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
4692
- }
4693
- const errorEntry = errorCache.get(dir);
4694
- const notFoundEntry = notFoundCache.get(dir);
6612
+ const [errorEntry, notFoundEntry] = await Promise.all([
6613
+ errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
6614
+ errorCache.set(dir, r);
6615
+ return r;
6616
+ }),
6617
+ notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
6618
+ notFoundCache.set(dir, r);
6619
+ return r;
6620
+ })
6621
+ ]);
4695
6622
  if (errorEntry || notFoundEntry) {
4696
6623
  boundaries.push({
4697
6624
  path: dir,
@@ -4744,22 +6671,27 @@ async function buildDevRoute(absolutePath, relativePath, root) {
4744
6671
  mode: page ? resolveMode(page, routeChain) : "ssr",
4745
6672
  page: page ?? devStubPage,
4746
6673
  routeChain,
6674
+ tags: collectRouteTags(routeChain, page),
4747
6675
  segmentBoundaries: []
4748
6676
  };
4749
6677
  }
4750
6678
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
6679
+ var DIR_SCAN_CONCURRENCY = 8;
4751
6680
  async function collectPageFilePaths(dir) {
4752
6681
  const files = [];
4753
6682
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
4754
- for (const entry of entries) {
6683
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
4755
6684
  const absolutePath = join10(dir, entry.name);
4756
6685
  if (entry.isDirectory()) {
4757
- files.push(...await collectPageFilePaths(absolutePath));
4758
- continue;
6686
+ return await collectPageFilePaths(absolutePath);
4759
6687
  }
4760
6688
  if (entry.isFile()) {
4761
- files.push(absolutePath);
6689
+ return [absolutePath];
4762
6690
  }
6691
+ return [];
6692
+ });
6693
+ for (const chunk of resolved) {
6694
+ files.push(...chunk);
4763
6695
  }
4764
6696
  return files;
4765
6697
  }
@@ -4804,35 +6736,13 @@ function filePathToPattern(path) {
4804
6736
  // src/build/scan-server.ts
4805
6737
  import { readFileSync as readFileSync4 } from "fs";
4806
6738
  import { parse as parse3 } from "yuku-parser";
4807
- function detectLangFromPath(filePath) {
4808
- if (filePath.endsWith(".d.ts")) {
4809
- return "dts";
4810
- }
4811
- const ext = filePath.split(".").pop()?.toLowerCase();
4812
- switch (ext) {
4813
- case "ts":
4814
- return "ts";
4815
- case "tsx":
4816
- return "tsx";
4817
- case "jsx":
4818
- return "jsx";
4819
- default:
4820
- return "js";
4821
- }
4822
- }
4823
6739
  function scanFurinInstances(serverEntryPath) {
4824
6740
  const code = readFileSync4(serverEntryPath, "utf8");
4825
- let lang = detectLangFromPath(serverEntryPath);
6741
+ const lang = detectLangFromPath(serverEntryPath);
4826
6742
  if (lang === "dts") {
4827
6743
  return [];
4828
6744
  }
4829
- let parseInput = code;
4830
- if (lang === "ts" || lang === "tsx") {
4831
- const transpiler = new Bun.Transpiler({ loader: lang });
4832
- parseInput = transpiler.transformSync(code);
4833
- lang = "js";
4834
- }
4835
- const { program, diagnostics } = parse3(parseInput, { sourceType: "module", lang });
6745
+ const { program, diagnostics } = parse3(code, { sourceType: "module", lang });
4836
6746
  const firstError = diagnostics.find((d) => d.severity === "error");
4837
6747
  if (firstError) {
4838
6748
  console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
@@ -4850,7 +6760,7 @@ function checkFurinCall(node, out) {
4850
6760
  if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
4851
6761
  return;
4852
6762
  }
4853
- const firstArg = args[0];
6763
+ const firstArg = unwrapTSExpression(args[0]);
4854
6764
  if (firstArg?.type !== "ObjectExpression") {
4855
6765
  return;
4856
6766
  }