@rangojs/router 0.0.0-experimental.78a48627 → 0.0.0-experimental.79

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 (147) hide show
  1. package/README.md +76 -18
  2. package/dist/bin/rango.js +138 -50
  3. package/dist/vite/index.js +853 -435
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/package.json +16 -17
  6. package/skills/cache-guide/SKILL.md +32 -0
  7. package/skills/caching/SKILL.md +45 -4
  8. package/skills/handler-use/SKILL.md +362 -0
  9. package/skills/intercept/SKILL.md +20 -0
  10. package/skills/layout/SKILL.md +22 -0
  11. package/skills/links/SKILL.md +3 -1
  12. package/skills/loader/SKILL.md +53 -43
  13. package/skills/middleware/SKILL.md +34 -3
  14. package/skills/migrate-nextjs/SKILL.md +560 -0
  15. package/skills/migrate-react-router/SKILL.md +764 -0
  16. package/skills/parallel/SKILL.md +185 -0
  17. package/skills/prerender/SKILL.md +110 -68
  18. package/skills/rango/SKILL.md +24 -22
  19. package/skills/route/SKILL.md +55 -0
  20. package/skills/router-setup/SKILL.md +87 -2
  21. package/skills/typesafety/SKILL.md +10 -0
  22. package/src/__internal.ts +1 -1
  23. package/src/browser/app-version.ts +14 -0
  24. package/src/browser/event-controller.ts +5 -0
  25. package/src/browser/navigation-bridge.ts +37 -5
  26. package/src/browser/navigation-client.ts +142 -57
  27. package/src/browser/navigation-store.ts +43 -8
  28. package/src/browser/partial-update.ts +63 -22
  29. package/src/browser/prefetch/cache.ts +73 -11
  30. package/src/browser/prefetch/fetch.ts +98 -27
  31. package/src/browser/prefetch/queue.ts +92 -20
  32. package/src/browser/prefetch/resource-ready.ts +77 -0
  33. package/src/browser/react/Link.tsx +76 -9
  34. package/src/browser/react/NavigationProvider.tsx +16 -7
  35. package/src/browser/react/context.ts +7 -2
  36. package/src/browser/react/use-handle.ts +9 -58
  37. package/src/browser/react/use-router.ts +21 -8
  38. package/src/browser/rsc-router.tsx +134 -59
  39. package/src/browser/scroll-restoration.ts +21 -18
  40. package/src/browser/segment-reconciler.ts +36 -9
  41. package/src/browser/server-action-bridge.ts +8 -6
  42. package/src/browser/types.ts +27 -5
  43. package/src/build/generate-manifest.ts +6 -6
  44. package/src/build/generate-route-types.ts +3 -0
  45. package/src/build/route-trie.ts +50 -24
  46. package/src/build/route-types/include-resolution.ts +8 -1
  47. package/src/build/route-types/router-processing.ts +223 -74
  48. package/src/build/route-types/scan-filter.ts +8 -1
  49. package/src/cache/cache-runtime.ts +15 -11
  50. package/src/cache/cache-scope.ts +48 -7
  51. package/src/cache/cf/cf-cache-store.ts +453 -11
  52. package/src/cache/cf/index.ts +5 -1
  53. package/src/cache/document-cache.ts +17 -7
  54. package/src/cache/index.ts +1 -0
  55. package/src/cache/taint.ts +55 -0
  56. package/src/client.tsx +84 -230
  57. package/src/context-var.ts +72 -2
  58. package/src/debug.ts +2 -2
  59. package/src/handle.ts +40 -0
  60. package/src/index.rsc.ts +3 -1
  61. package/src/index.ts +46 -6
  62. package/src/prerender/store.ts +5 -4
  63. package/src/prerender.ts +138 -77
  64. package/src/reverse.ts +25 -1
  65. package/src/route-definition/dsl-helpers.ts +224 -37
  66. package/src/route-definition/helpers-types.ts +67 -19
  67. package/src/route-definition/index.ts +3 -0
  68. package/src/route-definition/redirect.ts +11 -3
  69. package/src/route-definition/resolve-handler-use.ts +149 -0
  70. package/src/route-types.ts +18 -0
  71. package/src/router/content-negotiation.ts +100 -1
  72. package/src/router/handler-context.ts +82 -23
  73. package/src/router/intercept-resolution.ts +9 -4
  74. package/src/router/lazy-includes.ts +7 -6
  75. package/src/router/loader-resolution.ts +156 -21
  76. package/src/router/logging.ts +1 -1
  77. package/src/router/manifest.ts +28 -15
  78. package/src/router/match-api.ts +124 -189
  79. package/src/router/match-middleware/background-revalidation.ts +30 -2
  80. package/src/router/match-middleware/cache-lookup.ts +94 -17
  81. package/src/router/match-middleware/cache-store.ts +53 -10
  82. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  83. package/src/router/match-middleware/segment-resolution.ts +60 -5
  84. package/src/router/match-result.ts +104 -10
  85. package/src/router/metrics.ts +6 -1
  86. package/src/router/middleware-types.ts +6 -8
  87. package/src/router/middleware.ts +4 -6
  88. package/src/router/navigation-snapshot.ts +182 -0
  89. package/src/router/prerender-match.ts +110 -10
  90. package/src/router/preview-match.ts +30 -102
  91. package/src/router/request-classification.ts +310 -0
  92. package/src/router/route-snapshot.ts +245 -0
  93. package/src/router/router-context.ts +1 -0
  94. package/src/router/router-interfaces.ts +36 -4
  95. package/src/router/router-options.ts +37 -11
  96. package/src/router/segment-resolution/fresh.ts +198 -20
  97. package/src/router/segment-resolution/helpers.ts +29 -24
  98. package/src/router/segment-resolution/loader-cache.ts +1 -0
  99. package/src/router/segment-resolution/revalidation.ts +433 -296
  100. package/src/router/types.ts +1 -0
  101. package/src/router.ts +55 -6
  102. package/src/rsc/handler.ts +472 -372
  103. package/src/rsc/loader-fetch.ts +23 -3
  104. package/src/rsc/manifest-init.ts +5 -1
  105. package/src/rsc/progressive-enhancement.ts +14 -2
  106. package/src/rsc/rsc-rendering.ts +10 -1
  107. package/src/rsc/server-action.ts +8 -0
  108. package/src/rsc/ssr-setup.ts +2 -2
  109. package/src/rsc/types.ts +9 -1
  110. package/src/segment-content-promise.ts +67 -0
  111. package/src/segment-loader-promise.ts +122 -0
  112. package/src/segment-system.tsx +109 -23
  113. package/src/server/context.ts +166 -17
  114. package/src/server/handle-store.ts +19 -0
  115. package/src/server/loader-registry.ts +9 -8
  116. package/src/server/request-context.ts +185 -19
  117. package/src/ssr/index.tsx +4 -0
  118. package/src/static-handler.ts +18 -6
  119. package/src/types/cache-types.ts +4 -4
  120. package/src/types/handler-context.ts +137 -33
  121. package/src/types/loader-types.ts +36 -9
  122. package/src/types/route-entry.ts +12 -1
  123. package/src/types/segments.ts +2 -0
  124. package/src/urls/include-helper.ts +24 -14
  125. package/src/urls/path-helper-types.ts +39 -6
  126. package/src/urls/path-helper.ts +48 -13
  127. package/src/urls/pattern-types.ts +12 -0
  128. package/src/urls/response-types.ts +16 -6
  129. package/src/use-loader.tsx +77 -5
  130. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  131. package/src/vite/discovery/discover-routers.ts +5 -1
  132. package/src/vite/discovery/prerender-collection.ts +128 -74
  133. package/src/vite/discovery/state.ts +13 -6
  134. package/src/vite/index.ts +4 -0
  135. package/src/vite/plugin-types.ts +51 -79
  136. package/src/vite/plugins/expose-action-id.ts +1 -3
  137. package/src/vite/plugins/expose-id-utils.ts +12 -0
  138. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  139. package/src/vite/plugins/expose-internal-ids.ts +257 -40
  140. package/src/vite/plugins/performance-tracks.ts +88 -0
  141. package/src/vite/plugins/refresh-cmd.ts +88 -26
  142. package/src/vite/plugins/version-plugin.ts +13 -1
  143. package/src/vite/rango.ts +163 -211
  144. package/src/vite/router-discovery.ts +178 -45
  145. package/src/vite/utils/banner.ts +3 -3
  146. package/src/vite/utils/prerender-utils.ts +37 -5
  147. package/src/vite/utils/shared-utils.ts +3 -2
@@ -18,6 +18,9 @@ function hashId(filePath, exportName) {
18
18
  const hash = crypto.createHash("sha256").update(input).digest("hex");
19
19
  return `${hash.slice(0, 8)}#${exportName}`;
20
20
  }
21
+ function makeStubId(filePath, exportName, isBuild) {
22
+ return isBuild ? hashId(filePath, exportName) : `${filePath}#${exportName}`;
23
+ }
21
24
  function hashInlineId(filePath, lineNumber, index) {
22
25
  const input = index !== void 0 && index > 0 ? `${filePath}:${lineNumber}:${index}` : `${filePath}:${lineNumber}`;
23
26
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
@@ -292,7 +295,7 @@ function exposeActionId() {
292
295
  }
293
296
  if (!rscPluginApi) {
294
297
  throw new Error(
295
- "[rsc-router] Could not find @vitejs/plugin-rsc. @rangojs/router requires the Vite RSC plugin.\nThe RSC plugin should be included automatically. If you disabled it with\nrango({ rsc: false }), add rsc() before rango() in your config."
298
+ "[rsc-router] Could not find @vitejs/plugin-rsc. @rangojs/router requires the Vite RSC plugin, which is included automatically by rango()."
296
299
  );
297
300
  }
298
301
  if (!isBuild) return;
@@ -910,9 +913,7 @@ function generateWholeFileStubs(cfg, bindings, code, filePath, isBuild) {
910
913
  });
911
914
  return { code: stubs.join("\n") + "\n", map: null };
912
915
  }
913
- function generateExprStubs(cfg, bindings, code, filePath, sourceId, isBuild) {
914
- if (bindings.length === 0) return null;
915
- const s = new MagicString2(code);
916
+ function stubHandlerExprs(cfg, bindings, s, filePath, isBuild) {
916
917
  let hasChanges = false;
917
918
  for (const binding of bindings) {
918
919
  const exportName = binding.exportNames[0];
@@ -924,15 +925,7 @@ function generateExprStubs(cfg, bindings, code, filePath, sourceId, isBuild) {
924
925
  );
925
926
  hasChanges = true;
926
927
  }
927
- if (!hasChanges) return null;
928
- return {
929
- code: s.toString(),
930
- map: s.generateMap({
931
- source: sourceId,
932
- includeContent: true,
933
- hires: "boundary"
934
- })
935
- };
928
+ return hasChanges;
936
929
  }
937
930
  function transformHandlerIds(cfg, bindings, s, filePath, isBuild) {
938
931
  let hasChanges = false;
@@ -1269,15 +1262,6 @@ ${lazyImports.join(",\n")}
1269
1262
  isBuild
1270
1263
  );
1271
1264
  if (wholeFile) return wholeFile;
1272
- const exprStubs = generateExprStubs(
1273
- PRERENDER_CONFIG,
1274
- bindings,
1275
- code,
1276
- filePath,
1277
- id,
1278
- isBuild
1279
- );
1280
- if (exprStubs) return exprStubs;
1281
1265
  }
1282
1266
  if (hasPrerenderHandlerCode && isRscEnv && isBuild) {
1283
1267
  const fnNames = getFnNames(PRERENDER_CONFIG.fnName);
@@ -1329,15 +1313,134 @@ ${lazyImports.join(",\n")}
1329
1313
  isBuild
1330
1314
  );
1331
1315
  if (wholeFile) return wholeFile;
1332
- const exprStubs = generateExprStubs(
1333
- STATIC_CONFIG,
1334
- bindings,
1335
- code,
1336
- filePath,
1337
- id,
1338
- isBuild
1339
- );
1340
- if (exprStubs) return exprStubs;
1316
+ }
1317
+ if (!isRscEnv && (hasPrerenderHandlerCode || hasStaticHandlerCode)) {
1318
+ const prerenderFnNames = hasPrerenderHandlerCode ? getFnNames(PRERENDER_CONFIG.fnName) : [];
1319
+ const staticFnNames = hasStaticHandlerCode ? getFnNames(STATIC_CONFIG.fnName) : [];
1320
+ const loaderFnNames = hasLoaderCode ? getFnNames("createLoader") : [];
1321
+ const handleFnNames = hasHandleCode ? getFnNames("createHandle") : [];
1322
+ const lsFnNames = hasLocationStateCode ? getFnNames("createLocationState") : [];
1323
+ const allBindings = [];
1324
+ for (const fnNames of [
1325
+ prerenderFnNames,
1326
+ staticFnNames,
1327
+ loaderFnNames,
1328
+ handleFnNames,
1329
+ lsFnNames
1330
+ ]) {
1331
+ if (fnNames.length > 0) {
1332
+ allBindings.push(...getBindings(code, fnNames));
1333
+ }
1334
+ }
1335
+ let canStubWholeFile = allBindings.length > 0 && isExportOnlyFile(code, allBindings);
1336
+ if (canStubWholeFile && (handleFnNames.length > 0 || lsFnNames.length > 0)) {
1337
+ const exportedLocals = new Set(allBindings.map((b) => b.localName));
1338
+ const strippedBindings = [];
1339
+ const localDeclPattern = /(?:^|;|\n)\s*(?:const|let|var|function)\s+(\w+)/g;
1340
+ let declMatch;
1341
+ while ((declMatch = localDeclPattern.exec(code)) !== null) {
1342
+ const name = declMatch[1];
1343
+ if (!exportedLocals.has(name) && !/^_c\d*$/.test(name)) {
1344
+ strippedBindings.push(name);
1345
+ }
1346
+ }
1347
+ const importPattern = /import\s*\{([^}]*)\}\s*from\s*["'](?!@rangojs\/router)[^"']*["']/g;
1348
+ let importMatch;
1349
+ while ((importMatch = importPattern.exec(code)) !== null) {
1350
+ for (const spec of importMatch[1].split(",")) {
1351
+ const m = spec.trim().match(/^[A-Za-z_$][\w$]*(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);
1352
+ if (m) strippedBindings.push(m[1] || m[0].trim().split(/\s/)[0]);
1353
+ }
1354
+ }
1355
+ const defaultImportPattern = /import\s+([A-Za-z_$][\w$]*)\s+from\s*["'](?!@rangojs\/router)[^"']*["']/g;
1356
+ while ((importMatch = defaultImportPattern.exec(code)) !== null) {
1357
+ strippedBindings.push(importMatch[1]);
1358
+ }
1359
+ const nsImportPattern = /import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s*["'](?!@rangojs\/router)[^"']*["']/g;
1360
+ while ((importMatch = nsImportPattern.exec(code)) !== null) {
1361
+ strippedBindings.push(importMatch[1]);
1362
+ }
1363
+ if (strippedBindings.length > 0) {
1364
+ const preservedBindings = allBindings.filter((b) => {
1365
+ const fc = code.slice(b.callExprStart, b.callOpenParenPos + 1);
1366
+ return handleFnNames.some((n) => fc.includes(n)) || lsFnNames.some((n) => fc.includes(n));
1367
+ });
1368
+ const strippedRe = new RegExp(
1369
+ `\\b(?:${strippedBindings.join("|")})\\b`
1370
+ );
1371
+ canStubWholeFile = !preservedBindings.some((b) => {
1372
+ const expr = code.slice(b.callExprStart, b.callCloseParenPos + 1);
1373
+ return strippedRe.test(expr);
1374
+ });
1375
+ }
1376
+ }
1377
+ if (canStubWholeFile) {
1378
+ const lines = [];
1379
+ const neededImports = [];
1380
+ if (handleFnNames.length > 0) neededImports.push("createHandle");
1381
+ if (lsFnNames.length > 0) neededImports.push("createLocationState");
1382
+ if (neededImports.length > 0) {
1383
+ lines.push(
1384
+ `import { ${neededImports.join(", ")} } from "@rangojs/router";`
1385
+ );
1386
+ }
1387
+ for (const binding of allBindings) {
1388
+ const fnCall = code.slice(
1389
+ binding.callExprStart,
1390
+ binding.callOpenParenPos + 1
1391
+ );
1392
+ const isHandle = handleFnNames.some((n) => fnCall.includes(n));
1393
+ const isLocationState = lsFnNames.some((n) => fnCall.includes(n));
1394
+ const primaryName = binding.exportNames[0];
1395
+ const stubId = makeStubId(filePath, primaryName, isBuild);
1396
+ if (isHandle || isLocationState) {
1397
+ const rawArgs = code.slice(binding.callOpenParenPos + 1, binding.callCloseParenPos).replace(/\b_c\d*\s*=\s*/g, "");
1398
+ const canonicalName = isHandle ? "createHandle" : "createLocationState";
1399
+ const activeFnNames = isHandle ? handleFnNames : lsFnNames;
1400
+ let rawCallee = code.slice(
1401
+ binding.callExprStart,
1402
+ binding.callOpenParenPos
1403
+ );
1404
+ for (const alias of activeFnNames) {
1405
+ if (alias !== canonicalName && rawCallee.startsWith(alias)) {
1406
+ rawCallee = canonicalName + rawCallee.slice(alias.length);
1407
+ break;
1408
+ }
1409
+ }
1410
+ if (isHandle) {
1411
+ const idParam = binding.argCount === 0 ? `undefined, "${stubId}"` : `, "${stubId}"`;
1412
+ lines.push(
1413
+ `export const ${primaryName} = ${rawCallee}(${rawArgs}${idParam});`
1414
+ );
1415
+ lines.push(`${primaryName}.$$id = "${stubId}";`);
1416
+ } else {
1417
+ lines.push(
1418
+ `export const ${primaryName} = ${rawCallee}(${rawArgs});`
1419
+ );
1420
+ lines.push(
1421
+ `${primaryName}.__rsc_ls_key = "__rsc_ls_${stubId}";`
1422
+ );
1423
+ }
1424
+ for (const name of binding.exportNames.slice(1)) {
1425
+ lines.push(`export const ${name} = ${primaryName};`);
1426
+ }
1427
+ } else {
1428
+ let brand = "loader";
1429
+ if (prerenderFnNames.some((n) => fnCall.includes(n))) {
1430
+ brand = PRERENDER_CONFIG.brand;
1431
+ } else if (staticFnNames.some((n) => fnCall.includes(n))) {
1432
+ brand = STATIC_CONFIG.brand;
1433
+ }
1434
+ lines.push(
1435
+ `export const ${primaryName} = { __brand: "${brand}", $$id: "${stubId}" };`
1436
+ );
1437
+ for (const name of binding.exportNames.slice(1)) {
1438
+ lines.push(`export const ${name} = ${primaryName};`);
1439
+ }
1440
+ }
1441
+ }
1442
+ return { code: lines.join("\n") + "\n", map: null };
1443
+ }
1341
1444
  }
1342
1445
  if (hasStaticHandlerCode && isRscEnv && isBuild) {
1343
1446
  const fnNames = getFnNames(STATIC_CONFIG.fnName);
@@ -1372,25 +1475,41 @@ ${lazyImports.join(",\n")}
1372
1475
  isBuild
1373
1476
  ) || changed;
1374
1477
  }
1375
- if (hasPrerenderHandlerCode && isRscEnv) {
1478
+ if (hasPrerenderHandlerCode) {
1376
1479
  const fnNames = getFnNames(PRERENDER_CONFIG.fnName);
1377
- changed = transformHandlerIds(
1378
- PRERENDER_CONFIG,
1379
- getBindings(code, fnNames),
1380
- s,
1381
- filePath,
1382
- isBuild
1383
- ) || changed;
1480
+ const bindings = getBindings(code, fnNames);
1481
+ if (isRscEnv) {
1482
+ changed = transformHandlerIds(
1483
+ PRERENDER_CONFIG,
1484
+ bindings,
1485
+ s,
1486
+ filePath,
1487
+ isBuild
1488
+ ) || changed;
1489
+ } else {
1490
+ changed = stubHandlerExprs(
1491
+ PRERENDER_CONFIG,
1492
+ bindings,
1493
+ s,
1494
+ filePath,
1495
+ isBuild
1496
+ ) || changed;
1497
+ }
1384
1498
  }
1385
- if (hasStaticHandlerCode && isRscEnv) {
1499
+ if (hasStaticHandlerCode) {
1386
1500
  const fnNames = getFnNames(STATIC_CONFIG.fnName);
1387
- changed = transformHandlerIds(
1388
- STATIC_CONFIG,
1389
- getBindings(code, fnNames),
1390
- s,
1391
- filePath,
1392
- isBuild
1393
- ) || changed;
1501
+ const bindings = getBindings(code, fnNames);
1502
+ if (isRscEnv) {
1503
+ changed = transformHandlerIds(
1504
+ STATIC_CONFIG,
1505
+ bindings,
1506
+ s,
1507
+ filePath,
1508
+ isBuild
1509
+ ) || changed;
1510
+ } else {
1511
+ changed = stubHandlerExprs(STATIC_CONFIG, bindings, s, filePath, isBuild) || changed;
1512
+ }
1394
1513
  }
1395
1514
  if (!changed) return;
1396
1515
  return {
@@ -1745,7 +1864,7 @@ import { resolve } from "node:path";
1745
1864
  // package.json
1746
1865
  var package_default = {
1747
1866
  name: "@rangojs/router",
1748
- version: "0.0.0-experimental.78a48627",
1867
+ version: "0.0.0-experimental.79",
1749
1868
  description: "Django-inspired RSC router with composable URL patterns",
1750
1869
  keywords: [
1751
1870
  "react",
@@ -1887,7 +2006,7 @@ var package_default = {
1887
2006
  "test:unit:watch": "vitest"
1888
2007
  },
1889
2008
  dependencies: {
1890
- "@vitejs/plugin-rsc": "^0.5.14",
2009
+ "@vitejs/plugin-rsc": "^0.5.23",
1891
2010
  "magic-string": "^0.30.17",
1892
2011
  picomatch: "^4.0.3",
1893
2012
  "rsc-html-stream": "^0.0.7"
@@ -1907,7 +2026,7 @@ var package_default = {
1907
2026
  },
1908
2027
  peerDependencies: {
1909
2028
  "@cloudflare/vite-plugin": "^1.25.0",
1910
- "@vitejs/plugin-rsc": "^0.5.14",
2029
+ "@vitejs/plugin-rsc": "^0.5.23",
1911
2030
  react: "^18.0.0 || ^19.0.0",
1912
2031
  vite: "^7.3.0"
1913
2032
  },
@@ -2095,31 +2214,7 @@ declare global {
2095
2214
  }
2096
2215
 
2097
2216
  // src/build/route-types/scan-filter.ts
2098
- import { join, relative } from "node:path";
2099
2217
  import picomatch from "picomatch";
2100
- var DEFAULT_EXCLUDE_PATTERNS = [
2101
- "**/__tests__/**",
2102
- "**/__mocks__/**",
2103
- "**/dist/**",
2104
- "**/coverage/**",
2105
- "**/*.test.{ts,tsx,js,jsx}",
2106
- "**/*.spec.{ts,tsx,js,jsx}"
2107
- ];
2108
- function createScanFilter(root, opts) {
2109
- const { include, exclude } = opts;
2110
- const hasInclude = include && include.length > 0;
2111
- const hasCustomExclude = exclude !== void 0;
2112
- if (!hasInclude && !hasCustomExclude) return void 0;
2113
- const effectiveExclude = exclude ?? DEFAULT_EXCLUDE_PATTERNS;
2114
- const includeMatcher = hasInclude ? picomatch(include) : null;
2115
- const excludeMatcher = effectiveExclude.length > 0 ? picomatch(effectiveExclude) : null;
2116
- return (absolutePath) => {
2117
- const rel = relative(root, absolutePath);
2118
- if (excludeMatcher && excludeMatcher(rel)) return false;
2119
- if (includeMatcher) return includeMatcher(rel);
2120
- return true;
2121
- };
2122
- }
2123
2218
 
2124
2219
  // src/build/route-types/per-module-writer.ts
2125
2220
  import ts4 from "typescript";
@@ -2341,7 +2436,7 @@ function buildRouteMapFromBlock(block, fullSource, filePath, visited, searchSche
2341
2436
  }
2342
2437
  return routeMap;
2343
2438
  }
2344
- function buildCombinedRouteMapWithSearch(filePath, variableName, visited, diagnosticsOut) {
2439
+ function buildCombinedRouteMapWithSearch(filePath, variableName, visited, diagnosticsOut, inlineBlock) {
2345
2440
  visited = visited ?? /* @__PURE__ */ new Set();
2346
2441
  const realPath = resolve2(filePath);
2347
2442
  const key = variableName ? `${realPath}:${variableName}` : realPath;
@@ -2357,7 +2452,9 @@ function buildCombinedRouteMapWithSearch(filePath, variableName, visited, diagno
2357
2452
  return { routes: {}, searchSchemas: {} };
2358
2453
  }
2359
2454
  let block;
2360
- if (variableName) {
2455
+ if (inlineBlock) {
2456
+ block = inlineBlock;
2457
+ } else if (variableName) {
2361
2458
  const extracted = extractUrlsBlockForVariable(source, variableName);
2362
2459
  if (!extracted) return { routes: {}, searchSchemas: {} };
2363
2460
  block = extracted;
@@ -2386,7 +2483,7 @@ import {
2386
2483
  readdirSync
2387
2484
  } from "node:fs";
2388
2485
  import {
2389
- join as join2,
2486
+ join,
2390
2487
  dirname as dirname2,
2391
2488
  resolve as resolve3,
2392
2489
  sep,
@@ -2406,7 +2503,7 @@ function countPublicRouteEntries(source) {
2406
2503
  }
2407
2504
  var ROUTER_CALL_PATTERN = /\bcreateRouter\s*[<(]/;
2408
2505
  function isRoutableSourceFile(name) {
2409
- return (name.endsWith(".ts") || name.endsWith(".tsx") || name.endsWith(".js") || name.endsWith(".jsx")) && !name.includes(".gen.");
2506
+ return (name.endsWith(".ts") || name.endsWith(".tsx") || name.endsWith(".js") || name.endsWith(".jsx")) && !name.includes(".gen.") && !name.includes(".test.") && !name.includes(".spec.");
2410
2507
  }
2411
2508
  function findRouterFilesRecursive(dir, filter, results) {
2412
2509
  let entries;
@@ -2421,9 +2518,10 @@ function findRouterFilesRecursive(dir, filter, results) {
2421
2518
  const childDirs = [];
2422
2519
  const routerFilesInDir = [];
2423
2520
  for (const entry of entries) {
2424
- const fullPath = join2(dir, entry.name);
2521
+ const fullPath = join(dir, entry.name);
2425
2522
  if (entry.isDirectory()) {
2426
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
2523
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === "coverage" || entry.name === "__tests__" || entry.name === "__mocks__" || entry.name.startsWith("."))
2524
+ continue;
2427
2525
  childDirs.push(fullPath);
2428
2526
  continue;
2429
2527
  }
@@ -2475,7 +2573,7 @@ Router root: ${conflict.ancestor}
2475
2573
  Nested router: ${conflict.nested}
2476
2574
  Move the nested router into a sibling directory or configure it as a separate app root.`;
2477
2575
  }
2478
- function extractUrlsVariableFromRouter(code) {
2576
+ function extractUrlsFromRouter(code) {
2479
2577
  const sourceFile = ts5.createSourceFile(
2480
2578
  "router.tsx",
2481
2579
  code,
@@ -2489,24 +2587,70 @@ function extractUrlsVariableFromRouter(code) {
2489
2587
  const callee = node.expression;
2490
2588
  return ts5.isIdentifier(callee) && callee.text === "createRouter";
2491
2589
  }
2590
+ function isInlineBuilder(node) {
2591
+ return ts5.isArrowFunction(node) || ts5.isFunctionExpression(node);
2592
+ }
2593
+ function isRoutesOnCreateRouter(node) {
2594
+ if (!ts5.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "routes")
2595
+ return false;
2596
+ let inner = node.expression.expression;
2597
+ while (ts5.isCallExpression(inner) && ts5.isPropertyAccessExpression(inner.expression)) {
2598
+ inner = inner.expression.expression;
2599
+ }
2600
+ return isCreateRouterCall(inner);
2601
+ }
2492
2602
  function visit(node) {
2493
2603
  if (result) return;
2494
- if (ts5.isCallExpression(node) && ts5.isPropertyAccessExpression(node.expression) && node.expression.name.text === "routes" && node.arguments.length >= 1 && ts5.isIdentifier(node.arguments[0])) {
2495
- let inner = node.expression.expression;
2496
- while (ts5.isCallExpression(inner) && ts5.isPropertyAccessExpression(inner.expression)) {
2497
- inner = inner.expression.expression;
2498
- }
2499
- if (isCreateRouterCall(inner)) {
2500
- result = node.arguments[0].text;
2501
- return;
2604
+ if (ts5.isCallExpression(node) && node.arguments.length >= 1 && isRoutesOnCreateRouter(node)) {
2605
+ const arg = node.arguments[0];
2606
+ if (ts5.isIdentifier(arg)) {
2607
+ result = { kind: "variable", name: arg.text };
2608
+ } else if (isInlineBuilder(arg)) {
2609
+ result = { kind: "inline", block: arg.getText(sourceFile) };
2502
2610
  }
2611
+ return;
2503
2612
  }
2504
2613
  if (isCreateRouterCall(node)) {
2505
2614
  const callExpr = node;
2506
- for (const arg of callExpr.arguments) {
2615
+ for (const callArg of callExpr.arguments) {
2616
+ if (ts5.isObjectLiteralExpression(callArg)) {
2617
+ for (const prop of callArg.properties) {
2618
+ if (ts5.isPropertyAssignment(prop) && ts5.isIdentifier(prop.name) && prop.name.text === "urls") {
2619
+ if (ts5.isIdentifier(prop.initializer)) {
2620
+ result = { kind: "variable", name: prop.initializer.text };
2621
+ } else if (isInlineBuilder(prop.initializer)) {
2622
+ result = {
2623
+ kind: "inline",
2624
+ block: prop.initializer.getText(sourceFile)
2625
+ };
2626
+ }
2627
+ return;
2628
+ }
2629
+ }
2630
+ }
2631
+ }
2632
+ }
2633
+ ts5.forEachChild(node, visit);
2634
+ }
2635
+ visit(sourceFile);
2636
+ return result;
2637
+ }
2638
+ function extractBasenameFromRouter(code) {
2639
+ const sourceFile = ts5.createSourceFile(
2640
+ "router.tsx",
2641
+ code,
2642
+ ts5.ScriptTarget.Latest,
2643
+ true,
2644
+ ts5.ScriptKind.TSX
2645
+ );
2646
+ let result;
2647
+ function visit(node) {
2648
+ if (result !== void 0) return;
2649
+ if (ts5.isCallExpression(node) && ts5.isIdentifier(node.expression) && node.expression.text === "createRouter") {
2650
+ for (const arg of node.arguments) {
2507
2651
  if (ts5.isObjectLiteralExpression(arg)) {
2508
2652
  for (const prop of arg.properties) {
2509
- if (ts5.isPropertyAssignment(prop) && ts5.isIdentifier(prop.name) && prop.name.text === "urls" && ts5.isIdentifier(prop.initializer)) {
2653
+ if (ts5.isPropertyAssignment(prop) && ts5.isIdentifier(prop.name) && prop.name.text === "basename" && ts5.isStringLiteral(prop.initializer)) {
2510
2654
  result = prop.initializer.text;
2511
2655
  return;
2512
2656
  }
@@ -2519,6 +2663,19 @@ function extractUrlsVariableFromRouter(code) {
2519
2663
  visit(sourceFile);
2520
2664
  return result;
2521
2665
  }
2666
+ function applyBasenameToRoutes(result, basename3) {
2667
+ const prefixed = {};
2668
+ for (const [name, pattern] of Object.entries(result.routes)) {
2669
+ if (pattern === "/") {
2670
+ prefixed[name] = basename3;
2671
+ } else if (basename3.endsWith("/") && pattern.startsWith("/")) {
2672
+ prefixed[name] = basename3 + pattern.slice(1);
2673
+ } else {
2674
+ prefixed[name] = basename3 + pattern;
2675
+ }
2676
+ }
2677
+ return { routes: prefixed, searchSchemas: result.searchSchemas };
2678
+ }
2522
2679
  function buildCombinedRouteMapForRouterFile(routerFilePath) {
2523
2680
  let routerSource;
2524
2681
  try {
@@ -2526,19 +2683,40 @@ function buildCombinedRouteMapForRouterFile(routerFilePath) {
2526
2683
  } catch {
2527
2684
  return { routes: {}, searchSchemas: {} };
2528
2685
  }
2529
- const urlsVarName = extractUrlsVariableFromRouter(routerSource);
2530
- if (!urlsVarName) {
2686
+ const extraction = extractUrlsFromRouter(routerSource);
2687
+ if (!extraction) {
2531
2688
  return { routes: {}, searchSchemas: {} };
2532
2689
  }
2533
- const imported = resolveImportedVariable(routerSource, urlsVarName);
2534
- if (imported) {
2535
- const targetFile = resolveImportPath(imported.specifier, routerFilePath);
2536
- if (!targetFile) {
2537
- return { routes: {}, searchSchemas: {} };
2690
+ const rawBasename = extractBasenameFromRouter(routerSource);
2691
+ const basename3 = rawBasename ? ("/" + rawBasename.replace(/^\/+|\/+$/g, "")).replace(/^\/$/, "") : void 0;
2692
+ let result;
2693
+ if (extraction.kind === "inline") {
2694
+ result = buildCombinedRouteMapWithSearch(
2695
+ routerFilePath,
2696
+ void 0,
2697
+ void 0,
2698
+ void 0,
2699
+ extraction.block
2700
+ );
2701
+ } else {
2702
+ const imported = resolveImportedVariable(routerSource, extraction.name);
2703
+ if (imported) {
2704
+ const targetFile = resolveImportPath(imported.specifier, routerFilePath);
2705
+ if (!targetFile) {
2706
+ return { routes: {}, searchSchemas: {} };
2707
+ }
2708
+ result = buildCombinedRouteMapWithSearch(
2709
+ targetFile,
2710
+ imported.exportedName
2711
+ );
2712
+ } else {
2713
+ result = buildCombinedRouteMapWithSearch(routerFilePath, extraction.name);
2538
2714
  }
2539
- return buildCombinedRouteMapWithSearch(targetFile, imported.exportedName);
2540
2715
  }
2541
- return buildCombinedRouteMapWithSearch(routerFilePath, urlsVarName);
2716
+ if (basename3) {
2717
+ result = applyBasenameToRoutes(result, basename3);
2718
+ }
2719
+ return result;
2542
2720
  }
2543
2721
  function findRouterFiles(root, filter) {
2544
2722
  const result = [];
@@ -2547,7 +2725,7 @@ function findRouterFiles(root, filter) {
2547
2725
  }
2548
2726
  function writeCombinedRouteTypes(root, knownRouterFiles, opts) {
2549
2727
  try {
2550
- const oldCombinedPath = join2(root, "src", "named-routes.gen.ts");
2728
+ const oldCombinedPath = join(root, "src", "named-routes.gen.ts");
2551
2729
  if (existsSync3(oldCombinedPath)) {
2552
2730
  unlinkSync(oldCombinedPath);
2553
2731
  console.log(
@@ -2563,31 +2741,21 @@ function writeCombinedRouteTypes(root, knownRouterFiles, opts) {
2563
2741
  throw new Error(formatNestedRouterConflictError(nestedRouterConflict));
2564
2742
  }
2565
2743
  for (const routerFilePath of routerFilePaths) {
2566
- let routerSource;
2567
- try {
2568
- routerSource = readFileSync2(routerFilePath, "utf-8");
2569
- } catch {
2570
- continue;
2571
- }
2572
- const urlsVarName = extractUrlsVariableFromRouter(routerSource);
2573
- if (!urlsVarName) continue;
2574
- let result;
2575
- const imported = resolveImportedVariable(routerSource, urlsVarName);
2576
- if (imported) {
2577
- const targetFile = resolveImportPath(imported.specifier, routerFilePath);
2578
- if (!targetFile) continue;
2579
- result = buildCombinedRouteMapWithSearch(
2580
- targetFile,
2581
- imported.exportedName
2582
- );
2583
- } else {
2584
- result = buildCombinedRouteMapWithSearch(routerFilePath, urlsVarName);
2744
+ const result = buildCombinedRouteMapForRouterFile(routerFilePath);
2745
+ if (Object.keys(result.routes).length === 0 && Object.keys(result.searchSchemas).length === 0) {
2746
+ let routerSource;
2747
+ try {
2748
+ routerSource = readFileSync2(routerFilePath, "utf-8");
2749
+ } catch {
2750
+ continue;
2751
+ }
2752
+ if (!extractUrlsFromRouter(routerSource)) continue;
2585
2753
  }
2586
2754
  const routerBasename = pathBasename(routerFilePath).replace(
2587
2755
  /\.(tsx?|jsx?)$/,
2588
2756
  ""
2589
2757
  );
2590
- const outPath = join2(
2758
+ const outPath = join(
2591
2759
  dirname2(routerFilePath),
2592
2760
  `${routerBasename}.named-routes.gen.ts`
2593
2761
  );
@@ -2717,8 +2885,9 @@ function createVersionPlugin() {
2717
2885
  let isDev = false;
2718
2886
  let server = null;
2719
2887
  const clientModuleSignatures = /* @__PURE__ */ new Map();
2888
+ let versionCounter = 0;
2720
2889
  const bumpVersion = (reason) => {
2721
- currentVersion = Date.now().toString(16);
2890
+ currentVersion = Date.now().toString(16) + String(++versionCounter);
2722
2891
  console.log(`[rsc-router] ${reason}, version updated: ${currentVersion}`);
2723
2892
  const rscEnv = server?.environments?.rsc;
2724
2893
  const versionMod = rscEnv?.moduleGraph?.getModuleById(
@@ -2774,6 +2943,9 @@ function createVersionPlugin() {
2774
2943
  if (!isDev) return;
2775
2944
  const isRscModule = this.environment?.name === "rsc";
2776
2945
  if (!isRscModule) return;
2946
+ if (ctx.modules.length === 1 && ctx.modules[0].id === "\0" + VIRTUAL_IDS.version) {
2947
+ return;
2948
+ }
2777
2949
  if (isCodeModule(ctx.file)) {
2778
2950
  const filePath = normalizeModuleId(ctx.file);
2779
2951
  const previousSignature = clientModuleSignatures.get(filePath);
@@ -2803,6 +2975,68 @@ function createVersionPlugin() {
2803
2975
 
2804
2976
  // src/vite/utils/shared-utils.ts
2805
2977
  import * as Vite from "vite";
2978
+
2979
+ // src/vite/plugins/performance-tracks.ts
2980
+ import { readFile } from "node:fs/promises";
2981
+ var RSDW_PATCH_RE = /((?:var|let|const)\s+\w+\s*=\s*root\._children\s*,\s*(\w+)\s*=\s*root\._debugInfo\s*[;,])/;
2982
+ function buildPatchReplacement(match, debugInfoVar) {
2983
+ return `${match}
2984
+ if (${debugInfoVar} && 0 === ${debugInfoVar}.length && "fulfilled" === root.status) {
2985
+ var _resolved = "function" === typeof resolveLazy ? resolveLazy(root.value) : root.value;
2986
+ if ("object" === typeof _resolved && null !== _resolved && isArrayImpl(_resolved._debugInfo)) {
2987
+ ${debugInfoVar} = _resolved._debugInfo;
2988
+ }
2989
+ }`;
2990
+ }
2991
+ function patchRsdwClientDebugInfoRecovery(code) {
2992
+ const match = code.match(RSDW_PATCH_RE);
2993
+ if (!match) {
2994
+ return { code, debugInfoVar: null };
2995
+ }
2996
+ return {
2997
+ code: code.replace(match[1], buildPatchReplacement(match[1], match[2])),
2998
+ debugInfoVar: match[2]
2999
+ };
3000
+ }
3001
+ function performanceTracksOptimizeDepsPlugin() {
3002
+ return {
3003
+ name: "@rangojs/router:performance-tracks-optimize-deps",
3004
+ setup(build) {
3005
+ build.onLoad(
3006
+ {
3007
+ filter: /react-server-dom-webpack-client\.browser\.(development|production)\.js$/
3008
+ },
3009
+ async (args) => {
3010
+ const code = await readFile(args.path, "utf8");
3011
+ const patched = patchRsdwClientDebugInfoRecovery(code);
3012
+ return {
3013
+ contents: patched.code,
3014
+ loader: "js"
3015
+ };
3016
+ }
3017
+ );
3018
+ }
3019
+ };
3020
+ }
3021
+ function performanceTracksPlugin() {
3022
+ return {
3023
+ name: "@rangojs/router:performance-tracks",
3024
+ transform(code, id) {
3025
+ if (!id.includes("react-server-dom") || !id.includes("client")) return;
3026
+ const patched = patchRsdwClientDebugInfoRecovery(code);
3027
+ if (!patched.debugInfoVar) return;
3028
+ if (process.env.INTERNAL_RANGO_DEBUG)
3029
+ console.log(
3030
+ "[perf-tracks] patched RSDW client (var:",
3031
+ patched.debugInfoVar,
3032
+ ")"
3033
+ );
3034
+ return patched.code;
3035
+ }
3036
+ };
3037
+ }
3038
+
3039
+ // src/vite/utils/shared-utils.ts
2806
3040
  var versionEsbuildPlugin = {
2807
3041
  name: "@rangojs/router-version",
2808
3042
  setup(build) {
@@ -2820,7 +3054,7 @@ var versionEsbuildPlugin = {
2820
3054
  }
2821
3055
  };
2822
3056
  var sharedEsbuildOptions = {
2823
- plugins: [versionEsbuildPlugin]
3057
+ plugins: [versionEsbuildPlugin, performanceTracksOptimizeDepsPlugin()]
2824
3058
  };
2825
3059
  function createVirtualEntriesPlugin(entries, routerPathRef) {
2826
3060
  const virtualModules = {};
@@ -2903,11 +3137,11 @@ ${dim} \u2571${reset} ${bold}\u2554\u2550\u2557${reset}${dim} * \u2
2903
3137
  ${dim} ${reset}${bold}\u2551 \u2551${reset} ${bold}\u2554\u2550\u2557${reset}${dim} * \u2727. \u2571${reset}
2904
3138
  ${dim} ${reset}${bold}\u2554\u2557 \u2551 \u2551 \u2551 \u2551${reset}${dim} * \u2571${reset}
2905
3139
  ${dim} ${reset}${bold}\u2551\u2551 \u2551 \u2551 \u2551 \u2551 \u2566\u2550\u2557\u2554\u2550\u2557\u2554\u2557\u2554\u2554\u2550\u2557\u2554\u2550\u2557${reset}${dim} \u2727 \u2726${reset}
2906
- ${dim} ${reset}${bold}\u2550\u2563\u2551 \u2551 \u2560\u2550\u255D \u2551 \u2560\u2566\u255D\u2560\u2550\u2563\u2551\u2551\u2551\u2551 \u2566\u2551 \u2551${reset}${dim} * \u2727${reset}
3140
+ ${dim} ${reset}${bold}\u2551\u2551 \u2551 \u2560\u2550\u255D \u2551 \u2560\u2566\u255D\u2560\u2550\u2563\u2551\u2551\u2551\u2551 \u2566\u2551 \u2551${reset}${dim} * \u2727${reset}
2907
3141
  ${dim} ${reset}${bold}\u2551\u255A\u2550\u255D \u2554\u2550\u2550\u2550\u255D \u2569\u255A\u2550\u2569 \u2569\u255D\u255A\u255D\u255A\u2550\u255D\u255A\u2550\u255D${reset}${dim} \u2726 . *${reset}
2908
3142
  ${dim} ${reset}${bold}\u255A\u2550\u2550\u2557 \u2551${reset}${dim} * RSC Wrangler \u2727 \u2726${reset}
2909
- ${dim} * ${reset}${bold}\u2551 \u2560\u2550${reset}${dim} * \u2727. \u2571${reset}
2910
- ${bold}\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550${reset}${dim} \u2726 *${reset}
3143
+ ${dim} * ${reset}${bold}\u2551 \u2551${reset}${dim} * \u2727. \u2571${reset}
3144
+ ${dim} ${reset}${bold}\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550${reset}${dim} \u2726 *${reset}
2911
3145
 
2912
3146
  v${version} \xB7 ${preset} \xB7 ${mode}
2913
3147
  `;
@@ -3026,6 +3260,8 @@ function createCjsToEsmPlugin() {
3026
3260
  import { createServer as createViteServer } from "vite";
3027
3261
  import { resolve as resolve8 } from "node:path";
3028
3262
  import { readFileSync as readFileSync6 } from "node:fs";
3263
+ import { createRequire } from "node:module";
3264
+ import { pathToFileURL } from "node:url";
3029
3265
 
3030
3266
  // src/vite/plugins/virtual-stub-plugin.ts
3031
3267
  function createVirtualStubPlugin() {
@@ -3052,7 +3288,7 @@ function createVirtualStubPlugin() {
3052
3288
  }
3053
3289
 
3054
3290
  // src/vite/plugins/client-ref-hashing.ts
3055
- import { relative as relative2 } from "node:path";
3291
+ import { relative } from "node:path";
3056
3292
  import { createHash as createHash2 } from "node:crypto";
3057
3293
  var CLIENT_PKG_PROXY_PREFIX = "/@id/__x00__virtual:vite-rsc/client-package-proxy/";
3058
3294
  var CLIENT_IN_SERVER_PKG_PROXY_PREFIX = "/@id/__x00__virtual:vite-rsc/client-in-server-package-proxy/";
@@ -3065,10 +3301,10 @@ function computeProductionHash(projectRoot, refKey) {
3065
3301
  const absPath = decodeURIComponent(
3066
3302
  refKey.slice(CLIENT_IN_SERVER_PKG_PROXY_PREFIX.length)
3067
3303
  );
3068
- toHash = relative2(projectRoot, absPath).replaceAll("\\", "/");
3304
+ toHash = relative(projectRoot, absPath).replaceAll("\\", "/");
3069
3305
  } else if (refKey.startsWith(FS_PREFIX)) {
3070
3306
  const absPath = refKey.slice(FS_PREFIX.length - 1);
3071
- toHash = relative2(projectRoot, absPath).replaceAll("\\", "/");
3307
+ toHash = relative(projectRoot, absPath).replaceAll("\\", "/");
3072
3308
  } else if (refKey.startsWith("/")) {
3073
3309
  toHash = refKey.slice(1);
3074
3310
  } else {
@@ -3209,8 +3445,8 @@ function createDiscoveryState(entryPath, opts) {
3209
3445
  perRouterManifestDataMap: /* @__PURE__ */ new Map(),
3210
3446
  prerenderManifestEntries: null,
3211
3447
  staticManifestEntries: null,
3212
- handlerChunkInfo: null,
3213
- staticHandlerChunkInfo: null,
3448
+ handlerChunkInfoMap: /* @__PURE__ */ new Map(),
3449
+ staticHandlerChunkInfoMap: /* @__PURE__ */ new Map(),
3214
3450
  rscEntryFileName: null,
3215
3451
  resolvedPrerenderModules: void 0,
3216
3452
  resolvedStaticModules: void 0,
@@ -3293,8 +3529,17 @@ function jsonParseExpression(value) {
3293
3529
  }
3294
3530
 
3295
3531
  // src/context-var.ts
3532
+ var NON_CACHEABLE_KEYS = /* @__PURE__ */ Symbol.for(
3533
+ "rango:non-cacheable-keys"
3534
+ );
3535
+ function getNonCacheableKeys(variables) {
3536
+ if (!variables[NON_CACHEABLE_KEYS]) {
3537
+ variables[NON_CACHEABLE_KEYS] = /* @__PURE__ */ new Set();
3538
+ }
3539
+ return variables[NON_CACHEABLE_KEYS];
3540
+ }
3296
3541
  var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
3297
- function contextSet(variables, keyOrVar, value) {
3542
+ function contextSet(variables, keyOrVar, value, options) {
3298
3543
  if (typeof keyOrVar === "string") {
3299
3544
  if (FORBIDDEN_KEYS.has(keyOrVar)) {
3300
3545
  throw new Error(
@@ -3302,8 +3547,14 @@ function contextSet(variables, keyOrVar, value) {
3302
3547
  );
3303
3548
  }
3304
3549
  variables[keyOrVar] = value;
3550
+ if (options?.cache === false) {
3551
+ getNonCacheableKeys(variables).add(keyOrVar);
3552
+ }
3305
3553
  } else {
3306
3554
  variables[keyOrVar.key] = value;
3555
+ if (options?.cache === false) {
3556
+ getNonCacheableKeys(variables).add(keyOrVar.key);
3557
+ }
3307
3558
  }
3308
3559
  }
3309
3560
 
@@ -3326,13 +3577,31 @@ function encodePathParam(value) {
3326
3577
  }
3327
3578
  function substituteRouteParams(pattern, params, encode = encodeURIComponent) {
3328
3579
  let result = pattern;
3580
+ let hadOmittedOptional = false;
3329
3581
  for (const [key, value] of Object.entries(params)) {
3330
3582
  const escaped = escapeRegExp2(key);
3331
- result = result.replace(
3332
- new RegExp(`:${escaped}(\\([^)]*\\))?\\??`),
3333
- encode(value)
3334
- );
3335
- result = result.replace(`*${key}`, encode(value));
3583
+ if (value === "") {
3584
+ result = result.replace(
3585
+ new RegExp(`:${escaped}(\\([^)]*\\))?(?!\\?)`),
3586
+ ""
3587
+ );
3588
+ result = result.replace(`*${key}`, "");
3589
+ } else {
3590
+ result = result.replace(
3591
+ new RegExp(`:${escaped}(\\([^)]*\\))?\\??`),
3592
+ encode(value)
3593
+ );
3594
+ result = result.replace(`*${key}`, encode(value));
3595
+ }
3596
+ }
3597
+ result = result.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)(\([^)]*\))?\?/g, () => {
3598
+ hadOmittedOptional = true;
3599
+ return "";
3600
+ });
3601
+ if (hadOmittedOptional) {
3602
+ const hadTrailingSlash = pattern.length > 1 && pattern.endsWith("/");
3603
+ result = result.replace(/\/\/+/g, "/").replace(/\/+$/, "") || "/";
3604
+ if (hadTrailingSlash && !result.endsWith("/")) result += "/";
3336
3605
  }
3337
3606
  return result;
3338
3607
  }
@@ -3442,84 +3711,126 @@ async function expandPrerenderRoutes(state, rscEnv, registry, allManifests) {
3442
3711
  if (!params) return pattern;
3443
3712
  return substituteRouteParams(pattern, params);
3444
3713
  };
3714
+ let resolvedRoutes = 0;
3715
+ let totalDynamic = 0;
3445
3716
  for (const { manifest } of allManifests) {
3446
3717
  if (!manifest.prerenderRoutes) continue;
3447
- const defs = manifest._prerenderDefs || {};
3448
3718
  for (const routeName of manifest.prerenderRoutes) {
3449
3719
  const pattern = manifest.routeManifest[routeName];
3450
- if (!pattern) continue;
3451
- const def = defs[routeName];
3452
- const isPassthroughRoute = !!def?.options?.passthrough;
3453
- const hasDynamic = pattern.includes(":") || pattern.includes("*");
3454
- if (!hasDynamic) {
3455
- entries.push({
3456
- urlPath: pattern.replace(/\/$/, "") || "/",
3457
- routeName,
3458
- concurrency: 1,
3459
- isPassthroughRoute
3460
- });
3461
- } else {
3462
- if (def?.getParams) {
3463
- try {
3464
- const buildVars = {};
3465
- const getParamsCtx = {
3466
- build: true,
3467
- set: ((keyOrVar, value) => {
3468
- contextSet(buildVars, keyOrVar, value);
3469
- }),
3470
- reverse: getParamsReverse
3471
- };
3472
- const paramsList = await def.getParams(getParamsCtx);
3473
- const concurrency = def.options?.concurrency ?? 1;
3474
- const hasBuildVars = Object.keys(buildVars).length > 0 || Object.getOwnPropertySymbols(buildVars).length > 0;
3475
- for (const params of paramsList) {
3476
- let url = substituteRouteParams(
3477
- pattern,
3478
- params,
3479
- encodePathParam
3480
- );
3481
- if (url.includes("*")) {
3482
- const wildcardValue = params["*"] ?? params.splat;
3483
- if (wildcardValue !== void 0) {
3484
- url = url.replace(/\*[^/]*$/, encodePathParam(wildcardValue));
3720
+ if (pattern && (pattern.includes(":") || pattern.includes("*"))) {
3721
+ totalDynamic++;
3722
+ }
3723
+ }
3724
+ }
3725
+ const paramsStart = performance.now();
3726
+ const progressInterval = totalDynamic > 0 ? setInterval(() => {
3727
+ const elapsed = ((performance.now() - paramsStart) / 1e3).toFixed(1);
3728
+ console.log(
3729
+ `[rsc-router] Resolving prerender params... ${resolvedRoutes}/${totalDynamic} routes (${elapsed}s)`
3730
+ );
3731
+ }, 5e3) : void 0;
3732
+ try {
3733
+ for (const { manifest } of allManifests) {
3734
+ if (!manifest.prerenderRoutes) continue;
3735
+ const defs = manifest._prerenderDefs || {};
3736
+ const passthroughSet = new Set(manifest.passthroughRoutes || []);
3737
+ for (const routeName of manifest.prerenderRoutes) {
3738
+ const pattern = manifest.routeManifest[routeName];
3739
+ if (!pattern) continue;
3740
+ const def = defs[routeName];
3741
+ const isPassthroughRoute = passthroughSet.has(routeName);
3742
+ const hasDynamic = pattern.includes(":") || pattern.includes("*");
3743
+ if (!hasDynamic) {
3744
+ entries.push({
3745
+ urlPath: pattern.replace(/\/$/, "") || "/",
3746
+ routeName,
3747
+ concurrency: 1,
3748
+ isPassthroughRoute
3749
+ });
3750
+ } else {
3751
+ if (def?.getParams) {
3752
+ try {
3753
+ const buildVars = {};
3754
+ const buildEnv = state.resolvedBuildEnv;
3755
+ const getParamsCtx = {
3756
+ build: true,
3757
+ dev: !state.isBuildMode,
3758
+ set: ((keyOrVar, value) => {
3759
+ contextSet(buildVars, keyOrVar, value);
3760
+ }),
3761
+ reverse: getParamsReverse,
3762
+ get env() {
3763
+ if (buildEnv !== void 0) return buildEnv;
3764
+ throw new Error(
3765
+ "[rsc-router] ctx.env is not available during build-time getParams(). Configure buildEnv in your rango() plugin options to enable build-time env access."
3766
+ );
3485
3767
  }
3768
+ };
3769
+ const paramsList = await def.getParams(getParamsCtx);
3770
+ const concurrency = def.options?.concurrency ?? 1;
3771
+ const hasBuildVars = Object.keys(buildVars).length > 0 || Object.getOwnPropertySymbols(buildVars).length > 0;
3772
+ for (const params of paramsList) {
3773
+ let url = substituteRouteParams(
3774
+ pattern,
3775
+ params,
3776
+ encodePathParam
3777
+ );
3778
+ if (url.includes("*")) {
3779
+ const wildcardValue = params["*"] ?? params.splat;
3780
+ if (wildcardValue !== void 0) {
3781
+ url = url.replace(
3782
+ /\*[^/]*$/,
3783
+ encodePathParam(wildcardValue)
3784
+ );
3785
+ }
3786
+ }
3787
+ entries.push({
3788
+ urlPath: url.replace(/\/$/, "") || "/",
3789
+ routeName,
3790
+ concurrency,
3791
+ ...hasBuildVars ? { buildVars } : {},
3792
+ isPassthroughRoute
3793
+ });
3486
3794
  }
3487
- entries.push({
3488
- urlPath: url.replace(/\/$/, "") || "/",
3489
- routeName,
3490
- concurrency,
3491
- ...hasBuildVars ? { buildVars } : {},
3492
- isPassthroughRoute
3493
- });
3494
- }
3495
- } catch (err) {
3496
- if (err.name === "Skip") {
3497
- console.log(
3498
- `[rsc-router] SKIP route "${routeName}" - ${err.message}`
3499
- );
3500
- notifyOnError(
3501
- registry,
3502
- err,
3503
- "prerender",
3504
- routeName,
3505
- void 0,
3506
- true
3795
+ resolvedRoutes++;
3796
+ } catch (err) {
3797
+ resolvedRoutes++;
3798
+ if (err.name === "Skip") {
3799
+ console.log(
3800
+ `[rsc-router] SKIP route "${routeName}" - ${err.message}`
3801
+ );
3802
+ notifyOnError(
3803
+ registry,
3804
+ err,
3805
+ "prerender",
3806
+ routeName,
3807
+ void 0,
3808
+ true
3809
+ );
3810
+ continue;
3811
+ }
3812
+ console.error(
3813
+ `[rsc-router] Failed to get params for prerender route "${routeName}": ${err.message}`
3507
3814
  );
3508
- continue;
3815
+ notifyOnError(registry, err, "prerender", routeName);
3816
+ throw err;
3509
3817
  }
3510
- console.error(
3511
- `[rsc-router] Failed to get params for prerender route "${routeName}": ${err.message}`
3818
+ } else {
3819
+ console.warn(
3820
+ `[rsc-router] Dynamic prerender route "${routeName}" has no getParams(), skipping`
3512
3821
  );
3513
- notifyOnError(registry, err, "prerender", routeName);
3514
- throw err;
3515
3822
  }
3516
- } else {
3517
- console.warn(
3518
- `[rsc-router] Dynamic prerender route "${routeName}" has no getParams(), skipping`
3519
- );
3520
3823
  }
3521
3824
  }
3522
3825
  }
3826
+ } finally {
3827
+ if (progressInterval) {
3828
+ clearInterval(progressInterval);
3829
+ const elapsed = ((performance.now() - paramsStart) / 1e3).toFixed(1);
3830
+ console.log(
3831
+ `[rsc-router] Resolved prerender params: ${resolvedRoutes}/${totalDynamic} routes (${elapsed}s)`
3832
+ );
3833
+ }
3523
3834
  }
3524
3835
  if (entries.length === 0) return;
3525
3836
  const maxConcurrency = Math.max(...entries.map((e) => e.concurrency));
@@ -3546,7 +3857,8 @@ async function expandPrerenderRoutes(state, rscEnv, registry, allManifests) {
3546
3857
  entry.urlPath,
3547
3858
  {},
3548
3859
  entry.buildVars,
3549
- entry.isPassthroughRoute
3860
+ entry.isPassthroughRoute,
3861
+ state.resolvedBuildEnv
3550
3862
  );
3551
3863
  if (!result) continue;
3552
3864
  if (result.passthrough) {
@@ -3670,7 +3982,9 @@ async function renderStaticHandlers(state, rscEnv, registry) {
3670
3982
  const result = await routerInstance.renderStaticSegment(
3671
3983
  def.handler,
3672
3984
  def.$$id,
3673
- def.$$routePrefix
3985
+ def.$$routePrefix,
3986
+ state.resolvedBuildEnv,
3987
+ !state.isBuildMode
3674
3988
  );
3675
3989
  if (result) {
3676
3990
  const hasHandles = Object.keys(result.handles).length > 0;
@@ -3795,7 +4109,11 @@ async function discoverRouters(state, rscEnv) {
3795
4109
  if (!router.urlpatterns || !generateManifestFull) {
3796
4110
  continue;
3797
4111
  }
3798
- const manifest = generateManifestFull(router.urlpatterns, routerMountIndex);
4112
+ const manifest = generateManifestFull(
4113
+ router.urlpatterns,
4114
+ routerMountIndex,
4115
+ router.__basename ? { urlPrefix: router.__basename } : void 0
4116
+ );
3799
4117
  routerMountIndex++;
3800
4118
  allManifests.push({ id, manifest });
3801
4119
  const routeCount = Object.keys(manifest.routeManifest).length;
@@ -3937,7 +4255,7 @@ async function discoverRouters(state, rscEnv) {
3937
4255
  }
3938
4256
 
3939
4257
  // src/vite/discovery/route-types-writer.ts
3940
- import { dirname as dirname3, basename, join as join3, resolve as resolve6 } from "node:path";
4258
+ import { dirname as dirname3, basename, join as join2, resolve as resolve6 } from "node:path";
3941
4259
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync5, unlinkSync as unlinkSync2 } from "node:fs";
3942
4260
  function filterUserNamedRoutes(manifest) {
3943
4261
  const filtered = {};
@@ -3958,7 +4276,7 @@ function writeCombinedRouteTypesWithTracking(state, opts) {
3958
4276
  /\.(tsx?|jsx?)$/,
3959
4277
  ""
3960
4278
  );
3961
- const outPath = join3(routerDir, `${routerBasename}.named-routes.gen.ts`);
4279
+ const outPath = join2(routerDir, `${routerBasename}.named-routes.gen.ts`);
3962
4280
  try {
3963
4281
  preContent.set(outPath, readFileSync4(outPath, "utf-8"));
3964
4282
  } catch {
@@ -3971,7 +4289,7 @@ function writeCombinedRouteTypesWithTracking(state, opts) {
3971
4289
  /\.(tsx?|jsx?)$/,
3972
4290
  ""
3973
4291
  );
3974
- const outPath = join3(routerDir, `${routerBasename}.named-routes.gen.ts`);
4292
+ const outPath = join2(routerDir, `${routerBasename}.named-routes.gen.ts`);
3975
4293
  if (!existsSync5(outPath)) continue;
3976
4294
  try {
3977
4295
  const content = readFileSync4(outPath, "utf-8");
@@ -3988,7 +4306,7 @@ function writeRouteTypesFiles(state) {
3988
4306
  const entryDir = dirname3(
3989
4307
  resolve6(state.projectRoot, state.resolvedEntryPath)
3990
4308
  );
3991
- const oldCombinedPath = join3(entryDir, "named-routes.gen.ts");
4309
+ const oldCombinedPath = join2(entryDir, "named-routes.gen.ts");
3992
4310
  if (existsSync5(oldCombinedPath)) {
3993
4311
  unlinkSync2(oldCombinedPath);
3994
4312
  console.log(
@@ -4013,7 +4331,7 @@ Set an explicit \`id\` on createRouter() or check the call site.`
4013
4331
  }
4014
4332
  const routerDir = dirname3(sourceFile);
4015
4333
  const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
4016
- const outPath = join3(routerDir, `${routerBasename}.named-routes.gen.ts`);
4334
+ const outPath = join2(routerDir, `${routerBasename}.named-routes.gen.ts`);
4017
4335
  const userRoutes = filterUserNamedRoutes(routeManifest);
4018
4336
  let effectiveSearchSchemas = routeSearchSchemas;
4019
4337
  if ((!effectiveSearchSchemas || Object.keys(effectiveSearchSchemas).length === 0) && sourceFile) {
@@ -4078,7 +4396,7 @@ function supplementGenFilesWithRuntimeRoutes(state) {
4078
4396
  }
4079
4397
  const routerDir = dirname3(sourceFile);
4080
4398
  const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
4081
- const outPath = join3(routerDir, `${routerBasename}.named-routes.gen.ts`);
4399
+ const outPath = join2(routerDir, `${routerBasename}.named-routes.gen.ts`);
4082
4400
  const source = generateRouteTypesSource(
4083
4401
  mergedRoutes,
4084
4402
  Object.keys(mergedSearchSchemas).length > 0 ? mergedSearchSchemas : void 0
@@ -4092,7 +4410,7 @@ function supplementGenFilesWithRuntimeRoutes(state) {
4092
4410
  }
4093
4411
 
4094
4412
  // src/vite/discovery/virtual-module-codegen.ts
4095
- import { dirname as dirname4, basename as basename2, join as join4 } from "node:path";
4413
+ import { dirname as dirname4, basename as basename2, join as join3 } from "node:path";
4096
4414
  function generateRoutesManifestModule(state) {
4097
4415
  const hasManifest = state.mergedRouteManifest && Object.keys(state.mergedRouteManifest).length > 0;
4098
4416
  if (hasManifest) {
@@ -4107,7 +4425,7 @@ function generateRoutesManifestModule(state) {
4107
4425
  /\.(tsx?|jsx?)$/,
4108
4426
  ""
4109
4427
  );
4110
- const genPath = join4(
4428
+ const genPath = join3(
4111
4429
  routerDir,
4112
4430
  `${routerBasename}.named-routes.gen.js`
4113
4431
  ).replaceAll("\\", "/");
@@ -4204,7 +4522,7 @@ function generatePerRouterModule(state, routerId) {
4204
4522
  /\.(tsx?|jsx?)$/,
4205
4523
  ""
4206
4524
  );
4207
- const genPath = join4(
4525
+ const genPath = join3(
4208
4526
  routerDir,
4209
4527
  `${routerBasename}.named-routes.gen.js`
4210
4528
  ).replaceAll("\\", "/");
@@ -4244,48 +4562,45 @@ function postprocessBundle(state) {
4244
4562
  );
4245
4563
  const evictionTargets = [
4246
4564
  {
4247
- info: state.handlerChunkInfo,
4565
+ infos: state.handlerChunkInfoMap.values(),
4248
4566
  fnName: "Prerender",
4249
4567
  brand: "prerenderHandler",
4250
4568
  label: "handler code from RSC bundle"
4251
4569
  },
4252
4570
  {
4253
- info: state.staticHandlerChunkInfo,
4571
+ infos: state.staticHandlerChunkInfoMap.values(),
4254
4572
  fnName: "Static",
4255
4573
  brand: "staticHandler",
4256
4574
  label: "static handler code"
4257
4575
  }
4258
4576
  ];
4259
4577
  for (const target of evictionTargets) {
4260
- if (!target.info) continue;
4261
- const chunkPath = resolve7(
4262
- state.projectRoot,
4263
- "dist/rsc",
4264
- target.info.fileName
4265
- );
4266
- try {
4267
- const code = readFileSync5(chunkPath, "utf-8");
4268
- const result = evictHandlerCode(
4269
- code,
4270
- target.info.exports,
4271
- target.fnName,
4272
- target.brand
4273
- );
4274
- if (result) {
4275
- writeFileSync4(chunkPath, result.code);
4276
- const savedKB = (result.savedBytes / 1024).toFixed(1);
4277
- console.log(
4278
- `[rsc-router] Evicted ${target.label} (${savedKB} KB saved): ${target.info.fileName}`
4578
+ for (const info of target.infos) {
4579
+ const chunkPath = resolve7(state.projectRoot, "dist/rsc", info.fileName);
4580
+ try {
4581
+ const code = readFileSync5(chunkPath, "utf-8");
4582
+ const result = evictHandlerCode(
4583
+ code,
4584
+ info.exports,
4585
+ target.fnName,
4586
+ target.brand
4587
+ );
4588
+ if (result) {
4589
+ writeFileSync4(chunkPath, result.code);
4590
+ const savedKB = (result.savedBytes / 1024).toFixed(1);
4591
+ console.log(
4592
+ `[rsc-router] Evicted ${target.label} (${savedKB} KB saved): ${info.fileName}`
4593
+ );
4594
+ }
4595
+ } catch (replaceErr) {
4596
+ console.warn(
4597
+ `[rsc-router] Failed to evict ${target.label}: ${replaceErr.message}`
4279
4598
  );
4280
4599
  }
4281
- } catch (replaceErr) {
4282
- console.warn(
4283
- `[rsc-router] Failed to evict ${target.label}: ${replaceErr.message}`
4284
- );
4285
4600
  }
4286
4601
  }
4287
- state.handlerChunkInfo = null;
4288
- state.staticHandlerChunkInfo = null;
4602
+ state.handlerChunkInfoMap.clear();
4603
+ state.staticHandlerChunkInfoMap.clear();
4289
4604
  if (hasPrerenderData && existsSync6(rscEntryPath)) {
4290
4605
  const rscCode = readFileSync5(rscEntryPath, "utf-8");
4291
4606
  if (!rscCode.includes("__prerender-manifest.js")) {
@@ -4328,7 +4643,7 @@ function postprocessBundle(state) {
4328
4643
  }
4329
4644
  if (hasStaticData && existsSync6(rscEntryPath)) {
4330
4645
  const rscCode = readFileSync5(rscEntryPath, "utf-8");
4331
- if (!rscCode.includes("__STATIC_MANIFEST")) {
4646
+ if (!rscCode.includes("__static-manifest.js")) {
4332
4647
  try {
4333
4648
  const manifestEntries = [];
4334
4649
  let totalBytes = copyStagedBuildAssets(
@@ -4397,8 +4712,67 @@ async function createTempRscServer(state, options = {}) {
4397
4712
  ]
4398
4713
  });
4399
4714
  }
4715
+ async function resolveBuildEnv(option, factoryCtx) {
4716
+ if (!option) return null;
4717
+ if (option === "auto") {
4718
+ if (factoryCtx.preset !== "cloudflare") {
4719
+ throw new Error(
4720
+ '[rsc-router] buildEnv: "auto" is only supported with preset: "cloudflare". Use a factory function or plain object for other presets.'
4721
+ );
4722
+ }
4723
+ try {
4724
+ const userRequire = createRequire(
4725
+ resolve8(factoryCtx.root, "package.json")
4726
+ );
4727
+ const wranglerPath = userRequire.resolve("wrangler");
4728
+ const { getPlatformProxy } = await import(pathToFileURL(wranglerPath).href);
4729
+ const proxy = await getPlatformProxy();
4730
+ return {
4731
+ env: proxy.env,
4732
+ dispose: proxy.dispose
4733
+ };
4734
+ } catch (err) {
4735
+ throw new Error(
4736
+ `[rsc-router] buildEnv: "auto" requires wrangler to be installed.
4737
+ Install it with: pnpm add -D wrangler
4738
+ ${err.message}`
4739
+ );
4740
+ }
4741
+ }
4742
+ if (typeof option === "function") {
4743
+ return await option(factoryCtx);
4744
+ }
4745
+ return { env: option };
4746
+ }
4747
+ async function acquireBuildEnv(s, command, mode) {
4748
+ const option = s.opts?.buildEnv;
4749
+ if (!option) return false;
4750
+ const result = await resolveBuildEnv(option, {
4751
+ root: s.projectRoot,
4752
+ mode,
4753
+ command,
4754
+ preset: s.opts?.preset ?? "node"
4755
+ });
4756
+ if (!result) return false;
4757
+ s.resolvedBuildEnv = result.env;
4758
+ s.buildEnvDispose = result.dispose ?? null;
4759
+ return true;
4760
+ }
4761
+ async function releaseBuildEnv(s) {
4762
+ if (s.buildEnvDispose) {
4763
+ try {
4764
+ await s.buildEnvDispose();
4765
+ } catch (err) {
4766
+ console.warn(`[rsc-router] buildEnv dispose failed: ${err.message}`);
4767
+ }
4768
+ s.buildEnvDispose = null;
4769
+ }
4770
+ s.resolvedBuildEnv = void 0;
4771
+ }
4400
4772
  function createRouterDiscoveryPlugin(entryPath, opts) {
4401
4773
  const s = createDiscoveryState(entryPath, opts);
4774
+ let viteCommand = "build";
4775
+ let viteMode = "production";
4402
4776
  return {
4403
4777
  name: "@rangojs/router:discovery",
4404
4778
  config() {
@@ -4407,31 +4781,13 @@ function createRouterDiscoveryPlugin(entryPath, opts) {
4407
4781
  __RANGO_DEBUG__: JSON.stringify(!!process.env.INTERNAL_RANGO_DEBUG)
4408
4782
  }
4409
4783
  };
4410
- if (opts?.enableBuildPrerender) {
4411
- config.environments = {
4412
- rsc: {
4413
- build: {
4414
- rollupOptions: {
4415
- output: {
4416
- manualChunks(id) {
4417
- if (s.resolvedPrerenderModules?.has(id)) {
4418
- return "__prerender-handlers";
4419
- }
4420
- if (s.resolvedStaticModules?.has(id)) {
4421
- return "__static-handlers";
4422
- }
4423
- }
4424
- }
4425
- }
4426
- }
4427
- }
4428
- };
4429
- }
4430
4784
  return config;
4431
4785
  },
4432
4786
  configResolved(config) {
4433
4787
  s.projectRoot = config.root;
4434
4788
  s.isBuildMode = config.command === "build";
4789
+ viteCommand = config.command;
4790
+ viteMode = config.mode;
4435
4791
  s.userResolveAlias = config.resolve.alias;
4436
4792
  if (!s.resolvedEntryPath && opts?.routerPathRef?.path) {
4437
4793
  s.resolvedEntryPath = opts.routerPathRef.path;
@@ -4445,12 +4801,6 @@ function createRouterDiscoveryPlugin(entryPath, opts) {
4445
4801
  s.resolvedEntryPath = entries[0];
4446
4802
  }
4447
4803
  }
4448
- if (opts?.include || opts?.exclude) {
4449
- s.scanFilter = createScanFilter(s.projectRoot, {
4450
- include: opts.include,
4451
- exclude: opts.exclude
4452
- });
4453
- }
4454
4804
  if (opts?.staticRouteTypesGeneration !== false) {
4455
4805
  s.cachedRouterFiles = findRouterFiles(s.projectRoot, s.scanFilter);
4456
4806
  writeCombinedRouteTypesWithTracking(s, { preserveIfLarger: true });
@@ -4482,6 +4832,8 @@ function createRouterDiscoveryPlugin(entryPath, opts) {
4482
4832
  });
4483
4833
  prerenderTempServer = null;
4484
4834
  }
4835
+ releaseBuildEnv(s).catch(() => {
4836
+ });
4485
4837
  });
4486
4838
  async function getOrCreateTempServer() {
4487
4839
  if (prerenderNodeRegistry) {
@@ -4512,6 +4864,7 @@ function createRouterDiscoveryPlugin(entryPath, opts) {
4512
4864
  if (!rscEnv?.runner) {
4513
4865
  s.devServerOrigin = getDevServerOrigin();
4514
4866
  try {
4867
+ await acquireBuildEnv(s, viteCommand, viteMode);
4515
4868
  const tempRscEnv = await getOrCreateTempServer();
4516
4869
  if (tempRscEnv) {
4517
4870
  await discoverRouters(s, tempRscEnv);
@@ -4527,6 +4880,7 @@ ${err.stack}`
4527
4880
  return;
4528
4881
  }
4529
4882
  try {
4883
+ await acquireBuildEnv(s, viteCommand, viteMode);
4530
4884
  const serverMod = await rscEnv.runner.import(
4531
4885
  "@rangojs/router/server"
4532
4886
  );
@@ -4591,7 +4945,26 @@ ${err.stack}`
4591
4945
  res.end("Missing pathname");
4592
4946
  return;
4593
4947
  }
4594
- let registry = mainRegistry;
4948
+ const rscEnv = server.environments?.rsc;
4949
+ let registry = null;
4950
+ if (rscEnv?.runner && s.resolvedEntryPath) {
4951
+ try {
4952
+ await rscEnv.runner.import(s.resolvedEntryPath);
4953
+ const serverMod = await rscEnv.runner.import(
4954
+ "@rangojs/router/server"
4955
+ );
4956
+ registry = serverMod.RouterRegistry ?? null;
4957
+ } catch (err) {
4958
+ console.warn(
4959
+ `[rsc-router] Dev prerender module refresh failed: ${err.message}`
4960
+ );
4961
+ res.statusCode = 500;
4962
+ res.end(`Prerender handler error: ${err.message}`);
4963
+ return;
4964
+ }
4965
+ } else {
4966
+ registry = mainRegistry;
4967
+ }
4595
4968
  if (!registry) {
4596
4969
  if (!prerenderNodeRegistry) {
4597
4970
  await getOrCreateTempServer();
@@ -4613,7 +4986,10 @@ ${err.stack}`
4613
4986
  pathname,
4614
4987
  {},
4615
4988
  void 0,
4616
- wantPassthrough
4989
+ wantPassthrough,
4990
+ s.resolvedBuildEnv,
4991
+ true
4992
+ // devMode: check getParams for passthrough routes
4617
4993
  );
4618
4994
  if (!result) continue;
4619
4995
  if (result.passthrough) continue;
@@ -4749,6 +5125,7 @@ ${err.stack}`
4749
5125
  resetStagedBuildAssets(s.projectRoot);
4750
5126
  s.prerenderManifestEntries = null;
4751
5127
  s.staticManifestEntries = null;
5128
+ await acquireBuildEnv(s, viteCommand, viteMode);
4752
5129
  let tempServer = null;
4753
5130
  globalThis.__rscRouterDiscoveryActive = true;
4754
5131
  try {
@@ -4788,6 +5165,7 @@ ${details}`
4788
5165
  if (tempServer) {
4789
5166
  await tempServer.close();
4790
5167
  }
5168
+ await releaseBuildEnv(s);
4791
5169
  }
4792
5170
  },
4793
5171
  // Virtual module: provides the pre-generated route manifest as a JS module
@@ -4830,20 +5208,30 @@ ${details}`
4830
5208
  }
4831
5209
  if (!s.resolvedPrerenderModules?.size && !s.resolvedStaticModules?.size)
4832
5210
  return;
5211
+ s.handlerChunkInfoMap.clear();
5212
+ s.staticHandlerChunkInfoMap.clear();
4833
5213
  for (const [fileName, chunk] of Object.entries(bundle)) {
4834
5214
  if (chunk.type !== "chunk") continue;
4835
- if (fileName.includes("__prerender-handlers") && s.resolvedPrerenderModules?.size) {
5215
+ if (s.resolvedPrerenderModules?.size) {
4836
5216
  const handlers = extractHandlerExportsFromChunk(
4837
5217
  chunk.code,
4838
5218
  s.resolvedPrerenderModules,
4839
5219
  "Prerender",
4840
- true
5220
+ false
4841
5221
  );
4842
5222
  if (handlers.length > 0) {
4843
- s.handlerChunkInfo = { fileName, exports: handlers };
5223
+ const existing = s.handlerChunkInfoMap.get(fileName);
5224
+ if (existing) {
5225
+ existing.exports.push(...handlers);
5226
+ } else {
5227
+ s.handlerChunkInfoMap.set(fileName, {
5228
+ fileName,
5229
+ exports: handlers
5230
+ });
5231
+ }
4844
5232
  }
4845
5233
  }
4846
- if (fileName.includes("__static-handlers") && s.resolvedStaticModules?.size) {
5234
+ if (s.resolvedStaticModules?.size) {
4847
5235
  const handlers = extractHandlerExportsFromChunk(
4848
5236
  chunk.code,
4849
5237
  s.resolvedStaticModules,
@@ -4851,7 +5239,15 @@ ${details}`
4851
5239
  false
4852
5240
  );
4853
5241
  if (handlers.length > 0) {
4854
- s.staticHandlerChunkInfo = { fileName, exports: handlers };
5242
+ const existing = s.staticHandlerChunkInfoMap.get(fileName);
5243
+ if (existing) {
5244
+ existing.exports.push(...handlers);
5245
+ } else {
5246
+ s.staticHandlerChunkInfoMap.set(fileName, {
5247
+ fileName,
5248
+ exports: handlers
5249
+ });
5250
+ }
4855
5251
  }
4856
5252
  }
4857
5253
  }
@@ -4878,8 +5274,16 @@ async function rango(options) {
4878
5274
  const showBanner = resolvedOptions.banner ?? true;
4879
5275
  const plugins = [];
4880
5276
  const rangoAliases = getPackageAliases();
4881
- const excludeDeps = getExcludeDeps();
4882
- let rscEntryPath = null;
5277
+ const excludeDeps = [
5278
+ ...getExcludeDeps(),
5279
+ // The public browser entry re-exports the RSDW browser client.
5280
+ // Excluding both keeps Vite from freezing the unpatched bundle into
5281
+ // .vite/deps before our source transforms run.
5282
+ "@vitejs/plugin-rsc/browser",
5283
+ // Keep the browser RSDW client out of Vite's dep optimizer so our
5284
+ // cjs-to-esm transform can patch the real file.
5285
+ "@vitejs/plugin-rsc/vendor/react-server-dom/client.browser"
5286
+ ];
4883
5287
  const routerRef = { path: void 0 };
4884
5288
  const prerenderEnabled = true;
4885
5289
  if (preset === "cloudflare") {
@@ -4975,6 +5379,7 @@ async function rango(options) {
4975
5379
  }
4976
5380
  });
4977
5381
  plugins.push(createVirtualEntriesPlugin(finalEntries));
5382
+ plugins.push(performanceTracksPlugin());
4978
5383
  plugins.push(
4979
5384
  rsc({
4980
5385
  entries: finalEntries,
@@ -4983,153 +5388,122 @@ async function rango(options) {
4983
5388
  );
4984
5389
  plugins.push(clientRefDedup());
4985
5390
  } else {
4986
- const nodeOptions = resolvedOptions;
4987
- routerRef.path = nodeOptions.router;
4988
- if (!routerRef.path) {
4989
- plugins.push({
4990
- name: "@rangojs/router:auto-discover",
4991
- config(userConfig) {
4992
- if (routerRef.path) return;
4993
- const root = userConfig.root ? resolve9(process.cwd(), userConfig.root) : process.cwd();
4994
- const filter = createScanFilter(root, {
4995
- include: resolvedOptions.include,
4996
- exclude: resolvedOptions.exclude
4997
- });
4998
- const candidates = findRouterFiles(root, filter);
4999
- if (candidates.length === 1) {
5000
- const abs = candidates[0];
5001
- routerRef.path = (abs.startsWith(root) ? "./" + abs.slice(root.length + 1) : abs).replaceAll("\\", "/");
5002
- } else if (candidates.length > 1) {
5003
- const list = candidates.map(
5004
- (f) => " - " + (f.startsWith(root) ? f.slice(root.length + 1) : f)
5005
- ).join("\n");
5006
- throw new Error(
5007
- `[rsc-router] Multiple routers found. Specify \`router\` to choose one:
5008
- ${list}`
5009
- );
5010
- }
5391
+ plugins.push({
5392
+ name: "@rangojs/router:auto-discover",
5393
+ config(userConfig) {
5394
+ if (routerRef.path) return;
5395
+ const root = userConfig.root ? resolve9(process.cwd(), userConfig.root) : process.cwd();
5396
+ const candidates = findRouterFiles(root);
5397
+ if (candidates.length === 1) {
5398
+ const abs = candidates[0];
5399
+ routerRef.path = (abs.startsWith(root) ? "./" + abs.slice(root.length + 1) : abs).replaceAll("\\", "/");
5400
+ } else if (candidates.length > 1) {
5401
+ const list = candidates.map(
5402
+ (f) => " - " + (f.startsWith(root) ? f.slice(root.length + 1) : f)
5403
+ ).join("\n");
5404
+ throw new Error(`[rsc-router] Multiple routers found:
5405
+ ${list}`);
5011
5406
  }
5012
- });
5013
- }
5014
- const rscOption = nodeOptions.rsc ?? true;
5015
- if (rscOption !== false) {
5016
- const { default: rsc } = await import("@vitejs/plugin-rsc");
5017
- const userEntries = typeof rscOption === "boolean" ? {} : rscOption.entries || {};
5018
- const finalEntries = {
5019
- client: userEntries.client ?? VIRTUAL_IDS.browser,
5020
- ssr: userEntries.ssr ?? VIRTUAL_IDS.ssr,
5021
- rsc: userEntries.rsc ?? VIRTUAL_IDS.rsc
5022
- };
5023
- rscEntryPath = userEntries.rsc ?? null;
5024
- let hasWarnedDuplicate = false;
5025
- plugins.push({
5026
- name: "@rangojs/router:rsc-integration",
5027
- enforce: "pre",
5028
- config() {
5029
- const useVirtualClient = finalEntries.client === VIRTUAL_IDS.browser;
5030
- const useVirtualSSR = finalEntries.ssr === VIRTUAL_IDS.ssr;
5031
- const useVirtualRSC = finalEntries.rsc === VIRTUAL_IDS.rsc;
5032
- return {
5033
- // Exclude rsc-router modules from optimization to prevent module duplication
5034
- // This ensures the same Context instance is used by both browser entry and RSC proxy modules
5035
- optimizeDeps: {
5036
- exclude: excludeDeps,
5037
- esbuildOptions: sharedEsbuildOptions
5038
- },
5039
- build: {
5040
- rollupOptions: { onwarn }
5041
- },
5042
- resolve: {
5043
- alias: rangoAliases
5044
- },
5045
- environments: {
5046
- client: {
5047
- build: {
5048
- rollupOptions: {
5049
- output: {
5050
- manualChunks: getManualChunks
5051
- }
5052
- }
5053
- },
5054
- // Always exclude rsc-router modules, conditionally add virtual entry
5055
- optimizeDeps: {
5056
- // Pre-bundle React and rsc-html-stream to prevent late discovery
5057
- // triggering ERR_OUTDATED_OPTIMIZED_DEP on cold starts
5058
- include: [
5059
- "react",
5060
- "react-dom",
5061
- "react/jsx-runtime",
5062
- "react/jsx-dev-runtime",
5063
- "rsc-html-stream/client"
5064
- ],
5065
- exclude: excludeDeps,
5066
- esbuildOptions: sharedEsbuildOptions,
5067
- ...useVirtualClient && {
5068
- // Tell Vite to scan the virtual entry for dependencies
5069
- entries: [VIRTUAL_IDS.browser]
5070
- }
5071
- }
5072
- },
5073
- ...useVirtualSSR && {
5074
- ssr: {
5075
- optimizeDeps: {
5076
- entries: [VIRTUAL_IDS.ssr],
5077
- // Pre-bundle all SSR deps to prevent late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
5078
- include: [
5079
- "react",
5080
- "react-dom",
5081
- "react-dom/server.edge",
5082
- "react-dom/static.edge",
5083
- "react/jsx-runtime",
5084
- "react/jsx-dev-runtime",
5085
- "@vitejs/plugin-rsc/vendor/react-server-dom/client.edge"
5086
- ],
5087
- exclude: excludeDeps,
5088
- esbuildOptions: sharedEsbuildOptions
5407
+ }
5408
+ });
5409
+ const finalEntries = {
5410
+ client: VIRTUAL_IDS.browser,
5411
+ ssr: VIRTUAL_IDS.ssr,
5412
+ rsc: VIRTUAL_IDS.rsc
5413
+ };
5414
+ const { default: rsc } = await import("@vitejs/plugin-rsc");
5415
+ let hasWarnedDuplicate = false;
5416
+ plugins.push({
5417
+ name: "@rangojs/router:rsc-integration",
5418
+ enforce: "pre",
5419
+ config() {
5420
+ return {
5421
+ optimizeDeps: {
5422
+ exclude: excludeDeps,
5423
+ esbuildOptions: sharedEsbuildOptions
5424
+ },
5425
+ build: {
5426
+ rollupOptions: { onwarn }
5427
+ },
5428
+ resolve: {
5429
+ alias: rangoAliases
5430
+ },
5431
+ environments: {
5432
+ client: {
5433
+ build: {
5434
+ rollupOptions: {
5435
+ output: {
5436
+ manualChunks: getManualChunks
5089
5437
  }
5090
5438
  }
5091
5439
  },
5092
- ...useVirtualRSC && {
5093
- rsc: {
5094
- optimizeDeps: {
5095
- entries: [VIRTUAL_IDS.rsc],
5096
- // Pre-bundle all RSC deps to prevent late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
5097
- include: [
5098
- "react",
5099
- "react/jsx-runtime",
5100
- "react/jsx-dev-runtime",
5101
- "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge"
5102
- ],
5103
- esbuildOptions: sharedEsbuildOptions
5104
- }
5105
- }
5440
+ optimizeDeps: {
5441
+ include: [
5442
+ "react",
5443
+ "react-dom",
5444
+ "react/jsx-runtime",
5445
+ "react/jsx-dev-runtime",
5446
+ "rsc-html-stream/client"
5447
+ ],
5448
+ exclude: excludeDeps,
5449
+ esbuildOptions: sharedEsbuildOptions,
5450
+ entries: [VIRTUAL_IDS.browser]
5451
+ }
5452
+ },
5453
+ ssr: {
5454
+ optimizeDeps: {
5455
+ entries: [VIRTUAL_IDS.ssr],
5456
+ include: [
5457
+ "react",
5458
+ "react-dom",
5459
+ "react-dom/server.edge",
5460
+ "react-dom/static.edge",
5461
+ "react/jsx-runtime",
5462
+ "react/jsx-dev-runtime",
5463
+ "@vitejs/plugin-rsc/vendor/react-server-dom/client.edge"
5464
+ ],
5465
+ exclude: excludeDeps,
5466
+ esbuildOptions: sharedEsbuildOptions
5467
+ }
5468
+ },
5469
+ rsc: {
5470
+ optimizeDeps: {
5471
+ entries: [VIRTUAL_IDS.rsc],
5472
+ include: [
5473
+ "react",
5474
+ "react/jsx-runtime",
5475
+ "react/jsx-dev-runtime",
5476
+ "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge"
5477
+ ],
5478
+ esbuildOptions: sharedEsbuildOptions
5106
5479
  }
5107
5480
  }
5108
- };
5109
- },
5110
- configResolved(config) {
5111
- if (showBanner) {
5112
- const mode = config.command === "serve" ? process.argv.includes("preview") ? "preview" : "dev" : "build";
5113
- printBanner(mode, "node", rangoVersion);
5114
- }
5115
- const rscMinimalCount = config.plugins.filter(
5116
- (p) => p.name === "rsc:minimal"
5117
- ).length;
5118
- if (rscMinimalCount > 1 && !hasWarnedDuplicate) {
5119
- hasWarnedDuplicate = true;
5120
- console.warn(
5121
- "[rsc-router] Duplicate @vitejs/plugin-rsc detected. Remove rsc() from your config or use rango({ rsc: false }) for manual configuration."
5122
- );
5123
5481
  }
5482
+ };
5483
+ },
5484
+ configResolved(config) {
5485
+ if (showBanner) {
5486
+ const mode = config.command === "serve" ? process.argv.includes("preview") ? "preview" : "dev" : "build";
5487
+ printBanner(mode, "node", rangoVersion);
5124
5488
  }
5125
- });
5126
- plugins.push(createVirtualEntriesPlugin(finalEntries, routerRef));
5127
- plugins.push(
5128
- rsc({
5129
- entries: finalEntries
5130
- })
5131
- );
5132
- }
5489
+ const rscMinimalCount = config.plugins.filter(
5490
+ (p) => p.name === "rsc:minimal"
5491
+ ).length;
5492
+ if (rscMinimalCount > 1 && !hasWarnedDuplicate) {
5493
+ hasWarnedDuplicate = true;
5494
+ console.warn(
5495
+ "[rsc-router] Duplicate @vitejs/plugin-rsc detected. Remove rsc() from your vite config \u2014 rango() includes it automatically."
5496
+ );
5497
+ }
5498
+ }
5499
+ });
5500
+ plugins.push(createVirtualEntriesPlugin(finalEntries, routerRef));
5501
+ plugins.push(performanceTracksPlugin());
5502
+ plugins.push(
5503
+ rsc({
5504
+ entries: finalEntries
5505
+ })
5506
+ );
5133
5507
  plugins.push(clientRefDedup());
5134
5508
  }
5135
5509
  plugins.push({
@@ -5157,18 +5531,16 @@ ${list}`
5157
5531
  plugins.push(createVersionPlugin());
5158
5532
  const discoveryEntryPath = preset !== "cloudflare" ? routerRef.path : void 0;
5159
5533
  const discoveryRouterRef = preset !== "cloudflare" ? routerRef : void 0;
5160
- const injectorEntryPath = rscEntryPath ?? (preset === "cloudflare" ? void 0 : null);
5161
- if (injectorEntryPath !== null) {
5162
- plugins.push(createVersionInjectorPlugin(injectorEntryPath));
5534
+ if (preset === "cloudflare") {
5535
+ plugins.push(createVersionInjectorPlugin(void 0));
5163
5536
  }
5164
5537
  plugins.push(createCjsToEsmPlugin());
5165
5538
  plugins.push(
5166
5539
  createRouterDiscoveryPlugin(discoveryEntryPath, {
5167
5540
  routerPathRef: discoveryRouterRef,
5168
5541
  enableBuildPrerender: prerenderEnabled,
5169
- staticRouteTypesGeneration: resolvedOptions.staticRouteTypesGeneration,
5170
- include: resolvedOptions.include,
5171
- exclude: resolvedOptions.exclude
5542
+ buildEnv: options?.buildEnv,
5543
+ preset
5172
5544
  })
5173
5545
  );
5174
5546
  return plugins;
@@ -5181,29 +5553,75 @@ function poke() {
5181
5553
  apply: "serve",
5182
5554
  configureServer(server) {
5183
5555
  const stdin = process.stdin;
5184
- const previousRawMode = stdin.isTTY ? stdin.isRaw : null;
5556
+ const debug = process.env.RANGO_POKE_DEBUG === "1";
5557
+ const triggerReload = (source) => {
5558
+ server.hot.send({ type: "full-reload", path: "*" });
5559
+ server.config.logger.info(` browser reload (${source})`, {
5560
+ timestamp: true
5561
+ });
5562
+ };
5563
+ const toBuffer = (chunk) => {
5564
+ return typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
5565
+ };
5566
+ const formatChunk = (chunk) => {
5567
+ const data = toBuffer(chunk);
5568
+ const hex = Array.from(data).map((byte) => `0x${byte.toString(16).padStart(2, "0")}`).join(" ");
5569
+ const ascii = Array.from(data).map((byte) => {
5570
+ if (byte >= 32 && byte <= 126) return String.fromCharCode(byte);
5571
+ if (byte === 10) return "\\n";
5572
+ if (byte === 13) return "\\r";
5573
+ if (byte === 9) return "\\t";
5574
+ return ".";
5575
+ }).join("");
5576
+ return `len=${data.length} hex=[${hex}] ascii="${ascii}"`;
5577
+ };
5578
+ const readCtrlR = (chunk) => {
5579
+ const data = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
5580
+ return data.length === 1 && data[0] === 18;
5581
+ };
5582
+ const readSubmittedCommands = (chunk) => {
5583
+ const text = toBuffer(chunk).toString("utf8").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5584
+ if (!text.includes("\n")) return [];
5585
+ const lines = text.split("\n");
5586
+ lines.pop();
5587
+ return lines;
5588
+ };
5589
+ if (debug) {
5590
+ server.config.logger.info(
5591
+ ` poke debug enabled (isTTY=${stdin.isTTY ? "yes" : "no"}, isRaw=${stdin.isTTY ? stdin.isRaw ? "yes" : "no" : "n/a"})`,
5592
+ { timestamp: true }
5593
+ );
5594
+ }
5185
5595
  if (stdin.isTTY) {
5186
- stdin.setRawMode(true);
5596
+ server.config.logger.info(
5597
+ " poke ready: press e + enter to reload browser (ctrl+r also works when available)",
5598
+ { timestamp: true }
5599
+ );
5187
5600
  }
5188
5601
  const onData = (data) => {
5189
- if (data.length !== 1) return;
5190
- if (data[0] === 3) {
5191
- process.emit("SIGINT", "SIGINT");
5192
- return;
5193
- }
5194
- if (data[0] === 18) {
5195
- server.hot.send({ type: "full-reload", path: "*" });
5196
- server.config.logger.info(" browser reload (ctrl+r)", {
5602
+ if (debug) {
5603
+ server.config.logger.info(` poke stdin ${formatChunk(data)}`, {
5197
5604
  timestamp: true
5198
5605
  });
5199
5606
  }
5607
+ if (readCtrlR(data)) {
5608
+ triggerReload("ctrl+r");
5609
+ return;
5610
+ }
5611
+ for (const command of readSubmittedCommands(data)) {
5612
+ if (command === "e") {
5613
+ triggerReload("e+enter");
5614
+ return;
5615
+ }
5616
+ if (command === "\x1Br") {
5617
+ triggerReload("option+r+enter");
5618
+ return;
5619
+ }
5620
+ }
5200
5621
  };
5201
5622
  stdin.on("data", onData);
5202
5623
  server.httpServer?.on("close", () => {
5203
5624
  stdin.off("data", onData);
5204
- if (stdin.isTTY && previousRawMode !== null) {
5205
- stdin.setRawMode(previousRawMode);
5206
- }
5207
5625
  });
5208
5626
  }
5209
5627
  };