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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/build/entry-template.ts +3 -1
  2. package/dist/build/index.js +360 -219
  3. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  4. package/dist/build/types.d.ts +2 -0
  5. package/dist/cli/index.js +363 -221
  6. package/dist/client/document.d.ts +2 -0
  7. package/dist/client/link.js +11 -0
  8. package/dist/client.js +11 -0
  9. package/dist/config.d.ts +7 -2
  10. package/dist/config.js +24 -1
  11. package/dist/furin.js +217 -82
  12. package/dist/rsc-client.js +9 -1
  13. package/dist/rsc.js +19 -7
  14. package/dist/server/browser-events/shutdown.d.ts +3 -0
  15. package/dist/server/cache/redis/index.d.ts +2 -0
  16. package/dist/server/cache/redis/index.js +67 -12
  17. package/dist/server/cache/redis/scripts.d.ts +5 -5
  18. package/dist/server/dev/plugin.d.ts +1 -0
  19. package/dist/server/evlog.d.ts +1 -1
  20. package/dist/server/internal.js +3 -1
  21. package/dist/server/production-server.d.ts +13 -0
  22. package/dist/server/production-server.js +2906 -0
  23. package/dist/server/router/hmr.d.ts +6 -0
  24. package/dist/server/router/hmr.production.d.ts +5 -0
  25. package/dist/server/router/plugin.d.ts +5 -1
  26. package/dist/server/sync/index.js +5 -2
  27. package/dist/server/sync/stream.d.ts +4 -0
  28. package/dist/shared/production-build.d.ts +2 -0
  29. package/package.json +8 -3
  30. package/src/adapter/bun.ts +74 -15
  31. package/src/adapter/vercel.ts +15 -1
  32. package/src/build/elysia-aot.ts +1 -1
  33. package/src/build/entry-template.ts +3 -1
  34. package/src/build/hydrate.ts +5 -1
  35. package/src/build/index.ts +5 -0
  36. package/src/build/private-server-sourcemaps.ts +20 -0
  37. package/src/build/server-app-entry.ts +3 -2
  38. package/src/build/types.ts +2 -0
  39. package/src/cli/index.ts +1 -0
  40. package/src/client/document.tsx +19 -0
  41. package/src/config.ts +30 -2
  42. package/src/furin.ts +37 -12
  43. package/src/rsc/codec.ts +11 -6
  44. package/src/rsc/render-error.ts +3 -1
  45. package/src/server/browser-events/plugin.ts +7 -0
  46. package/src/server/browser-events/shutdown.ts +32 -0
  47. package/src/server/cache/redis/index.ts +19 -2
  48. package/src/server/cache/redis/scripts.ts +47 -7
  49. package/src/server/dev/plugin.ts +10 -1
  50. package/src/server/evlog.ts +11 -4
  51. package/src/server/production-server.ts +135 -0
  52. package/src/server/render/document.tsx +7 -1
  53. package/src/server/render/ssr.ts +2 -1
  54. package/src/server/render/template.ts +5 -1
  55. package/src/server/router/discovery.ts +3 -1
  56. package/src/server/router/hmr.production.ts +11 -0
  57. package/src/server/router/hmr.ts +84 -77
  58. package/src/server/router/plugin.ts +76 -17
  59. package/src/server/router/schema-merge.ts +9 -2
  60. package/src/server/sync/stream.ts +43 -2
  61. package/src/shared/production-build.ts +20 -0
package/dist/cli/index.js CHANGED
@@ -2833,7 +2833,7 @@ var init_toolkit = __esm(() => {
2833
2833
 
2834
2834
  // src/server/evlog.ts
2835
2835
  import { Elysia as Elysia2 } from "elysia";
2836
- var loggerStorage, integration, getRequestLogger;
2836
+ var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2837
2837
  var init_evlog = __esm(() => {
2838
2838
  init_toolkit();
2839
2839
  loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
@@ -2854,6 +2854,7 @@ var init_evlog = __esm(() => {
2854
2854
  storage: loggerStorage.storage
2855
2855
  });
2856
2856
  getRequestLogger = loggerStorage.useLogger;
2857
+ runtimeWaitUntil = new Set;
2857
2858
  });
2858
2859
 
2859
2860
  // src/server/context-logger.ts
@@ -2900,7 +2901,7 @@ var IS_DEV = true;
2900
2901
  // src/server/dev/graph.ts
2901
2902
  import { randomUUID } from "crypto";
2902
2903
  import { readFileSync as readFileSync2, statSync as statSync2 } from "fs";
2903
- import { dirname as dirname6, extname as extname2 } from "path";
2904
+ import { dirname as dirname7, extname as extname2 } from "path";
2904
2905
  function normalizeModulePath(path) {
2905
2906
  return path.replaceAll("\\", "/");
2906
2907
  }
@@ -2909,7 +2910,7 @@ function resolveDevSourceImports(source, path, loader) {
2909
2910
  const transpiler = new Bun.Transpiler({ loader });
2910
2911
  for (const imported of transpiler.scanImports(source)) {
2911
2912
  try {
2912
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname6(path)));
2913
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname7(path)));
2913
2914
  if (!resolved.includes("/node_modules/")) {
2914
2915
  imports.push(resolved);
2915
2916
  }
@@ -3384,20 +3385,28 @@ function injectDevDiagnosticClient(html, basePath) {
3384
3385
  }
3385
3386
  return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
3386
3387
  }
3388
+ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection", (event) => {
3389
+ const stack = event.reason?.stack;
3390
+ if (typeof stack !== "string") return;
3391
+ const firstFrame = stack.match(/^(?:\\s*at [^\\n]*|[^\\n]*@[^\\n]*)/m)?.[0];
3392
+ if (firstFrame && /\\b(?:chrome|moz)-extension:\\/\\//.test(firstFrame)) {
3393
+ event.stopImmediatePropagation();
3394
+ }
3395
+ }, true);`;
3387
3396
  var init_plugin2 = () => {};
3388
3397
 
3389
3398
  // src/cli/index.ts
3390
- import { existsSync as existsSync15 } from "fs";
3399
+ import { existsSync as existsSync16 } from "fs";
3391
3400
  import { resolve as resolve12 } from "path";
3392
3401
  import { parseArgs } from "util";
3393
3402
 
3394
3403
  // src/build/index.ts
3395
- import { existsSync as existsSync12, writeFileSync as writeFileSync8 } from "fs";
3396
- import { join as join14, relative as relative9, resolve as resolve9 } from "path";
3404
+ import { existsSync as existsSync13, writeFileSync as writeFileSync9 } from "fs";
3405
+ import { join as join15, relative as relative10, resolve as resolve9 } from "path";
3397
3406
 
3398
3407
  // src/adapter/bun.ts
3399
- import { existsSync as existsSync7, readFileSync as readFileSync4, rmSync as rmSync2 } from "fs";
3400
- import { join as join9, resolve as resolve6 } from "path";
3408
+ import { existsSync as existsSync8, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
3409
+ import { join as join10, resolve as resolve6 } from "path";
3401
3410
 
3402
3411
  // src/build/bun-build.ts
3403
3412
  function runBunBuild(config) {
@@ -3515,7 +3524,7 @@ function buildEntrySource(options) {
3515
3524
  "",
3516
3525
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3517
3526
  "__setDevMode(false);",
3518
- 'process.env.NODE_ENV = "production";'
3527
+ ...mode === "boot" ? ['process.env.NODE_ENV = "production";'] : []
3519
3528
  ] : [],
3520
3529
  ...contextBlocks,
3521
3530
  "",
@@ -3541,7 +3550,9 @@ function buildEntrySource(options) {
3541
3550
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3542
3551
  "export const app = __serverModule.default;",
3543
3552
  "export const port = __serverModule.port;",
3553
+ "export const idleTimeout = __serverModule.idleTimeout;",
3544
3554
  "export const startServer = __serverModule.startServer;",
3555
+ "export const onShutdown = __serverModule.onShutdown;",
3545
3556
  "export default __serverModule.default;",
3546
3557
  ""
3547
3558
  ] : []
@@ -3674,7 +3685,7 @@ export function handleWSResponse(){return e()}
3674
3685
  }
3675
3686
  function elysiaAot(entry) {
3676
3687
  const entryPath = resolve(entry);
3677
- const hooks = aotFactory({ entry, strip: "auto", target: "bun" });
3688
+ const hooks = aotFactory({ entry, strip: false, target: "bun" });
3678
3689
  return {
3679
3690
  name: "elysia-aot",
3680
3691
  async setup(build) {
@@ -3727,8 +3738,23 @@ function elysiaAot(entry) {
3727
3738
  };
3728
3739
  }
3729
3740
 
3741
+ // src/build/private-server-sourcemaps.ts
3742
+ import { existsSync as existsSync4, renameSync } from "fs";
3743
+ import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
3744
+ function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
3745
+ for (const filename of filenames) {
3746
+ const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
3747
+ if (!existsSync4(source)) {
3748
+ continue;
3749
+ }
3750
+ const destination = join4(privateDir, relative2(outputDir, source));
3751
+ ensureDir(dirname3(destination));
3752
+ renameSync(source, destination);
3753
+ }
3754
+ }
3755
+
3730
3756
  // src/build/production-instrumentation.ts
3731
- import { dirname as dirname3, relative as relative2, resolve as resolve2 } from "path";
3757
+ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from "path";
3732
3758
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3733
3759
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3734
3760
  var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
@@ -3738,7 +3764,7 @@ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plu
3738
3764
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3739
3765
  var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3740
3766
  function isFurinRuntimePath(path) {
3741
- const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3767
+ const fromRuntimeRoot = relative3(FURIN_RUNTIME_ROOT, path);
3742
3768
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
3743
3769
  }
3744
3770
  function devBuildExport(path) {
@@ -3749,7 +3775,7 @@ function productionInstrumentationPlugin() {
3749
3775
  name: "furin-production-instrumentation",
3750
3776
  setup(build) {
3751
3777
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3752
- const importPath = resolve2(dirname3(args.importer), args.path);
3778
+ const importPath = resolve2(dirname4(args.importer), args.path);
3753
3779
  if (!isFurinRuntimePath(importPath)) {
3754
3780
  return;
3755
3781
  }
@@ -3783,18 +3809,18 @@ function productionInstrumentationPlugin() {
3783
3809
 
3784
3810
  // src/build/server-app-entry.ts
3785
3811
  import { writeFileSync } from "fs";
3786
- import { join as join5 } from "path";
3812
+ import { join as join6 } from "path";
3787
3813
 
3788
3814
  // src/plugin/routes.ts
3789
3815
  import {
3790
- existsSync as existsSync4,
3816
+ existsSync as existsSync5,
3791
3817
  readdirSync as readdirSync2,
3792
3818
  readFileSync,
3793
3819
  realpathSync,
3794
3820
  statSync,
3795
3821
  watch
3796
3822
  } from "fs";
3797
- import { dirname as dirname4, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve3, sep } from "path";
3823
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve3, sep } from "path";
3798
3824
  import { pathToFileURL } from "url";
3799
3825
  import { Elysia } from "elysia";
3800
3826
 
@@ -3949,8 +3975,8 @@ function findSearchDefaultsForRouteTarget(to, routes) {
3949
3975
  init_patterns();
3950
3976
 
3951
3977
  // src/server/router/schema-merge.ts
3952
- import { t } from "elysia";
3953
3978
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3979
+ var TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
3954
3980
  function mergeRouteSchemas(routeChain, key) {
3955
3981
  const schemas = routeChain.flatMap((route) => route[key] ? [route[key]] : []);
3956
3982
  if (schemas.length === 0) {
@@ -3964,7 +3990,13 @@ function mergeRouteSchemas(routeChain, key) {
3964
3990
  }
3965
3991
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3966
3992
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
3967
- return t.Object(properties, options);
3993
+ const required = Object.keys(properties).filter((name) => {
3994
+ const property = properties[name];
3995
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
3996
+ });
3997
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
3998
+ value: "Object"
3999
+ });
3968
4000
  }
3969
4001
 
3970
4002
  // src/server/router/schemas.ts
@@ -4056,7 +4088,7 @@ function scanRouteFiles(directory, directorySegments, files) {
4056
4088
  if (entry.name.startsWith("_")) {
4057
4089
  continue;
4058
4090
  }
4059
- scanRouteFiles(join4(directory, entry.name), [...directorySegments, entry.name], files);
4091
+ scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
4060
4092
  continue;
4061
4093
  }
4062
4094
  const extension = extname(entry.name);
@@ -4064,7 +4096,7 @@ function scanRouteFiles(directory, directorySegments, files) {
4064
4096
  continue;
4065
4097
  }
4066
4098
  const base = entry.name.slice(0, -extension.length);
4067
- const sourcePath = join4(directory, entry.name);
4099
+ const sourcePath = join5(directory, entry.name);
4068
4100
  for (const segment of [...directorySegments, base]) {
4069
4101
  parseDynamicRouteSegment(segment, sourcePath);
4070
4102
  }
@@ -4263,19 +4295,19 @@ function routeModuleCache() {
4263
4295
  return cache;
4264
4296
  }
4265
4297
  function findPackageRoot(sourcePath) {
4266
- const fallback = dirname4(sourcePath);
4298
+ const fallback = dirname5(sourcePath);
4267
4299
  let directory = fallback;
4268
- while (dirname4(directory) !== directory) {
4269
- if (existsSync4(join4(directory, "package.json"))) {
4300
+ while (dirname5(directory) !== directory) {
4301
+ if (existsSync5(join5(directory, "package.json"))) {
4270
4302
  return directory;
4271
4303
  }
4272
- directory = dirname4(directory);
4304
+ directory = dirname5(directory);
4273
4305
  }
4274
- return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4306
+ return existsSync5(join5(directory, "package.json")) ? directory : fallback;
4275
4307
  }
4276
4308
  function isWithinDirectory(path, directory) {
4277
- const relativePath = relative3(directory, path);
4278
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute(relativePath));
4309
+ const relativePath = relative4(directory, path);
4310
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
4279
4311
  }
4280
4312
  function isFurinPackageImport(specifier) {
4281
4313
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -4292,8 +4324,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4292
4324
  continue;
4293
4325
  }
4294
4326
  try {
4295
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname4(dependencyPath)));
4296
- if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4327
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname5(dependencyPath)));
4328
+ if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4297
4329
  resolvedImports.push(resolvedImport);
4298
4330
  }
4299
4331
  } catch {}
@@ -4391,8 +4423,8 @@ function serverProxySource(instance, includeRootCatchAll) {
4391
4423
  function createRoutesPlugin(options) {
4392
4424
  const routeFilesBySpecifier = new Map;
4393
4425
  const routeFilesByResolvedPath = new Map;
4394
- const registryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4395
- const composableRegistryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4426
+ const registryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4427
+ const composableRegistryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4396
4428
  const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4397
4429
  [
4398
4430
  routeModuleSpecifier(instance),
@@ -4452,7 +4484,7 @@ function createRoutesPlugin(options) {
4452
4484
  return {
4453
4485
  contents: await Bun.file(routeFile.sourcePath).text(),
4454
4486
  loader: detectLoaderFromPath(routeFile.sourcePath),
4455
- resolveDir: dirname4(routeFile.sourcePath)
4487
+ resolveDir: dirname5(routeFile.sourcePath)
4456
4488
  };
4457
4489
  });
4458
4490
  for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
@@ -4473,11 +4505,11 @@ async function materializeServerAppEntry(options) {
4473
4505
  if (!instance) {
4474
4506
  throw new Error(`[furin] Missing route instance for server app ${index}.`);
4475
4507
  }
4476
- const routePath = join5(options.outDir, `_furin-routes-${index}.ts`);
4508
+ const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
4477
4509
  writeFileSync(routePath, await materializedRouteModuleSource(instance));
4478
4510
  return { ...app, nativeRoutes: toPosixPath(routePath) };
4479
4511
  }));
4480
- const entryPath = join5(options.outDir, "_furin-app.ts");
4512
+ const entryPath = join6(options.outDir, "_furin-app.ts");
4481
4513
  writeFileSync(entryPath, buildEntrySource({
4482
4514
  apps,
4483
4515
  headerComment: options.headerComment,
@@ -4488,7 +4520,8 @@ async function materializeServerAppEntry(options) {
4488
4520
  }
4489
4521
  function serverBootSource(appEntry) {
4490
4522
  return `// Auto-generated by furin build - do not edit
4491
- import app, { port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4523
+ import { startProductionServer } from "@teyik0/furin/production-server";
4524
+ import app, { idleTimeout, onShutdown, port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4492
4525
 
4493
4526
  if (typeof startServer === "function") {
4494
4527
  await startServer();
@@ -4496,7 +4529,7 @@ if (typeof startServer === "function") {
4496
4529
  const serverPort = process.env.PORT === undefined
4497
4530
  ? typeof port === "number" ? port : 3000
4498
4531
  : Number(process.env.PORT);
4499
- app.listen(serverPort);
4532
+ startProductionServer({ app, idleTimeout, onShutdown, port: serverPort });
4500
4533
  console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4501
4534
  }
4502
4535
  `;
@@ -6957,13 +6990,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6957
6990
  }
6958
6991
 
6959
6992
  // src/adapter/runtime-build.ts
6960
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
6961
- import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute2, join as join8, relative as relative5, resolve as resolve5 } from "path";
6993
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
6994
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join9, relative as relative6, resolve as resolve5 } from "path";
6962
6995
  import { fileURLToPath as fileURLToPath5 } from "url";
6963
6996
 
6964
6997
  // src/build/client.ts
6965
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6966
- import { basename as basename2, dirname as dirname5, join as join6, resolve as resolve4 } from "path";
6998
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6999
+ import { basename as basename2, dirname as dirname6, join as join7, resolve as resolve4 } from "path";
6967
7000
 
6968
7001
  // src/plugin/transform-client.ts
6969
7002
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7784,6 +7817,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
7784
7817
  // a matched loader threw notFound(). The latter still has a _match; the
7785
7818
  // former does not \u2014 so the two cases fork on _match below.
7786
7819
  const dataEl = document.getElementById("__FURIN_DATA__");
7820
+ const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7787
7821
  let loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
7788
7822
  const syncEl = document.getElementById("__FURIN_SYNC__");
7789
7823
  const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
@@ -7800,6 +7834,7 @@ const documentState: DocumentState = {
7800
7834
  assets: {
7801
7835
  buildId,
7802
7836
  entryModule: entryEl?.getAttribute("src") ?? undefined,
7837
+ extensionErrorFilterScript: document.querySelector("[data-furin-extension-error-filter]")?.textContent ?? undefined,
7803
7838
  faviconHref,
7804
7839
  frameworkModules,
7805
7840
  staticMode: document.querySelector('meta[name="furin-mode"][content="static"]') !== null,
@@ -7809,6 +7844,9 @@ const documentState: DocumentState = {
7809
7844
  },
7810
7845
  dataJson: dataEl?.textContent ?? undefined,
7811
7846
  head,
7847
+ routeFrames: frameTemplate?.hasAttribute("data-furin-document-state")
7848
+ ? (frameTemplate.content.textContent ?? "")
7849
+ : undefined,
7812
7850
  syncJson: syncEl?.textContent ?? undefined,
7813
7851
  };
7814
7852
 
@@ -7883,7 +7921,6 @@ if (__deferred && __deferred._chunks) {
7883
7921
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
7884
7922
  // bundler to misidentify which chunk to reference as the entry in index.html.
7885
7923
  (async () => {
7886
- const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7887
7924
  if (frameTemplate) {
7888
7925
  const payload = frameTemplate.content.textContent || "";
7889
7926
  const routeFrameStream = (window as unknown as { __FURIN_ROUTE_FRAME_STREAM__?: FurinRouteFrameStream })
@@ -8031,15 +8068,15 @@ async function buildClient(routes, {
8031
8068
  pagesDir
8032
8069
  }) {
8033
8070
  const dirName = clientDirName ?? "client";
8034
- const clientDir = join6(outDir, dirName);
8035
- if (!existsSync5(outDir)) {
8071
+ const clientDir = join7(outDir, dirName);
8072
+ if (!existsSync6(outDir)) {
8036
8073
  mkdirSync2(outDir, { recursive: true });
8037
8074
  }
8038
- if (!existsSync5(clientDir)) {
8075
+ if (!existsSync6(clientDir)) {
8039
8076
  mkdirSync2(clientDir, { recursive: true });
8040
8077
  }
8041
8078
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
8042
- const hydratePath = join6(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8079
+ const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8043
8080
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8044
8081
  console.log("[furin] Building production client bundle\u2026");
8045
8082
  const transformPlugin = {
@@ -8114,7 +8151,7 @@ async function buildClient(routes, {
8114
8151
  if (result.metafile === undefined) {
8115
8152
  throw new Error("[furin] client build did not produce the requested metafile");
8116
8153
  }
8117
- mkdirSync2(dirname5(metafilePath), { recursive: true });
8154
+ mkdirSync2(dirname6(metafilePath), { recursive: true });
8118
8155
  writeFileSync2(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8119
8156
  `);
8120
8157
  console.log(`[furin] Client metafile: ${metafilePath}`);
@@ -9963,6 +10000,10 @@ function HeadContent() {
9963
10000
  }
9964
10001
  return /* @__PURE__ */ jsxDEV(Fragment, {
9965
10002
  children: [
10003
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
10004
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
10005
+ "data-furin-extension-error-filter": ""
10006
+ }, undefined, false, undefined, this),
9966
10007
  /* @__PURE__ */ jsxDEV("meta", {
9967
10008
  charSet: "utf-8",
9968
10009
  "data-furin-head": ""
@@ -10020,6 +10061,13 @@ function Scripts() {
10020
10061
  id: "__FURIN_DATA__",
10021
10062
  type: "application/json"
10022
10063
  }, undefined, false, undefined, this),
10064
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
10065
+ dangerouslySetInnerHTML: {
10066
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
10067
+ },
10068
+ "data-furin-document-state": "",
10069
+ id: "__FURIN_ROUTE_FRAMES__"
10070
+ }, undefined, false, undefined, this),
10023
10071
  /* @__PURE__ */ jsxDEV("script", {
10024
10072
  dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
10025
10073
  "data-furin-scripts": "",
@@ -10300,6 +10348,21 @@ function cyrb53(input) {
10300
10348
  return 4294967296 * (2097151 & h2) + (4294967295 & h1);
10301
10349
  }
10302
10350
 
10351
+ // src/shared/production-build.ts
10352
+ var productionBuildScope;
10353
+ var productionBuildScopePromise;
10354
+ async function withProductionBuild(build) {
10355
+ productionBuildScopePromise ??= import("async_hooks").then(({ AsyncLocalStorage }) => {
10356
+ productionBuildScope = new AsyncLocalStorage;
10357
+ return productionBuildScope;
10358
+ });
10359
+ const scope = await productionBuildScopePromise;
10360
+ return scope.run(true, build);
10361
+ }
10362
+ function isProductionBuild() {
10363
+ return productionBuildScope?.getStore() === true || typeof process !== "undefined" && false;
10364
+ }
10365
+
10303
10366
  // src/rsc/shared.tsx
10304
10367
  import {
10305
10368
  Children,
@@ -10475,10 +10538,12 @@ function withDocumentState(element, assets, head, data) {
10475
10538
  ...assets,
10476
10539
  frameworkModules: [browserEventsClientPath, ...assets.frameworkModules]
10477
10540
  };
10541
+ const routeFrames = data !== undefined && containsRscSource(data) ? serializeRouteFrames(data, undefined) : undefined;
10478
10542
  const state = {
10479
10543
  assets: resolvedAssets,
10480
- dataJson: data === undefined ? undefined : safeJson(data),
10544
+ dataJson: data === undefined || routeFrames !== undefined ? undefined : safeJson(data),
10481
10545
  head,
10546
+ routeFrames,
10482
10547
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
10483
10548
  };
10484
10549
  return createElement3(DocumentProvider, { value: state }, element);
@@ -11234,7 +11299,9 @@ function errorStack(error) {
11234
11299
  return error instanceof Error ? error.stack : undefined;
11235
11300
  }
11236
11301
  function renderErrorMessage(options) {
11237
- if (typeof process !== "undefined" && false) {}
11302
+ if (isProductionBuild()) {
11303
+ return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
11304
+ }
11238
11305
  if (options.hook !== undefined && options.component !== undefined) {
11239
11306
  const diagnostic = `[furin/rsc] A component rendered inside ${options.operation}()
11240
11307
  used a client-only React hook.
@@ -11764,7 +11831,11 @@ async function getDevDocumentAssets(origin) {
11764
11831
  if (state.devAssets && Date.now() - state.devAssets.ts < DEV_TEMPLATE_TTL_MS) {
11765
11832
  return state.devAssets.assets;
11766
11833
  }
11767
- const assets = documentAssetsFromTemplate(await getDevTemplate(origin));
11834
+ await Promise.resolve().then(() => init_plugin2());
11835
+ const assets = {
11836
+ ...documentAssetsFromTemplate(await getDevTemplate(origin)),
11837
+ extensionErrorFilterScript
11838
+ };
11768
11839
  state.devAssets = { assets, ts: Date.now() };
11769
11840
  return assets;
11770
11841
  }
@@ -12081,7 +12152,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
12081
12152
  }
12082
12153
 
12083
12154
  // src/server/render/static-params.ts
12084
- import { dirname as dirname7, relative as relative4 } from "path";
12155
+ import { dirname as dirname8, relative as relative5 } from "path";
12085
12156
  init_patterns();
12086
12157
  var STATIC_PARAMS_CONCURRENCY = 4;
12087
12158
  function collectStaticParamsStages(route) {
@@ -12102,12 +12173,12 @@ function ancestorPattern(route, ancestors) {
12102
12173
  if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12103
12174
  return route.pattern;
12104
12175
  }
12105
- const pagesDir = dirname7(rootSourcePath);
12106
- const ancestorDir = dirname7(ancestorSourcePath);
12176
+ const pagesDir = dirname8(rootSourcePath);
12177
+ const ancestorDir = dirname8(ancestorSourcePath);
12107
12178
  if (ancestorDir === pagesDir) {
12108
12179
  return "/";
12109
12180
  }
12110
- return filePathToPattern(`${relative4(pagesDir, ancestorDir)}/index.tsx`);
12181
+ return filePathToPattern(`${relative5(pagesDir, ancestorDir)}/index.tsx`);
12111
12182
  }
12112
12183
  function createBuildContext(pattern, params, origin) {
12113
12184
  const path = resolvePath(pattern, params);
@@ -12284,7 +12355,7 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12284
12355
 
12285
12356
  // src/rsc/build/index.ts
12286
12357
  import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
12287
- import { basename as basename3, join as join7 } from "path";
12358
+ import { basename as basename3, join as join8 } from "path";
12288
12359
  import { fileURLToPath as fileURLToPath4 } from "url";
12289
12360
 
12290
12361
  // src/rsc/version.ts
@@ -12332,7 +12403,7 @@ function assertInstalledRscVersions() {
12332
12403
  // src/rsc/build/index.ts
12333
12404
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12334
12405
  await assertInstalledRscVersions();
12335
- const graphDir = join7(outDir, "rsc");
12406
+ const graphDir = join8(outDir, "rsc");
12336
12407
  mkdirSync3(graphDir, { recursive: true });
12337
12408
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12338
12409
  const entrypoints = [
@@ -12394,13 +12465,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12394
12465
  }
12395
12466
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12396
12467
  const manifest = { buildId, clientReferences: [], css };
12397
- writeFileSync3(join7(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12468
+ writeFileSync3(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12398
12469
  return manifest;
12399
12470
  }
12400
12471
 
12401
12472
  // src/adapter/runtime-build.ts
12402
- var _pkgRoot2 = dirname8(dirname8(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12403
- var _pkgSrcDir2 = existsSync6(join8(_pkgRoot2, "src", "furin.ts")) ? join8(_pkgRoot2, "src") : join8(_pkgRoot2, "dist");
12473
+ var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12474
+ var _pkgSrcDir2 = existsSync7(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
12404
12475
  var _ext2 = ".ts";
12405
12476
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12406
12477
  var ANY_MODULE_RE = /.*/;
@@ -12460,13 +12531,13 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12460
12531
  }
12461
12532
  }
12462
12533
  for (const path of BUILD_ID_INPUT_PATHS) {
12463
- if (!existsSync6(path)) {
12534
+ if (!existsSync7(path)) {
12464
12535
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
12465
12536
  }
12466
12537
  fingerprintPaths.add(path);
12467
12538
  }
12468
12539
  const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
12469
- const content = existsSync6(path) ? await Bun.file(path).text() : "";
12540
+ const content = existsSync7(path) ? await Bun.file(path).text() : "";
12470
12541
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
12471
12542
  }));
12472
12543
  const routeParts = routes.map((route) => JSON.stringify({
@@ -12478,12 +12549,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12478
12549
  `);
12479
12550
  }
12480
12551
  function stableFingerprintPath(path, projectRoot) {
12481
- const projectPath = relative5(projectRoot, path);
12482
- if (!isAbsolute2(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12552
+ const projectPath = relative6(projectRoot, path);
12553
+ if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12483
12554
  return `app/${toPosixPath(projectPath)}`;
12484
12555
  }
12485
- const frameworkPath = relative5(_pkgRoot2, path);
12486
- if (!isAbsolute2(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12556
+ const frameworkPath = relative6(_pkgRoot2, path);
12557
+ if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12487
12558
  return `furin/${toPosixPath(frameworkPath)}`;
12488
12559
  }
12489
12560
  return `external/${basename4(path)}`;
@@ -12520,7 +12591,7 @@ function pprRuntimePlugin(apps) {
12520
12591
  return;
12521
12592
  }
12522
12593
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12523
- const absolute = resolve5(dirname8(importer.split("?")[0]), path);
12594
+ const absolute = resolve5(dirname9(importer.split("?")[0]), path);
12524
12595
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12525
12596
  return;
12526
12597
  }
@@ -12540,7 +12611,7 @@ function isFrameworkRuntimeImporter(importer) {
12540
12611
  if (importer === "") {
12541
12612
  return false;
12542
12613
  }
12543
- const fromRuntimeRoot = relative5(_pkgSrcDir2, importer.split("?")[0]);
12614
+ const fromRuntimeRoot = relative6(_pkgSrcDir2, importer.split("?")[0]);
12544
12615
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12545
12616
  }
12546
12617
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12552,7 +12623,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12552
12623
  basePath: prefix,
12553
12624
  clientDirName,
12554
12625
  clientLogging: options.clientLogging ?? false,
12555
- metafilePath: options.analyze ? join8(dirname8(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12626
+ metafilePath: options.analyze ? join9(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12556
12627
  optimizeImports: options.optimizeImports,
12557
12628
  outDir: targetDir,
12558
12629
  pagesDir: app.pagesDir,
@@ -12564,9 +12635,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12564
12635
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12565
12636
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12566
12637
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12567
- const clientDir = join8(targetDir, clientDirName);
12638
+ const clientDir = join9(targetDir, clientDirName);
12568
12639
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12569
- writeFileSync4(join8(clientDir, "index.html"), indexHtml);
12640
+ writeFileSync4(join9(clientDir, "index.html"), indexHtml);
12570
12641
  setProductionTemplateContent(indexHtml);
12571
12642
  ssgRouteCache().clear();
12572
12643
  let ssgCache;
@@ -12626,7 +12697,7 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12626
12697
  // src/adapter/bun.ts
12627
12698
  function generateBootEntry(appEntry, outDir, filename) {
12628
12699
  ensureDir(outDir);
12629
- const entryPath = join9(outDir, filename);
12700
+ const entryPath = join10(outDir, filename);
12630
12701
  return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12631
12702
  }
12632
12703
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
@@ -12642,6 +12713,42 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12642
12713
  function compiledServerFilename(platform) {
12643
12714
  return platform === "win32" ? "server.exe" : "server";
12644
12715
  }
12716
+ function serverSourcemapMode(enabled) {
12717
+ return enabled ? "external" : "none";
12718
+ }
12719
+ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
12720
+ if (!enabled) {
12721
+ return;
12722
+ }
12723
+ movePrivateServerSourceMaps(targetDir, join10(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
12724
+ }
12725
+ function writeServerMetafile(build, analyze, buildRoot) {
12726
+ if (!analyze) {
12727
+ return;
12728
+ }
12729
+ if (build.metafile === undefined) {
12730
+ throw new Error("[furin] Bun server build did not produce the requested metafile.");
12731
+ }
12732
+ const analysisDir = join10(buildRoot, "analysis");
12733
+ ensureDir(analysisDir);
12734
+ const metafilePath = join10(analysisDir, "bun-server.json");
12735
+ writeFileSync5(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
12736
+ `);
12737
+ console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
12738
+ }
12739
+ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
12740
+ if (compile !== "embed") {
12741
+ return;
12742
+ }
12743
+ for (const app of apps) {
12744
+ rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
12745
+ force: true,
12746
+ recursive: true
12747
+ });
12748
+ }
12749
+ manifest.clientDir = null;
12750
+ manifest.templatePath = null;
12751
+ }
12645
12752
  async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12646
12753
  if (!serverEntry) {
12647
12754
  return;
@@ -12657,7 +12764,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
12657
12764
  ...context.extraContext ?? [],
12658
12765
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12659
12766
  ],
12660
- templateHtml: readFileSync4(join9(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12767
+ templateHtml: readFileSync4(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12661
12768
  }));
12662
12769
  return await materializeServerAppEntry({
12663
12770
  apps: contexts,
@@ -12678,30 +12785,35 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12678
12785
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12679
12786
  const targetDir = resolve6(rootDir, targetManifest.targetDir);
12680
12787
  rmSync2(targetDir, { force: true, recursive: true });
12788
+ rmSync2(join10(buildRoot, "private", "server-sourcemaps", "bun"), {
12789
+ force: true,
12790
+ recursive: true
12791
+ });
12681
12792
  ensureDir(targetDir);
12682
- const publicDir = existsSync7(join9(rootDir, "public")) ? join9(rootDir, "public") : undefined;
12793
+ const publicDir = existsSync8(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
12683
12794
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12684
12795
  targetManifest.buildId = headlineBuildId;
12685
12796
  if (serverEntry) {
12686
- targetManifest.rscManifestPath = toPosixPath(join9(targetManifest.targetDir, "rsc", "manifest.json"));
12797
+ targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
12687
12798
  }
12688
- const targetPublicDir = publicDir ? join9(targetDir, "public") : undefined;
12799
+ const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
12689
12800
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12690
12801
  copyDirRecursive(publicDir, targetPublicDir);
12691
12802
  }
12692
12803
  const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12693
12804
  if (options.compile && serverEntry && appEntry) {
12694
12805
  const serverFilename = compiledServerFilename(process.platform);
12695
- const outfile = join9(targetDir, serverFilename);
12806
+ const outfile = join10(targetDir, serverFilename);
12696
12807
  const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12697
12808
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12698
- await runBunBuild({
12809
+ const serverBuild = await runBunBuild({
12699
12810
  bytecode: true,
12700
12811
  compile: { assets: embeddedAssets, outfile },
12701
12812
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
12702
12813
  entrypoints: [entry.entrypoint],
12703
12814
  files: entry.files,
12704
12815
  format: "esm",
12816
+ metafile: options.analyze,
12705
12817
  minify: true,
12706
12818
  plugins: [
12707
12819
  entry.plugin,
@@ -12713,27 +12825,21 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12713
12825
  environmentGuardPlugin("ssr"),
12714
12826
  elysiaAot(appEntry)
12715
12827
  ],
12716
- sourcemap: "none",
12828
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12717
12829
  splitting: true,
12718
12830
  target: "bun"
12719
12831
  });
12832
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12833
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12720
12834
  console.log(`[furin] Server binary: ${outfile}`);
12721
- targetManifest.serverPath = toPosixPath(join9(targetManifest.targetDir, serverFilename));
12722
- if (options.compile === "embed") {
12723
- for (const app of apps) {
12724
- rmSync2(join9(targetDir, clientDirNameForPrefix(app.prefix)), {
12725
- force: true,
12726
- recursive: true
12727
- });
12728
- }
12729
- targetManifest.clientDir = null;
12730
- targetManifest.templatePath = null;
12731
- }
12835
+ targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, serverFilename));
12836
+ finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
12732
12837
  } else if (serverEntry && appEntry) {
12733
12838
  const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12734
- await runBunBuild({
12839
+ const serverBuild = await runBunBuild({
12735
12840
  entrypoints: [entry.entrypoint],
12736
12841
  files: entry.files,
12842
+ metafile: options.analyze,
12737
12843
  minify: true,
12738
12844
  naming: { chunk: "[name]-[hash].[ext]", entry: "[name].[ext]" },
12739
12845
  outdir: targetDir,
@@ -12747,28 +12853,30 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12747
12853
  environmentGuardPlugin("ssr"),
12748
12854
  elysiaAot(appEntry)
12749
12855
  ],
12750
- sourcemap: "none",
12856
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12751
12857
  target: "bun"
12752
12858
  });
12753
- console.log(`[furin] Server bundle: ${toPosixPath(join9(targetManifest.targetDir, "server.js"))}`);
12754
- targetManifest.serverPath = toPosixPath(join9(targetManifest.targetDir, "server.js"));
12859
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12860
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12861
+ console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
12862
+ targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
12755
12863
  }
12756
12864
  return targetManifest;
12757
12865
  }
12758
12866
 
12759
12867
  // src/adapter/package.ts
12760
- import { existsSync as existsSync8, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
12761
- import { join as join10, relative as relative6, resolve as resolve7 } from "path";
12868
+ import { existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
12869
+ import { join as join11, relative as relative7, resolve as resolve7 } from "path";
12762
12870
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12763
12871
  const { prefix, root, routes, pagesDir } = app;
12764
12872
  const modulePaths = routeSourcePaths(app);
12765
- const targetDir = join10(buildRoot, "package");
12873
+ const targetDir = join11(buildRoot, "package");
12766
12874
  rmSync3(targetDir, { force: true, recursive: true });
12767
12875
  ensureDir(targetDir);
12768
12876
  const { entryChunk, cssChunks } = await buildClient(routes, {
12769
12877
  basePath: prefix,
12770
12878
  clientLogging: options.clientLogging ?? false,
12771
- metafilePath: options.analyze ? join10(buildRoot, "analysis", "package-client.json") : undefined,
12879
+ metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
12772
12880
  optimizeImports: options.optimizeImports,
12773
12881
  outDir: targetDir,
12774
12882
  pagesDir,
@@ -12780,13 +12888,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12780
12888
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12781
12889
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12782
12890
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12783
- const clientDir = join10(targetDir, "client");
12784
- const publicDir = join10(rootDir, "public");
12785
- if (existsSync8(publicDir)) {
12786
- copyDirRecursive(publicDir, join10(targetDir, "public"));
12891
+ const clientDir = join11(targetDir, "client");
12892
+ const publicDir = join11(rootDir, "public");
12893
+ if (existsSync9(publicDir)) {
12894
+ copyDirRecursive(publicDir, join11(targetDir, "public"));
12787
12895
  }
12788
12896
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12789
- writeFileSync5(join10(clientDir, "index.html"), indexHtml);
12897
+ writeFileSync6(join11(clientDir, "index.html"), indexHtml);
12790
12898
  setProductionTemplateContent(indexHtml);
12791
12899
  ssgRouteCache().clear();
12792
12900
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12823,7 +12931,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12823
12931
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12824
12932
  mode: "register"
12825
12933
  });
12826
- const registerEntry = join10(targetDir, "register.ts");
12934
+ const registerEntry = join11(targetDir, "register.ts");
12827
12935
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12828
12936
  const result = await runBunBuild({
12829
12937
  entrypoints: [register.entrypoint],
@@ -12843,7 +12951,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12843
12951
  if (!result.success) {
12844
12952
  throw new AggregateError(result.logs, "[furin] package register build failed");
12845
12953
  }
12846
- const relativePagesDir = toPosixPath(relative6(targetDir, resolve7(rootDir, pagesDir)));
12954
+ const relativePagesDir = toPosixPath(relative7(targetDir, resolve7(rootDir, pagesDir)));
12847
12955
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12848
12956
  import { fileURLToPath } from "node:url";
12849
12957
  import { furin } from "@teyik0/furin";
@@ -12870,7 +12978,7 @@ export function createFurinApp(options = {}) {
12870
12978
 
12871
12979
  export const prefix = ${JSON.stringify(prefix)};
12872
12980
  `;
12873
- writeFileSync5(join10(targetDir, "index.js"), factorySource);
12981
+ writeFileSync6(join11(targetDir, "index.js"), factorySource);
12874
12982
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12875
12983
 
12876
12984
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12878,19 +12986,19 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12878
12986
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12879
12987
  export declare const prefix: string;
12880
12988
  `;
12881
- writeFileSync5(join10(targetDir, "index.d.ts"), dtsSource);
12882
- console.log(`[furin] Package artifact: ${toPosixPath(relative6(rootDir, targetDir))}`);
12989
+ writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
12990
+ console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
12883
12991
  return {
12884
12992
  buildId,
12885
12993
  generatedAt: new Date().toISOString(),
12886
12994
  prefix,
12887
- targetDir: toPosixPath(relative6(rootDir, targetDir))
12995
+ targetDir: toPosixPath(relative7(rootDir, targetDir))
12888
12996
  };
12889
12997
  }
12890
12998
 
12891
12999
  // src/adapter/static.ts
12892
- import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
12893
- import { dirname as dirname9, isAbsolute as isAbsolute3, join as join11, parse as parse3, relative as relative7, resolve as resolve8, sep as sep2, win32 } from "path";
13000
+ import { cpSync as cpSync2, existsSync as existsSync10, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";
13001
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join12, parse as parse3, relative as relative8, resolve as resolve8, sep as sep2, win32 } from "path";
12894
13002
  var STATIC_CONCURRENCY = 4;
12895
13003
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
12896
13004
  var TRAILING_SLASHES_RE = /\/+$/;
@@ -12898,7 +13006,7 @@ var STATIC_RENDER_ORIGIN = "http://localhost";
12898
13006
  function pathToOutputFile(urlPath, outDir, fileName) {
12899
13007
  const normalizedOutDir = resolve8(outDir);
12900
13008
  if (urlPath === "/" || urlPath === "") {
12901
- return join11(normalizedOutDir, fileName);
13009
+ return join12(normalizedOutDir, fileName);
12902
13010
  }
12903
13011
  const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
12904
13012
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
@@ -12973,22 +13081,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
12973
13081
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
12974
13082
  }
12975
13083
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
12976
- ensureDir(dirname9(htmlOutputFile));
12977
- writeFileSync6(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13084
+ ensureDir(dirname10(htmlOutputFile));
13085
+ writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12978
13086
  if (staticLocation.spa !== null) {
12979
13087
  const serializedRedirect = await toCrossJSONAsync({
12980
13088
  __furinRedirect: staticLocation.spa
12981
13089
  });
12982
- writeFileSync6(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13090
+ writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12983
13091
  `);
12984
13092
  }
12985
13093
  renderedRoutes.push(urlPath);
12986
13094
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
12987
13095
  return;
12988
13096
  }
12989
- ensureDir(dirname9(htmlOutputFile));
12990
- writeFileSync6(htmlOutputFile, entry.html);
12991
- writeFileSync6(dataOutputFile, entry.ndjson);
13097
+ ensureDir(dirname10(htmlOutputFile));
13098
+ writeFileSync7(htmlOutputFile, entry.html);
13099
+ writeFileSync7(dataOutputFile, entry.ndjson);
12992
13100
  renderedRoutes.push(urlPath);
12993
13101
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
12994
13102
  } catch (err) {
@@ -13102,8 +13210,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13102
13210
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
13103
13211
  }
13104
13212
  function isOutsideOutDir(target) {
13105
- const rel = relative7(outDir, target);
13106
- return rel.startsWith("..") || isAbsolute3(rel);
13213
+ const rel = relative8(outDir, target);
13214
+ return rel.startsWith("..") || isAbsolute4(rel);
13107
13215
  }
13108
13216
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
13109
13217
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -13119,36 +13227,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13119
13227
  const afterQueueCount = skippedRoutes.length;
13120
13228
  rmSync4(outDir, { force: true, recursive: true });
13121
13229
  ensureDir(outDir);
13122
- const targetDir = join11(buildRoot, "static");
13230
+ const targetDir = join12(buildRoot, "static");
13123
13231
  rmSync4(targetDir, { force: true, recursive: true });
13124
13232
  ensureDir(targetDir);
13125
13233
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
13126
13234
  basePath,
13127
13235
  clientLogging: Boolean(options.clientLogging),
13128
- metafilePath: options.analyze ? join11(buildRoot, "analysis", "static-client.json") : undefined,
13236
+ metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
13129
13237
  optimizeImports: options.optimizeImports,
13130
13238
  outDir: targetDir,
13131
- pagesDir: dirname9(root.path),
13239
+ pagesDir: dirname10(root.path),
13132
13240
  plugins: options.plugins,
13133
13241
  publicPath,
13134
13242
  reactCompiler: options.reactCompiler,
13135
13243
  rootLayout: root.path
13136
13244
  });
13137
- const publicFavicon = join11(rootDir, "public", "favicon.ico");
13138
- const faviconHref = existsSync9(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13245
+ const publicFavicon = join12(rootDir, "public", "favicon.ico");
13246
+ const faviconHref = existsSync10(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13139
13247
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
13140
13248
  setProductionTemplateContent(shellHtml);
13141
- const publicSrcDir = join11(rootDir, "public");
13142
- if (existsSync9(publicSrcDir)) {
13249
+ const publicSrcDir = join12(rootDir, "public");
13250
+ if (existsSync10(publicSrcDir)) {
13143
13251
  cpSync2(publicSrcDir, outDir, { recursive: true });
13144
13252
  }
13145
- const clientSrcDir = join11(targetDir, "client");
13146
- if (existsSync9(clientSrcDir)) {
13147
- cpSync2(clientSrcDir, join11(outDir, "_client"), { recursive: true });
13253
+ const clientSrcDir = join12(targetDir, "client");
13254
+ if (existsSync10(clientSrcDir)) {
13255
+ cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
13148
13256
  }
13149
13257
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
13150
13258
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
13151
- writeFileSync6(join11(outDir, "404.html"), shellHtml);
13259
+ writeFileSync7(join12(outDir, "404.html"), shellHtml);
13152
13260
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
13153
13261
  rmSync4(targetDir, { force: true, recursive: true });
13154
13262
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -13162,8 +13270,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13162
13270
  }
13163
13271
 
13164
13272
  // src/adapter/vercel.ts
13165
- import { cpSync as cpSync3, existsSync as existsSync10, readFileSync as readFileSync5, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync7 } from "fs";
13166
- import { basename as basename5, dirname as dirname10, extname as extname3, join as join12, relative as relative8 } from "path";
13273
+ import { cpSync as cpSync3, existsSync as existsSync11, readFileSync as readFileSync5, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync8 } from "fs";
13274
+ import { basename as basename5, dirname as dirname11, extname as extname3, join as join13, relative as relative9 } from "path";
13167
13275
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
13168
13276
  init_patterns();
13169
13277
  var ISR_PATH_PARAM = "__furin_path";
@@ -13174,12 +13282,12 @@ var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
13174
13282
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
13175
13283
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
13176
13284
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
13177
- var FURIN_RUNTIME_ROOT2 = dirname10(import.meta.dir);
13285
+ var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
13178
13286
  function isFurinRuntimeImporter(importer) {
13179
13287
  if (importer === "") {
13180
13288
  return false;
13181
13289
  }
13182
- const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13290
+ const fromRuntimeRoot = relative9(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13183
13291
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
13184
13292
  }
13185
13293
  function vercelRuntimePlugin() {
@@ -13205,8 +13313,8 @@ function vercelRuntimePlugin() {
13205
13313
  };
13206
13314
  }
13207
13315
  function frameworkVersion() {
13208
- const packageRoot = dirname10(dirname10(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13209
- const packageJson = JSON.parse(readFileSync5(join12(packageRoot, "package.json"), "utf8"));
13316
+ const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13317
+ const packageJson = JSON.parse(readFileSync5(join13(packageRoot, "package.json"), "utf8"));
13210
13318
  return packageJson.version;
13211
13319
  }
13212
13320
  function serverEntryLoader(serverEntry) {
@@ -13322,9 +13430,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13322
13430
  body = result.html;
13323
13431
  ({ status } = result);
13324
13432
  }
13325
- const fallbackPath = join12(dirname10(join12(functionsDir, spec.functionName)), fallback);
13326
- ensureDir(dirname10(fallbackPath));
13327
- writeFileSync7(fallbackPath, body);
13433
+ const fallbackPath = join13(dirname11(join13(functionsDir, spec.functionName)), fallback);
13434
+ ensureDir(dirname11(fallbackPath));
13435
+ writeFileSync8(fallbackPath, body);
13328
13436
  spec.config.fallback = fallback;
13329
13437
  spec.config.initialHeaders = {
13330
13438
  "content-type": contentType,
@@ -13335,9 +13443,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13335
13443
  spec.config.initialStatus = status;
13336
13444
  }
13337
13445
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13338
- const aliasPath = join12(functionsDir, `${functionName}.func`);
13339
- ensureDir(dirname10(aliasPath));
13340
- const target = relative8(dirname10(aliasPath), serverFunctionDir);
13446
+ const aliasPath = join13(functionsDir, `${functionName}.func`);
13447
+ ensureDir(dirname11(aliasPath));
13448
+ const target = relative9(dirname11(aliasPath), serverFunctionDir);
13341
13449
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13342
13450
  }
13343
13451
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13559,10 +13667,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13559
13667
  if (jobs.length === 0) {
13560
13668
  return;
13561
13669
  }
13562
- const resultPath = join12(targetDir, "ppr-results.json");
13670
+ const resultPath = join13(targetDir, "ppr-results.json");
13563
13671
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13564
13672
  const script = `
13565
- const handler = (await import(${JSON.stringify(pathToFileURL2(join12(functionsDir, "__server.func/index.js")).href)})).default;
13673
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
13566
13674
  const results = [];
13567
13675
  for (const url of ${JSON.stringify(requests)}) {
13568
13676
  const response = await handler.fetch(new Request(url));
@@ -13671,35 +13779,39 @@ export default { fetch: handle };
13671
13779
  }
13672
13780
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13673
13781
  assertDefaultServerExport(serverEntry);
13674
- const targetDir = join12(buildRoot, "vercel");
13675
- const outputDir = join12(rootDir, ".vercel", "output");
13676
- const staticDir = join12(outputDir, "static");
13677
- const functionsDir = join12(outputDir, "functions");
13678
- const serverFunctionDir = join12(functionsDir, "__server.func");
13782
+ const targetDir = join13(buildRoot, "vercel");
13783
+ const outputDir = join13(rootDir, ".vercel", "output");
13784
+ const staticDir = join13(outputDir, "static");
13785
+ const functionsDir = join13(outputDir, "functions");
13786
+ const serverFunctionDir = join13(functionsDir, "__server.func");
13679
13787
  rmSync5(targetDir, { force: true, recursive: true });
13788
+ rmSync5(join13(buildRoot, "private", "server-sourcemaps", "vercel"), {
13789
+ force: true,
13790
+ recursive: true
13791
+ });
13680
13792
  rmSync5(outputDir, { force: true, recursive: true });
13681
13793
  ensureDir(targetDir);
13682
13794
  ensureDir(staticDir);
13683
13795
  ensureDir(serverFunctionDir);
13684
13796
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
13685
- cpSync3(join12(targetDir, "server-codec.js"), join12(serverFunctionDir, "server-codec.js"));
13686
- const publicDir = join12(rootDir, "public");
13687
- if (existsSync10(publicDir)) {
13797
+ cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
13798
+ const publicDir = join13(rootDir, "public");
13799
+ if (existsSync11(publicDir)) {
13688
13800
  cpSync3(publicDir, staticDir, { recursive: true });
13689
13801
  for (const app of apps) {
13690
- const appStaticDir = join12(staticDir, app.prefix.slice(1));
13691
- const appPublicDir = join12(appStaticDir, "public");
13802
+ const appStaticDir = join13(staticDir, app.prefix.slice(1));
13803
+ const appPublicDir = join13(appStaticDir, "public");
13692
13804
  cpSync3(publicDir, appPublicDir, { recursive: true });
13693
- const favicon = join12(publicDir, "favicon.ico");
13694
- if (app.prefix !== "" && existsSync10(favicon)) {
13695
- cpSync3(favicon, join12(appStaticDir, "favicon.ico"));
13805
+ const favicon = join13(publicDir, "favicon.ico");
13806
+ if (app.prefix !== "" && existsSync11(favicon)) {
13807
+ cpSync3(favicon, join13(appStaticDir, "favicon.ico"));
13696
13808
  }
13697
13809
  }
13698
13810
  }
13699
13811
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13700
13812
  const app = apps[appIndex];
13701
13813
  const build = builds[appIndex];
13702
- const clientOutputDir = join12(staticDir, app.prefix.slice(1), "_client");
13814
+ const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
13703
13815
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13704
13816
  }
13705
13817
  const pprResumeKey = crypto.randomUUID();
@@ -13716,7 +13828,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13716
13828
  outDir: serverFunctionDir,
13717
13829
  serverEntry
13718
13830
  });
13719
- const entryPath = join12(serverFunctionDir, "_vercel-handler.ts");
13831
+ const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
13720
13832
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13721
13833
  const serverBuild = await runBunBuild({
13722
13834
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
@@ -13738,24 +13850,27 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13738
13850
  environmentGuardPlugin("ssr"),
13739
13851
  elysiaAot(appEntry)
13740
13852
  ],
13741
- sourcemap: "none",
13853
+ sourcemap: options.serverSourceMaps ? "external" : "none",
13742
13854
  splitting: true,
13743
13855
  target: "bun"
13744
13856
  });
13857
+ if (options.serverSourceMaps) {
13858
+ movePrivateServerSourceMaps(serverFunctionDir, join13(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
13859
+ }
13745
13860
  if (options.analyze) {
13746
13861
  if (serverBuild.metafile === undefined) {
13747
13862
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13748
13863
  }
13749
- const metafilePath = join12(buildRoot, "analysis", "vercel-server.json");
13750
- ensureDir(dirname10(metafilePath));
13751
- writeFileSync7(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13864
+ const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
13865
+ ensureDir(dirname11(metafilePath));
13866
+ writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13752
13867
  `);
13753
13868
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13754
13869
  }
13755
13870
  const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13756
- writeFileSync7(join12(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13871
+ writeFileSync8(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13757
13872
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13758
- writeFileSync7(join12(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13873
+ writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13759
13874
  handler: "index.js",
13760
13875
  launcherType: "Nodejs",
13761
13876
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13766,7 +13881,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13766
13881
  `);
13767
13882
  for (const spec of prerenderSpecs) {
13768
13883
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13769
- writeFileSync7(join12(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13884
+ writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13770
13885
  `);
13771
13886
  }
13772
13887
  const assetRoutes = apps.map((app) => ({
@@ -13796,48 +13911,71 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13796
13911
  ],
13797
13912
  version: 3
13798
13913
  };
13799
- writeFileSync7(join12(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13914
+ writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13800
13915
  `);
13801
13916
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13802
13917
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
13803
- console.log(`[furin] Vercel output: ${toPosixPath(relative8(rootDir, outputDir))}`);
13918
+ console.log(`[furin] Vercel output: ${toPosixPath(relative9(rootDir, outputDir))}`);
13804
13919
  return {
13805
13920
  buildId: headlineBuildId,
13806
13921
  generatedAt: new Date().toISOString(),
13807
13922
  isrRoutes,
13808
- outputDir: toPosixPath(relative8(rootDir, outputDir)),
13809
- serverPath: toPosixPath(relative8(rootDir, serverFunctionDir)),
13923
+ outputDir: toPosixPath(relative9(rootDir, outputDir)),
13924
+ serverPath: toPosixPath(relative9(rootDir, serverFunctionDir)),
13810
13925
  ssgRoutes
13811
13926
  };
13812
13927
  }
13813
13928
 
13814
13929
  // src/config.ts
13815
- import { t as t2 } from "elysia";
13930
+ import { t } from "elysia";
13816
13931
  var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
13817
- var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13818
- var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13819
- var configSchema = t2.Object({
13820
- apps: t2.Optional(t2.Array(t2.Object({
13821
- pagesDir: t2.String(),
13822
- prefix: t2.Optional(t2.String())
13932
+ var VERCEL_REGIONS = [
13933
+ "arn1",
13934
+ "bom1",
13935
+ "cdg1",
13936
+ "cle1",
13937
+ "cpt1",
13938
+ "dub1",
13939
+ "dxb1",
13940
+ "fra1",
13941
+ "gru1",
13942
+ "hkg1",
13943
+ "hnd1",
13944
+ "iad1",
13945
+ "icn1",
13946
+ "kix1",
13947
+ "lhr1",
13948
+ "pdx1",
13949
+ "sfo1",
13950
+ "sin1",
13951
+ "syd1",
13952
+ "yul1"
13953
+ ];
13954
+ var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
13955
+ var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
13956
+ var configSchema = t.Object({
13957
+ apps: t.Optional(t.Array(t.Object({
13958
+ pagesDir: t.String(),
13959
+ prefix: t.Optional(t.String())
13823
13960
  }))),
13824
- bun: t2.Optional(t2.Object({
13825
- compile: t2.Optional(compileTargetSchema)
13961
+ bun: t.Optional(t.Object({
13962
+ compile: t.Optional(compileTargetSchema)
13826
13963
  })),
13827
- clientLogging: t2.Optional(t2.Boolean()),
13828
- optimizeImports: t2.Optional(t2.Array(t2.String())),
13829
- pagesDir: t2.Optional(t2.String()),
13830
- reactCompiler: t2.Optional(t2.Boolean()),
13831
- rootDir: t2.Optional(t2.String()),
13832
- serverEntry: t2.Optional(t2.String()),
13833
- static: t2.Optional(t2.Object({
13834
- basePath: t2.Optional(t2.String()),
13835
- onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")])),
13836
- outDir: t2.Optional(t2.String())
13964
+ clientLogging: t.Optional(t.Boolean()),
13965
+ optimizeImports: t.Optional(t.Array(t.String())),
13966
+ pagesDir: t.Optional(t.String()),
13967
+ reactCompiler: t.Optional(t.Boolean()),
13968
+ rootDir: t.Optional(t.String()),
13969
+ serverEntry: t.Optional(t.String()),
13970
+ serverSourceMaps: t.Optional(t.Boolean()),
13971
+ static: t.Optional(t.Object({
13972
+ basePath: t.Optional(t.String()),
13973
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
13974
+ outDir: t.Optional(t.String())
13837
13975
  })),
13838
- targets: t2.Optional(t2.Array(buildTargetSchema)),
13839
- vercel: t2.Optional(t2.Object({
13840
- regions: t2.Optional(t2.Array(t2.String({ pattern: "^[a-z]{3}[1-9][0-9]*$" }), {
13976
+ targets: t.Optional(t.Array(buildTargetSchema)),
13977
+ vercel: t.Optional(t.Object({
13978
+ regions: t.Optional(t.Array(t.Enum(VERCEL_REGIONS), {
13841
13979
  minItems: 1,
13842
13980
  uniqueItems: true
13843
13981
  }))
@@ -13848,9 +13986,9 @@ var configSchema = t2.Object({
13848
13986
  init_instance();
13849
13987
 
13850
13988
  // src/server/router/discovery.ts
13851
- import { existsSync as existsSync11 } from "fs";
13989
+ import { existsSync as existsSync12 } from "fs";
13852
13990
  import { readdir } from "fs/promises";
13853
- import { join as join13, parse as parse4 } from "path";
13991
+ import { join as join14, parse as parse4 } from "path";
13854
13992
 
13855
13993
  // src/server/internal.ts
13856
13994
  var _compileContexts = new Map;
@@ -14000,7 +14138,7 @@ async function scanPages(pagesDir) {
14000
14138
  async function scanRootLayout(pagesDir) {
14001
14139
  const rootPath = `${pagesDir}/root.tsx`;
14002
14140
  const ctx = getCompileContext();
14003
- if (!(existsSync11(rootPath) || ctx?.modules[rootPath])) {
14141
+ if (!(existsSync12(rootPath) || ctx?.modules[rootPath])) {
14004
14142
  throw new Error("[furin] root.tsx: not found.");
14005
14143
  }
14006
14144
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -14040,8 +14178,8 @@ function getSourceModuleCandidates(dir, name) {
14040
14178
  async function loadConventionComponent(dir, name) {
14041
14179
  const ctx = getCompileContext();
14042
14180
  for (const filePath of getSourceModuleCandidates(dir, name)) {
14043
- if (existsSync11(filePath) || ctx?.modules[filePath]) {
14044
- const moduleSpecifier = IS_DEV && existsSync11(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14181
+ if (existsSync12(filePath) || ctx?.modules[filePath]) {
14182
+ const moduleSpecifier = IS_DEV && existsSync12(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14045
14183
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
14046
14184
  if (mod.default) {
14047
14185
  return { component: mod.default, path: filePath };
@@ -14124,10 +14262,10 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
14124
14262
  for (const segment of segments) {
14125
14263
  directory = `${directory}/${segment}`;
14126
14264
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
14127
- if (!existsSync11(candidate)) {
14265
+ if (!existsSync12(candidate)) {
14128
14266
  continue;
14129
14267
  }
14130
- const layoutModule = await import(candidate);
14268
+ const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
14131
14269
  const layout = layoutModule.route;
14132
14270
  if (isDefinedRouteTerminal(layout) && typeof layout.layout === "function") {
14133
14271
  parent = adaptDefinedLayout(layout, parent, candidate);
@@ -14224,7 +14362,7 @@ async function collectPageFilePaths(dir) {
14224
14362
  const files = [];
14225
14363
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
14226
14364
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
14227
- const absolutePath = toPosixPath2(join13(dir, entry.name));
14365
+ const absolutePath = toPosixPath2(join14(dir, entry.name));
14228
14366
  if (entry.isDirectory()) {
14229
14367
  return await collectPageFilePaths(absolutePath);
14230
14368
  }
@@ -14343,20 +14481,23 @@ function resolveAppSpecs(options, serverEntry, rootDir) {
14343
14481
  return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14344
14482
  }
14345
14483
  async function buildApp(options) {
14484
+ return withProductionBuild(() => buildAppInternal(options));
14485
+ }
14486
+ async function buildAppInternal(options) {
14346
14487
  const rootDir = resolve9(options.rootDir ?? process.cwd());
14347
- const buildRoot = join14(rootDir, BUILD_OUTPUT_DIR);
14488
+ const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
14348
14489
  const serverEntry = (() => {
14349
14490
  if (options.target === "static" || options.target === "package") {
14350
14491
  return null;
14351
14492
  }
14352
14493
  if (options.serverEntry) {
14353
14494
  const resolved = resolve9(rootDir, options.serverEntry);
14354
- if (existsSync12(resolved)) {
14495
+ if (existsSync13(resolved)) {
14355
14496
  return resolved;
14356
14497
  }
14357
14498
  }
14358
14499
  const entry = resolve9(rootDir, "src/server.ts");
14359
- if (!existsSync12(entry)) {
14500
+ if (!existsSync13(entry)) {
14360
14501
  throw new Error("[furin] Entrypoint server.ts not found");
14361
14502
  }
14362
14503
  return entry;
@@ -14396,12 +14537,12 @@ async function buildApp(options) {
14396
14537
  version: 1,
14397
14538
  generatedAt: new Date().toISOString(),
14398
14539
  rootDir: toPosixPath(rootDir),
14399
- pagesDir: toPosixPath(relative9(rootDir, primaryApp.pagesDir)),
14400
- rootPath: toPosixPath(relative9(rootDir, primaryApp.root.path)),
14401
- serverEntry: serverEntry ? toPosixPath(relative9(rootDir, serverEntry)) : null,
14540
+ pagesDir: toPosixPath(relative10(rootDir, primaryApp.pagesDir)),
14541
+ rootPath: toPosixPath(relative10(rootDir, primaryApp.root.path)),
14542
+ serverEntry: serverEntry ? toPosixPath(relative10(rootDir, serverEntry)) : null,
14402
14543
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14403
14544
  apps: apps.map((app) => ({
14404
- pagesDir: toPosixPath(relative9(rootDir, app.pagesDir)),
14545
+ pagesDir: toPosixPath(relative10(rootDir, app.pagesDir)),
14405
14546
  prefix: app.prefix,
14406
14547
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14407
14548
  })),
@@ -14437,7 +14578,7 @@ async function buildApp(options) {
14437
14578
  throw new Error(`[furin] Unsupported build target "${target}"`);
14438
14579
  }
14439
14580
  }
14440
- writeFileSync8(join14(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14581
+ writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14441
14582
  `);
14442
14583
  return {
14443
14584
  manifest,
@@ -14449,7 +14590,7 @@ async function buildApp(options) {
14449
14590
  init_instance();
14450
14591
 
14451
14592
  // src/cli/config.ts
14452
- import { existsSync as existsSync13 } from "fs";
14593
+ import { existsSync as existsSync14 } from "fs";
14453
14594
  import { resolve as resolve10 } from "path";
14454
14595
  import { pathToFileURL as pathToFileURL3 } from "url";
14455
14596
  import { Validator as Validator2 } from "elysia";
@@ -14461,7 +14602,7 @@ var DEFAULT_CONFIG_FILENAMES = [
14461
14602
  ];
14462
14603
  async function loadCliConfig(cwd, explicitConfigPath) {
14463
14604
  const rootDir = resolve10(cwd);
14464
- const configPath = explicitConfigPath ? resolve10(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve10(rootDir, filename)).find((path) => existsSync13(path));
14605
+ const configPath = explicitConfigPath ? resolve10(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve10(rootDir, filename)).find((path) => existsSync14(path));
14465
14606
  if (!configPath) {
14466
14607
  return {
14467
14608
  configPath: null,
@@ -14489,8 +14630,8 @@ async function loadCliConfig(cwd, explicitConfigPath) {
14489
14630
  }
14490
14631
 
14491
14632
  // src/cli/preview.ts
14492
- import { existsSync as existsSync14 } from "fs";
14493
- import { isAbsolute as isAbsolute4, join as join15, relative as relative10, resolve as resolve11 } from "path";
14633
+ import { existsSync as existsSync15 } from "fs";
14634
+ import { isAbsolute as isAbsolute5, join as join16, relative as relative11, resolve as resolve11 } from "path";
14494
14635
  var LEADING_SLASHES_RE = /^\/+/;
14495
14636
  var TRAILING_SLASHES_RE2 = /\/+$/;
14496
14637
  function normalizeStaticPreviewBasePath(basePath) {
@@ -14509,14 +14650,14 @@ function startStaticPreview({
14509
14650
  }) {
14510
14651
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
14511
14652
  const distDir = resolve11(rawDistDir);
14512
- const indexPath = join15(distDir, "index.html");
14513
- const notFoundPath = join15(distDir, "404.html");
14514
- const faviconPath = join15(distDir, "favicon.ico");
14515
- if (!(existsSync14(indexPath) && existsSync14(notFoundPath))) {
14653
+ const indexPath = join16(distDir, "index.html");
14654
+ const notFoundPath = join16(distDir, "404.html");
14655
+ const faviconPath = join16(distDir, "favicon.ico");
14656
+ if (!(existsSync15(indexPath) && existsSync15(notFoundPath))) {
14516
14657
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
14517
14658
  }
14518
14659
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
14519
- const clientDir = join15(distDir, "_client");
14660
+ const clientDir = join16(distDir, "_client");
14520
14661
  const fetchStaticFile = async (request) => {
14521
14662
  const encodedPathname = new URL(request.url).pathname;
14522
14663
  let pathname;
@@ -14530,15 +14671,15 @@ function startStaticPreview({
14530
14671
  }
14531
14672
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
14532
14673
  const exactPath = resolve11(distDir, logicalPath);
14533
- const relativePath = relative10(distDir, exactPath);
14534
- if (relativePath.startsWith("..") || isAbsolute4(relativePath)) {
14674
+ const relativePath = relative11(distDir, exactPath);
14675
+ if (relativePath.startsWith("..") || isAbsolute5(relativePath)) {
14535
14676
  return notFound();
14536
14677
  }
14537
14678
  const exactFile = Bun.file(exactPath);
14538
14679
  if (!pathname.endsWith("/") && await exactFile.exists()) {
14539
14680
  return new Response(exactFile);
14540
14681
  }
14541
- const indexFile = Bun.file(join15(exactPath, "index.html"));
14682
+ const indexFile = Bun.file(join16(exactPath, "index.html"));
14542
14683
  if (await indexFile.exists()) {
14543
14684
  return new Response(indexFile);
14544
14685
  }
@@ -14554,7 +14695,7 @@ function startStaticPreview({
14554
14695
  routes: {
14555
14696
  ...entryRoutes,
14556
14697
  [`${basePath}/_client/*`]: { dir: clientDir },
14557
- "/favicon.ico": existsSync14(faviconPath) ? Bun.file(faviconPath) : notFound()
14698
+ "/favicon.ico": existsSync15(faviconPath) ? Bun.file(faviconPath) : notFound()
14558
14699
  }
14559
14700
  });
14560
14701
  }
@@ -14668,7 +14809,7 @@ if (command === "preview") {
14668
14809
  const isServerlessTarget = target === "static" || target === "package";
14669
14810
  const resolvedServerEntry = isServerlessTarget ? undefined : (() => {
14670
14811
  const entry = resolve12(config.rootDir, config.serverEntry ?? "src/server.ts");
14671
- if (!existsSync15(entry)) {
14812
+ if (!existsSync16(entry)) {
14672
14813
  const expected = config.serverEntry ?? "src/server.ts";
14673
14814
  throw new Error(`[furin] Entrypoint ${expected} not found`);
14674
14815
  }
@@ -14691,6 +14832,7 @@ if (command === "preview") {
14691
14832
  reactCompiler: config.reactCompiler,
14692
14833
  rootDir: config.rootDir,
14693
14834
  serverEntry: resolvedServerEntry,
14835
+ serverSourceMaps: config.serverSourceMaps,
14694
14836
  staticConfig: config.static,
14695
14837
  target,
14696
14838
  vercelConfig: config.vercel