@rangojs/router 0.0.0-experimental.20 → 0.0.0-experimental.204030a9

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 (293) hide show
  1. package/AGENTS.md +4 -0
  2. package/README.md +242 -55
  3. package/dist/bin/rango.js +277 -99
  4. package/dist/vite/index.js +2929 -1132
  5. package/dist/vite/index.js.bak +5448 -0
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +68 -21
  8. package/skills/breadcrumbs/SKILL.md +252 -0
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +243 -21
  11. package/skills/caching/SKILL.md +159 -10
  12. package/skills/composability/SKILL.md +27 -2
  13. package/skills/document-cache/SKILL.md +78 -55
  14. package/skills/handler-use/SKILL.md +364 -0
  15. package/skills/hooks/SKILL.md +262 -51
  16. package/skills/host-router/SKILL.md +243 -0
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +46 -4
  19. package/skills/layout/SKILL.md +28 -7
  20. package/skills/links/SKILL.md +249 -17
  21. package/skills/loader/SKILL.md +291 -31
  22. package/skills/middleware/SKILL.md +49 -12
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +27 -0
  26. package/skills/observability/SKILL.md +137 -0
  27. package/skills/parallel/SKILL.md +197 -6
  28. package/skills/prerender/SKILL.md +125 -102
  29. package/skills/rango/SKILL.md +242 -23
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +66 -9
  32. package/skills/route/SKILL.md +91 -8
  33. package/skills/router-setup/SKILL.md +98 -8
  34. package/skills/server-actions/SKILL.md +751 -0
  35. package/skills/streams-and-websockets/SKILL.md +283 -0
  36. package/skills/testing/SKILL.md +511 -188
  37. package/skills/typesafety/SKILL.md +354 -50
  38. package/skills/use-cache/SKILL.md +34 -5
  39. package/skills/view-transitions/SKILL.md +294 -0
  40. package/src/__augment-tests__/augment.ts +81 -0
  41. package/src/__augment-tests__/augmented.check.ts +117 -0
  42. package/src/__internal.ts +92 -0
  43. package/src/browser/action-coordinator.ts +53 -36
  44. package/src/browser/app-shell.ts +52 -0
  45. package/src/browser/app-version.ts +14 -0
  46. package/src/browser/event-controller.ts +91 -70
  47. package/src/browser/history-state.ts +21 -0
  48. package/src/browser/index.ts +3 -3
  49. package/src/browser/link-interceptor.ts +4 -0
  50. package/src/browser/navigation-bridge.ts +183 -18
  51. package/src/browser/navigation-client.ts +187 -57
  52. package/src/browser/navigation-store.ts +75 -17
  53. package/src/browser/navigation-transaction.ts +21 -37
  54. package/src/browser/partial-update.ts +143 -40
  55. package/src/browser/prefetch/cache.ts +275 -28
  56. package/src/browser/prefetch/fetch.ts +191 -46
  57. package/src/browser/prefetch/policy.ts +6 -0
  58. package/src/browser/prefetch/queue.ts +123 -20
  59. package/src/browser/prefetch/resource-ready.ts +77 -0
  60. package/src/browser/rango-state.ts +53 -13
  61. package/src/browser/react/Link.tsx +98 -14
  62. package/src/browser/react/NavigationProvider.tsx +110 -33
  63. package/src/browser/react/context.ts +7 -2
  64. package/src/browser/react/filter-segment-order.ts +51 -7
  65. package/src/browser/react/index.ts +3 -0
  66. package/src/browser/react/location-state-shared.ts +175 -4
  67. package/src/browser/react/location-state.ts +39 -13
  68. package/src/browser/react/use-handle.ts +23 -64
  69. package/src/browser/react/use-navigation.ts +22 -2
  70. package/src/browser/react/use-params.ts +20 -8
  71. package/src/browser/react/use-reverse.ts +106 -0
  72. package/src/browser/react/use-router.ts +43 -10
  73. package/src/browser/react/use-segments.ts +11 -8
  74. package/src/browser/response-adapter.ts +25 -0
  75. package/src/browser/rsc-router.tsx +200 -75
  76. package/src/browser/scroll-restoration.ts +46 -39
  77. package/src/browser/segment-reconciler.ts +36 -9
  78. package/src/browser/segment-structure-assert.ts +2 -2
  79. package/src/browser/server-action-bridge.ts +31 -36
  80. package/src/browser/types.ts +81 -5
  81. package/src/build/collect-fallback-refs.ts +107 -0
  82. package/src/build/generate-manifest.ts +65 -40
  83. package/src/build/generate-route-types.ts +5 -0
  84. package/src/build/index.ts +2 -0
  85. package/src/build/route-trie.ts +69 -26
  86. package/src/build/route-types/codegen.ts +4 -4
  87. package/src/build/route-types/include-resolution.ts +9 -2
  88. package/src/build/route-types/per-module-writer.ts +7 -4
  89. package/src/build/route-types/router-processing.ts +278 -88
  90. package/src/build/route-types/scan-filter.ts +9 -2
  91. package/src/build/route-types/source-scan.ts +118 -0
  92. package/src/build/runtime-discovery.ts +9 -20
  93. package/src/cache/cache-runtime.ts +15 -11
  94. package/src/cache/cache-scope.ts +76 -49
  95. package/src/cache/cf/cf-cache-store.ts +501 -18
  96. package/src/cache/cf/index.ts +5 -1
  97. package/src/cache/document-cache.ts +17 -7
  98. package/src/cache/index.ts +1 -0
  99. package/src/cache/taint.ts +55 -0
  100. package/src/client.rsc.tsx +5 -1
  101. package/src/client.tsx +95 -284
  102. package/src/context-var.ts +72 -2
  103. package/src/debug.ts +2 -2
  104. package/src/decode-loader-results.ts +36 -0
  105. package/src/errors.ts +30 -1
  106. package/src/handle.ts +65 -12
  107. package/src/handles/breadcrumbs.ts +66 -0
  108. package/src/handles/index.ts +1 -0
  109. package/src/host/index.ts +2 -5
  110. package/src/host/router.ts +129 -57
  111. package/src/host/types.ts +31 -2
  112. package/src/host/utils.ts +1 -1
  113. package/src/href-client.ts +140 -20
  114. package/src/index.rsc.ts +15 -40
  115. package/src/index.ts +92 -76
  116. package/src/loader-store.ts +500 -0
  117. package/src/loader.rsc.ts +2 -5
  118. package/src/loader.ts +3 -10
  119. package/src/missing-id-error.ts +68 -0
  120. package/src/outlet-context.ts +1 -1
  121. package/src/prerender/store.ts +57 -15
  122. package/src/prerender.ts +141 -80
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -15
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +435 -260
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +110 -34
  129. package/src/route-definition/index.ts +3 -3
  130. package/src/route-definition/redirect.ts +11 -3
  131. package/src/route-definition/resolve-handler-use.ts +155 -0
  132. package/src/route-definition/use-item-types.ts +32 -0
  133. package/src/route-map-builder.ts +7 -1
  134. package/src/route-types.ts +37 -41
  135. package/src/router/basename.ts +14 -0
  136. package/src/router/content-negotiation.ts +113 -1
  137. package/src/router/error-handling.ts +1 -1
  138. package/src/router/find-match.ts +4 -2
  139. package/src/router/handler-context.ts +105 -39
  140. package/src/router/intercept-resolution.ts +15 -22
  141. package/src/router/lazy-includes.ts +12 -9
  142. package/src/router/loader-resolution.ts +175 -23
  143. package/src/router/logging.ts +5 -2
  144. package/src/router/manifest.ts +31 -16
  145. package/src/router/match-api.ts +129 -193
  146. package/src/router/match-handlers.ts +63 -20
  147. package/src/router/match-middleware/background-revalidation.ts +30 -2
  148. package/src/router/match-middleware/cache-lookup.ts +136 -106
  149. package/src/router/match-middleware/cache-store.ts +54 -10
  150. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  151. package/src/router/match-middleware/segment-resolution.ts +61 -5
  152. package/src/router/match-result.ts +124 -18
  153. package/src/router/metrics.ts +239 -14
  154. package/src/router/middleware-types.ts +61 -31
  155. package/src/router/middleware.ts +226 -124
  156. package/src/router/navigation-snapshot.ts +182 -0
  157. package/src/router/pattern-matching.ts +118 -19
  158. package/src/router/prerender-match.ts +114 -10
  159. package/src/router/preview-match.ts +32 -102
  160. package/src/router/request-classification.ts +286 -0
  161. package/src/router/revalidation.ts +85 -9
  162. package/src/router/route-snapshot.ts +245 -0
  163. package/src/router/router-context.ts +6 -1
  164. package/src/router/router-interfaces.ts +91 -29
  165. package/src/router/router-options.ts +89 -19
  166. package/src/router/router-registry.ts +2 -5
  167. package/src/router/segment-resolution/fresh.ts +240 -23
  168. package/src/router/segment-resolution/helpers.ts +30 -25
  169. package/src/router/segment-resolution/loader-cache.ts +1 -0
  170. package/src/router/segment-resolution/revalidation.ts +483 -289
  171. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  172. package/src/router/segment-wrappers.ts +2 -0
  173. package/src/router/substitute-pattern-params.ts +56 -0
  174. package/src/router/telemetry.ts +99 -0
  175. package/src/router/trie-matching.ts +38 -15
  176. package/src/router/types.ts +9 -0
  177. package/src/router/url-params.ts +49 -0
  178. package/src/router.ts +120 -32
  179. package/src/rsc/handler-context.ts +2 -2
  180. package/src/rsc/handler.ts +524 -370
  181. package/src/rsc/helpers.ts +91 -43
  182. package/src/rsc/index.ts +1 -21
  183. package/src/rsc/loader-fetch.ts +23 -3
  184. package/src/rsc/manifest-init.ts +5 -1
  185. package/src/rsc/origin-guard.ts +28 -10
  186. package/src/rsc/progressive-enhancement.ts +39 -10
  187. package/src/rsc/response-route-handler.ts +46 -53
  188. package/src/rsc/rsc-rendering.ts +69 -89
  189. package/src/rsc/runtime-warnings.ts +9 -10
  190. package/src/rsc/server-action.ts +39 -47
  191. package/src/rsc/ssr-setup.ts +144 -0
  192. package/src/rsc/types.ts +19 -3
  193. package/src/search-params.ts +20 -17
  194. package/src/segment-content-promise.ts +67 -0
  195. package/src/segment-loader-promise.ts +122 -0
  196. package/src/segment-system.tsx +219 -67
  197. package/src/serialize.ts +243 -0
  198. package/src/server/context.ts +285 -63
  199. package/src/server/cookie-store.ts +28 -4
  200. package/src/server/handle-store.ts +19 -0
  201. package/src/server/loader-registry.ts +9 -8
  202. package/src/server/request-context.ts +228 -65
  203. package/src/server.ts +6 -0
  204. package/src/ssr/index.tsx +9 -1
  205. package/src/static-handler.ts +19 -7
  206. package/src/testing/cache-status.ts +166 -0
  207. package/src/testing/collect-handle.ts +63 -0
  208. package/src/testing/dispatch.ts +440 -0
  209. package/src/testing/dom.entry.ts +22 -0
  210. package/src/testing/e2e/fixture.ts +154 -0
  211. package/src/testing/e2e/index.ts +149 -0
  212. package/src/testing/e2e/matchers.ts +51 -0
  213. package/src/testing/e2e/page-helpers.ts +272 -0
  214. package/src/testing/e2e/parity.ts +306 -0
  215. package/src/testing/e2e/server.ts +183 -0
  216. package/src/testing/flight-matchers.ts +104 -0
  217. package/src/testing/flight-runtime.d.ts +21 -0
  218. package/src/testing/flight.entry.ts +22 -0
  219. package/src/testing/flight.ts +182 -0
  220. package/src/testing/generated-routes.ts +223 -0
  221. package/src/testing/index.ts +98 -0
  222. package/src/testing/internal/context.ts +151 -0
  223. package/src/testing/render-route.tsx +536 -0
  224. package/src/testing/run-loader.ts +296 -0
  225. package/src/testing/run-middleware.ts +170 -0
  226. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  227. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  228. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  229. package/src/testing/vitest-stubs/version.ts +5 -0
  230. package/src/testing/vitest.ts +112 -0
  231. package/src/theme/index.ts +4 -13
  232. package/src/types/cache-types.ts +4 -4
  233. package/src/types/global-namespace.ts +39 -26
  234. package/src/types/handler-context.ts +197 -79
  235. package/src/types/index.ts +1 -0
  236. package/src/types/loader-types.ts +41 -15
  237. package/src/types/request-scope.ts +126 -0
  238. package/src/types/route-config.ts +17 -8
  239. package/src/types/route-entry.ts +19 -1
  240. package/src/types/segments.ts +37 -6
  241. package/src/urls/include-helper.ts +34 -67
  242. package/src/urls/index.ts +0 -3
  243. package/src/urls/path-helper-types.ts +50 -9
  244. package/src/urls/path-helper.ts +63 -63
  245. package/src/urls/pattern-types.ts +48 -19
  246. package/src/urls/response-types.ts +25 -22
  247. package/src/urls/type-extraction.ts +26 -116
  248. package/src/urls/urls-function.ts +1 -5
  249. package/src/use-loader.tsx +487 -44
  250. package/src/vite/debug.ts +185 -0
  251. package/src/vite/discovery/bundle-postprocess.ts +63 -91
  252. package/src/vite/discovery/discover-routers.ts +106 -53
  253. package/src/vite/discovery/discovery-errors.ts +194 -0
  254. package/src/vite/discovery/gate-state.ts +171 -0
  255. package/src/vite/discovery/prerender-collection.ts +222 -107
  256. package/src/vite/discovery/route-types-writer.ts +40 -84
  257. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  258. package/src/vite/discovery/state.ts +50 -13
  259. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  260. package/src/vite/index.ts +10 -3
  261. package/src/vite/plugin-types.ts +111 -72
  262. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  263. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  265. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  266. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  267. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  268. package/src/vite/plugins/expose-action-id.ts +55 -33
  269. package/src/vite/plugins/expose-id-utils.ts +24 -8
  270. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  271. package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
  272. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  273. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  274. package/src/vite/plugins/expose-internal-ids.ts +544 -317
  275. package/src/vite/plugins/performance-tracks.ts +92 -0
  276. package/src/vite/plugins/refresh-cmd.ts +127 -0
  277. package/src/vite/plugins/use-cache-transform.ts +65 -50
  278. package/src/vite/plugins/version-injector.ts +39 -23
  279. package/src/vite/plugins/version-plugin.ts +72 -3
  280. package/src/vite/plugins/virtual-entries.ts +2 -2
  281. package/src/vite/rango.ts +265 -226
  282. package/src/vite/router-discovery.ts +924 -137
  283. package/src/vite/utils/ast-handler-extract.ts +15 -15
  284. package/src/vite/utils/banner.ts +4 -4
  285. package/src/vite/utils/bundle-analysis.ts +4 -2
  286. package/src/vite/utils/client-chunks.ts +190 -0
  287. package/src/vite/utils/forward-user-plugins.ts +193 -0
  288. package/src/vite/utils/manifest-utils.ts +21 -5
  289. package/src/vite/utils/package-resolution.ts +41 -1
  290. package/src/vite/utils/prerender-utils.ts +98 -5
  291. package/src/vite/utils/shared-utils.ts +109 -27
  292. package/src/browser/action-response-classifier.ts +0 -99
  293. package/src/route-definition/route-function.ts +0 -119
@@ -8,8 +8,67 @@ import {
8
8
  _getRequestContext,
9
9
  getLocationState,
10
10
  } from "../server/request-context.js";
11
+ import type { RequestContext } from "../server/request-context.js";
11
12
  import { resolveLocationStateEntries } from "../browser/react/location-state-shared.js";
13
+ import { isRedirectResponse } from "../response-utils.js";
12
14
  import type { MiddlewareEntry, MiddlewareFn } from "../router/middleware.js";
15
+ import { formatCacheSignalHeader } from "../router/telemetry.js";
16
+
17
+ /**
18
+ * DEVELOPMENT/TEST ONLY. When the debug cache signal gate is on,
19
+ * match/matchPartial populate ctx._cacheSignal. Emit it as the X-Rango-Cache
20
+ * header. When the gate is off, ctx._cacheSignal is undefined and NOTHING is
21
+ * attached — output is byte-identical to the default. Header mutation failures
22
+ * are swallowed so immutable Response headers (e.g. protocol-switch) are safe.
23
+ */
24
+ function applyCacheSignalHeader(target: Headers, ctx: RequestContext): void {
25
+ const signal = ctx._cacheSignal;
26
+ if (!signal || signal.length === 0) return;
27
+ try {
28
+ target.set("X-Rango-Cache", formatCacheSignalHeader(signal));
29
+ } catch {
30
+ // Headers immutable — skip.
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Copy stub headers from the request context onto a target Headers instance:
36
+ * append Set-Cookie entries, set everything else only if absent. Header
37
+ * mutation failures are swallowed so the same logic works against Response
38
+ * headers that may be immutable (e.g. Cloudflare protocol-switch responses).
39
+ */
40
+ function applyStubHeaders(target: Headers, stub: Headers): void {
41
+ stub.forEach((value, name) => {
42
+ try {
43
+ if (name.toLowerCase() === "set-cookie") {
44
+ target.append(name, value);
45
+ } else if (!target.has(name)) {
46
+ target.set(name, value);
47
+ }
48
+ } catch {
49
+ // Headers immutable — skip.
50
+ }
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Drain ctx._onResponseCallbacks onto a response. Swapping the array before
56
+ * iteration prevents re-entrant registrations from double-firing and matches
57
+ * the contract that each callback runs at most once per request.
58
+ */
59
+ function drainOnResponseCallbacks(
60
+ ctx: RequestContext,
61
+ response: Response,
62
+ ): Response {
63
+ const callbacks = ctx._onResponseCallbacks;
64
+ if (callbacks.length === 0) return response;
65
+ ctx._onResponseCallbacks = [];
66
+ let result = response;
67
+ for (const callback of callbacks) {
68
+ result = callback(result) ?? result;
69
+ }
70
+ return result;
71
+ }
13
72
 
14
73
  /**
15
74
  * Check if a request body has content to decode
@@ -39,40 +98,24 @@ export function createResponseWithMergedHeaders(
39
98
  return new Response(body, init);
40
99
  }
41
100
 
42
- // Merge headers from stub response into the new response.
43
- // Delete Set-Cookie from the stub after consuming so that downstream
44
- // merge points (e.g. executeMiddleware) do not duplicate them.
101
+ // Delete Set-Cookie from the stub after consuming so downstream merge
102
+ // points (e.g. executeMiddleware) don't duplicate them.
45
103
  const mergedHeaders = new Headers(init.headers);
46
- ctx.res.headers.forEach((value, name) => {
47
- if (name.toLowerCase() === "set-cookie") {
48
- mergedHeaders.append(name, value);
49
- } else if (!mergedHeaders.has(name)) {
50
- // Only set if not already present in init.headers
51
- mergedHeaders.set(name, value);
52
- }
53
- });
104
+ applyStubHeaders(mergedHeaders, ctx.res.headers);
54
105
  ctx.res.headers.delete("set-cookie");
106
+ applyCacheSignalHeader(mergedHeaders, ctx);
55
107
 
56
- // Use ctx.res.status if it was set (e.g., 404 for notFound, 500 for error)
57
- // Otherwise use the status from init
108
+ // ctx.res.status overrides init.status when explicitly set (e.g. 404 for
109
+ // notFound, 500 for error). Default ctx.res.status is 200.
58
110
  const status = ctx.res.status !== 200 ? ctx.res.status : init.status;
59
111
 
60
- let response = new Response(body, {
112
+ const response = new Response(body, {
61
113
  ...init,
62
114
  status,
63
115
  headers: mergedHeaders,
64
116
  });
65
117
 
66
- // Run onResponse callbacks - each can inspect/modify the response.
67
- // Drain the array so that downstream callers (e.g. finalizeResponse)
68
- // do not re-execute the same callbacks on this response.
69
- const callbacks = ctx._onResponseCallbacks;
70
- ctx._onResponseCallbacks = [];
71
- for (const callback of callbacks) {
72
- response = callback(response) ?? response;
73
- }
74
-
75
- return response;
118
+ return drainOnResponseCallbacks(ctx, response);
76
119
  }
77
120
 
78
121
  /**
@@ -122,10 +165,10 @@ export function interceptRedirectForPartial(
122
165
  locationState?: Record<string, unknown>,
123
166
  ) => Response,
124
167
  ): Response | null {
125
- const redirectUrl = response.headers.get("Location");
126
- if (!(response.status >= 300 && response.status < 400 && redirectUrl)) {
168
+ if (!isRedirectResponse(response)) {
127
169
  return null;
128
170
  }
171
+ const redirectUrl = response.headers.get("Location")!;
129
172
  const locationState = getLocationState();
130
173
  let intercepted: Response;
131
174
  if (locationState) {
@@ -175,24 +218,29 @@ export function buildRouteMiddlewareEntries<TEnv>(
175
218
  }
176
219
 
177
220
  /**
178
- * Run onResponse callbacks on an existing Response.
179
- *
180
- * Used for code paths that bypass createResponseWithMergedHeaders(), such as
181
- * middleware short-circuits where the Response is already constructed but
182
- * ctx.onResponse() callbacks still need to fire.
221
+ * Merge stub headers from the request context onto an existing Response in
222
+ * place, then drain onResponse callbacks. Used when a Response cannot flow
223
+ * through `new Response()` — status 101 is outside the constructor's
224
+ * 200-599 range, and the Cloudflare-specific `webSocket` property would be
225
+ * lost on reconstruction.
183
226
  */
184
- export function finalizeResponse(response: Response): Response {
227
+ export function mergeStubHeadersAndFinalize(response: Response): Response {
185
228
  const ctx = _getRequestContext();
186
- if (!ctx || ctx._onResponseCallbacks.length === 0) {
187
- return response;
188
- }
229
+ if (!ctx) return response;
189
230
 
190
- // Drain the array so callbacks run at most once per request.
191
- const callbacks = ctx._onResponseCallbacks;
192
- ctx._onResponseCallbacks = [];
193
- let result = response;
194
- for (const callback of callbacks) {
195
- result = callback(result) ?? result;
196
- }
197
- return result;
231
+ applyStubHeaders(response.headers, ctx.res.headers);
232
+ ctx.res.headers.delete("set-cookie");
233
+
234
+ return drainOnResponseCallbacks(ctx, response);
235
+ }
236
+
237
+ /**
238
+ * Run onResponse callbacks on an existing Response. Used by code paths that
239
+ * bypass createResponseWithMergedHeaders (e.g. middleware short-circuits)
240
+ * but still need ctx.onResponse() callbacks to fire.
241
+ */
242
+ export function finalizeResponse(response: Response): Response {
243
+ const ctx = _getRequestContext();
244
+ if (!ctx) return response;
245
+ return drainOnResponseCallbacks(ctx, response);
198
246
  }
package/src/rsc/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * RSC Router - RSC Entry Point
2
+ * Rango - RSC Entry Point
3
3
  *
4
4
  * This module provides RSC utilities for server-side rendering,
5
5
  * server actions, loader fetching, and progressive enhancement.
@@ -29,28 +29,8 @@ export type {
29
29
  NonceProvider,
30
30
  } from "./types.js";
31
31
 
32
- // Re-export HandleStore types for consumers who need custom handling
33
- export {
34
- createHandleStore,
35
- type HandleStore,
36
- type HandleData,
37
- } from "../server/handle-store.js";
38
-
39
32
  // Re-export request context utilities for server-side access to env/request/params
40
33
  export {
41
34
  getRequestContext,
42
35
  requireRequestContext,
43
- setRequestContextParams,
44
36
  } from "../server/request-context.js";
45
-
46
- // Re-export cache store types and implementations
47
- export type {
48
- SegmentCacheStore,
49
- CachedEntryData,
50
- CachedEntryResult,
51
- SegmentCacheProvider,
52
- SegmentHandleData,
53
- } from "../cache/types.js";
54
-
55
- export { MemorySegmentCacheStore } from "../cache/memory-segment-store.js";
56
- export { CFCacheStore, type CFCacheStoreOptions } from "../cache/cf/index.js";
@@ -168,8 +168,19 @@ export async function handleLoaderFetch<TEnv>(
168
168
  loaderResult: unknown;
169
169
  }
170
170
  const loaderPayload: LoaderPayload = { loaderResult: result };
171
- const rscStream =
172
- ctx.renderToReadableStream<LoaderPayload>(loaderPayload);
171
+ const rscStream = ctx.renderToReadableStream<LoaderPayload>(
172
+ loaderPayload,
173
+ {
174
+ onError: (error: unknown) => {
175
+ ctx.callOnError(error, "rendering", {
176
+ request,
177
+ url,
178
+ env,
179
+ loaderName: loaderId,
180
+ });
181
+ },
182
+ },
183
+ );
173
184
 
174
185
  return createResponseWithMergedHeaders(rscStream, {
175
186
  headers: { "content-type": "text/x-component;charset=utf-8" },
@@ -199,7 +210,16 @@ export async function handleLoaderFetch<TEnv>(
199
210
  name: err.name,
200
211
  },
201
212
  };
202
- const rscStream = ctx.renderToReadableStream(errorPayload);
213
+ const rscStream = ctx.renderToReadableStream(errorPayload, {
214
+ onError: (error: unknown) => {
215
+ ctx.callOnError(error, "rendering", {
216
+ request,
217
+ url,
218
+ env,
219
+ loaderName: loaderId,
220
+ });
221
+ },
222
+ });
203
223
 
204
224
  return createResponseWithMergedHeaders(rscStream, {
205
225
  status: 500,
@@ -31,7 +31,11 @@ export async function buildRouterTrieFromUrlpatterns(
31
31
  ): Promise<void> {
32
32
  const { generateManifestFull } =
33
33
  await import("../build/generate-manifest.js");
34
- const generated = generateManifestFull(router.urlpatterns);
34
+ const generated = generateManifestFull(
35
+ router.urlpatterns,
36
+ undefined,
37
+ router.basename ? { urlPrefix: router.basename } : undefined,
38
+ );
35
39
  if (
36
40
  generated._routeAncestry &&
37
41
  Object.keys(generated._routeAncestry).length > 0
@@ -9,11 +9,29 @@
9
9
  * navigations, bookmarks, and non-browser clients don't send Origin.
10
10
  */
11
11
 
12
+ import type { RequestPlan } from "../router/request-classification.js";
13
+
12
14
  /**
13
15
  * Request phase that triggered the origin check.
14
16
  */
15
17
  export type OriginCheckPhase = "action" | "loader" | "pe-form";
16
18
 
19
+ // Exhaustive over RequestPlan modes so a new mode must be classified here (the
20
+ // security gate) instead of silently falling through to no origin check.
21
+ export const ORIGIN_CHECK_PHASE_BY_MODE: Record<
22
+ RequestPlan["mode"],
23
+ OriginCheckPhase | null
24
+ > = {
25
+ action: "action",
26
+ loader: "loader",
27
+ "pe-render": "pe-form",
28
+ "full-render": null,
29
+ "partial-render": null,
30
+ response: null,
31
+ redirect: null,
32
+ "version-mismatch": null,
33
+ };
34
+
17
35
  /**
18
36
  * Context passed to the originCheck callback.
19
37
  */
@@ -116,14 +134,15 @@ export async function checkRequestOrigin<TEnv = any>(
116
134
  // Disabled by explicit opt-out
117
135
  if (config === false) return null;
118
136
 
119
- // Default: built-in validation (config === true or undefined)
120
- if (config === true || config === undefined) {
121
- const allowed = defaultOriginCheck(request, url);
122
- if (allowed) return null;
123
- return createForbiddenResponse(request);
124
- }
137
+ // Default (true/undefined) becomes a callback returning boolean, so the
138
+ // Response|true|reject resolution below is written once.
139
+ const check: (
140
+ ctx: OriginCheckContext<TEnv>,
141
+ ) => boolean | Response | Promise<boolean | Response> =
142
+ config === true || config === undefined
143
+ ? () => defaultOriginCheck(request, url)
144
+ : config;
125
145
 
126
- // Custom function — build context and call
127
146
  const ctx: OriginCheckContext<TEnv> = {
128
147
  request,
129
148
  url,
@@ -133,9 +152,8 @@ export async function checkRequestOrigin<TEnv = any>(
133
152
  defaultCheck: () => defaultOriginCheck(request, url),
134
153
  };
135
154
 
136
- const result = await config(ctx);
155
+ const result = await check(ctx);
137
156
 
138
157
  if (result instanceof Response) return result;
139
- if (result === true) return null;
140
- return createForbiddenResponse(request);
158
+ return result === true ? null : createForbiddenResponse(request);
141
159
  }
@@ -10,6 +10,7 @@ import {
10
10
  requireRequestContext,
11
11
  setRequestContextParams,
12
12
  } from "../server/request-context.js";
13
+ import { getSSRSetup } from "./ssr-setup.js";
13
14
  import type { MiddlewareFn } from "../router/middleware.js";
14
15
  import { executeMiddleware } from "../router/middleware.js";
15
16
  import type { RscPayload, ReactFormState } from "./types.js";
@@ -242,9 +243,13 @@ export async function handleProgressiveEnhancement<TEnv>(
242
243
  const payload: RscPayload = {
243
244
  metadata: {
244
245
  pathname: url.pathname,
246
+ routerId: ctx.router.id,
247
+ basename: ctx.router.basename,
245
248
  segments: match.segments,
246
249
  matched: match.matched,
247
250
  diff: match.diff,
251
+ resolvedIds: match.resolvedIds,
252
+ params: match.params,
248
253
  isPartial: false,
249
254
  rootLayout: ctx.router.rootLayout,
250
255
  handles: handleStore.stream(),
@@ -256,11 +261,21 @@ export async function handleProgressiveEnhancement<TEnv>(
256
261
  formState: actionResult,
257
262
  };
258
263
 
259
- const rscStream = ctx.renderToReadableStream<RscPayload>(payload);
260
- const [ssrModule, streamMode] = await Promise.all([
261
- ctx.loadSSRModule(),
262
- ctx.resolveStreamMode(request, env, url),
263
- ]);
264
+ const rscStream = ctx.renderToReadableStream<RscPayload>(payload, {
265
+ onError: (error: unknown) => {
266
+ ctx.callOnError(error, "rendering", { request, url, env });
267
+ },
268
+ });
269
+ // metricsStore=undefined is safe: the handler already stashed the early
270
+ // SSR setup promise on request variables, so getSSRSetup returns it
271
+ // without falling back to a fresh startSSRSetup.
272
+ const [ssrModule, streamMode] = await getSSRSetup(
273
+ ctx,
274
+ request,
275
+ env,
276
+ url,
277
+ undefined,
278
+ );
264
279
  const htmlStream = await ssrModule.renderHTML(rscStream, {
265
280
  formState: reactFormState,
266
281
  nonce,
@@ -335,9 +350,13 @@ async function renderPeErrorBoundary<TEnv>(
335
350
  const payload: RscPayload = {
336
351
  metadata: {
337
352
  pathname: url.pathname,
353
+ routerId: ctx.router.id,
354
+ basename: ctx.router.basename,
338
355
  segments: errorResult.segments,
339
356
  matched: errorResult.matched,
340
357
  diff: errorResult.diff,
358
+ resolvedIds: errorResult.resolvedIds,
359
+ params: errorResult.params,
341
360
  isPartial: false,
342
361
  isError: true,
343
362
  rootLayout: ctx.router.rootLayout,
@@ -349,11 +368,21 @@ async function renderPeErrorBoundary<TEnv>(
349
368
  },
350
369
  };
351
370
 
352
- const rscStream = ctx.renderToReadableStream<RscPayload>(payload);
353
- const [ssrModule, streamMode] = await Promise.all([
354
- ctx.loadSSRModule(),
355
- ctx.resolveStreamMode(request, env, url),
356
- ]);
371
+ const rscStream = ctx.renderToReadableStream<RscPayload>(payload, {
372
+ onError: (error: unknown) => {
373
+ ctx.callOnError(error, "rendering", { request, url, env });
374
+ },
375
+ });
376
+ // metricsStore=undefined is safe: the handler already stashed the early
377
+ // SSR setup promise on request variables, so getSSRSetup returns it
378
+ // without falling back to a fresh startSSRSetup.
379
+ const [ssrModule, streamMode] = await getSSRSetup(
380
+ ctx,
381
+ request,
382
+ env,
383
+ url,
384
+ undefined,
385
+ );
357
386
  const htmlStream = await ssrModule.renderHTML(rscStream, {
358
387
  nonce,
359
388
  streamMode,
@@ -11,6 +11,7 @@ import { requireRequestContext } from "../server/request-context.js";
11
11
  import { contextGet } from "../context-var.js";
12
12
  import { NOCACHE_SYMBOL } from "../cache/taint.js";
13
13
  import { traverseBack } from "../router/pattern-matching.js";
14
+ import { RESPONSE_TYPE_MIME } from "../router/content-negotiation.js";
14
15
  import { createCacheScope } from "../cache/cache-scope.js";
15
16
  import { executeMiddleware } from "../router/middleware.js";
16
17
  import {
@@ -26,7 +27,9 @@ import {
26
27
  finalizeResponse,
27
28
  isCacheableStatus,
28
29
  buildRouteMiddlewareEntries,
30
+ mergeStubHeadersAndFinalize,
29
31
  } from "./helpers.js";
32
+ import { isWebSocketUpgradeResponse } from "../response-utils.js";
30
33
 
31
34
  export interface ResponseRouteMatch {
32
35
  responseType: string;
@@ -78,10 +81,13 @@ export async function handleResponseRoute<TEnv>(
78
81
  env,
79
82
  searchParams: cleanUrl.searchParams,
80
83
  url: cleanUrl,
84
+ originalUrl: reqCtx.originalUrl,
81
85
  pathname: url.pathname,
82
86
  reverse: createReverseFunction(handlerCtx.getRequiredRouteMap()),
83
87
  get: ((keyOrVar: any) => contextGet(variables, keyOrVar)) as any,
84
88
  header: (name: string, value: string) => reqCtx.header(name, value),
89
+ waitUntil: reqCtx.waitUntil.bind(reqCtx),
90
+ executionContext: reqCtx.executionContext,
85
91
  _responseType: preview.responseType,
86
92
  };
87
93
  // Brand with taint symbol so "use cache" detects it as request-scoped
@@ -96,6 +102,12 @@ export async function handleResponseRoute<TEnv>(
96
102
  // so that stub headers (cookies, custom headers set via ctx.header()) are included.
97
103
  // Use Headers (not Record<string, string>) to preserve duplicate entries like Set-Cookie.
98
104
  const rewrapResponse = (result: Response) => {
105
+ // 204/205/304 are NOT short-circuited — they're valid for the Response
106
+ // constructor and must honor ctx.setStatus() overrides. Only upgrade
107
+ // responses (status 101 / `webSocket` property) bypass reconstruction.
108
+ if (isWebSocketUpgradeResponse(result)) {
109
+ return mergeStubHeadersAndFinalize(result);
110
+ }
99
111
  const headers = new Headers();
100
112
  result.headers.forEach((value, key) => {
101
113
  if (key.toLowerCase() === "set-cookie") {
@@ -110,13 +122,15 @@ export async function handleResponseRoute<TEnv>(
110
122
  });
111
123
  };
112
124
 
113
- // JSON response routes: wrap in { data } / { error } envelope
114
- if (preview.responseType === "json") {
115
- try {
116
- const result = await (preview.handler as Function)(responseHandlerCtx);
117
- if (result instanceof Response) {
118
- return rewrapResponse(result);
119
- }
125
+ try {
126
+ const result = await (preview.handler as Function)(responseHandlerCtx);
127
+
128
+ if (result instanceof Response) {
129
+ return rewrapResponse(result);
130
+ }
131
+
132
+ // Handled before the MIME lookup (json is also a RESPONSE_TYPE_MIME key).
133
+ if (preview.responseType === "json") {
120
134
  return createResponseWithMergedHeaders(
121
135
  JSON.stringify({ data: result }),
122
136
  {
@@ -124,10 +138,28 @@ export async function handleResponseRoute<TEnv>(
124
138
  headers: { "content-type": "application/json;charset=utf-8" },
125
139
  },
126
140
  );
127
- } catch (error) {
128
- handlerCtx.callOnError(error, "handler", errorCtx);
129
- const isDev = process.env.NODE_ENV !== "production";
130
- const status = error instanceof RouterError ? error.status : 500;
141
+ }
142
+
143
+ // Object.hasOwn (not truthiness) so prototype names like "toString" are not
144
+ // matched; image/stream/any are absent and fall through to the throw.
145
+ if (Object.hasOwn(RESPONSE_TYPE_MIME, preview.responseType)) {
146
+ return createResponseWithMergedHeaders(String(result), {
147
+ status: 200,
148
+ headers: {
149
+ "content-type": `${RESPONSE_TYPE_MIME[preview.responseType]};charset=utf-8`,
150
+ },
151
+ });
152
+ }
153
+
154
+ throw new Error(
155
+ `Response route handler for "${preview.responseType}" must return a Response object, got ${typeof result}`,
156
+ );
157
+ } catch (error) {
158
+ handlerCtx.callOnError(error, "handler", errorCtx);
159
+ const isDev = process.env.NODE_ENV !== "production";
160
+ const status = error instanceof RouterError ? error.status : 500;
161
+
162
+ if (preview.responseType === "json") {
131
163
  return createResponseWithMergedHeaders(
132
164
  JSON.stringify({
133
165
  error: createResponseErrorPayload(error, isDev),
@@ -138,48 +170,7 @@ export async function handleResponseRoute<TEnv>(
138
170
  },
139
171
  );
140
172
  }
141
- }
142
173
 
143
- // Non-JSON response routes: catch errors and return plain Response
144
- try {
145
- const result = await (preview.handler as Function)(responseHandlerCtx);
146
-
147
- if (result instanceof Response) {
148
- return rewrapResponse(result);
149
- }
150
-
151
- // Auto-wrap based on response type tag
152
- switch (preview.responseType) {
153
- case "text":
154
- return createResponseWithMergedHeaders(String(result), {
155
- status: 200,
156
- headers: { "content-type": "text/plain;charset=utf-8" },
157
- });
158
- case "html":
159
- return createResponseWithMergedHeaders(String(result), {
160
- status: 200,
161
- headers: { "content-type": "text/html;charset=utf-8" },
162
- });
163
- case "xml":
164
- return createResponseWithMergedHeaders(String(result), {
165
- status: 200,
166
- headers: { "content-type": "application/xml;charset=utf-8" },
167
- });
168
- case "md":
169
- return createResponseWithMergedHeaders(String(result), {
170
- status: 200,
171
- headers: { "content-type": "text/markdown;charset=utf-8" },
172
- });
173
- default:
174
- // image, stream, any -- must return Response
175
- throw new Error(
176
- `Response route handler for "${preview.responseType}" must return a Response object, got ${typeof result}`,
177
- );
178
- }
179
- } catch (error) {
180
- handlerCtx.callOnError(error, "handler", errorCtx);
181
- const isDev = process.env.NODE_ENV !== "production";
182
- const status = error instanceof RouterError ? error.status : 500;
183
174
  const message =
184
175
  error instanceof RouterError
185
176
  ? error.message
@@ -196,7 +187,9 @@ export async function handleResponseRoute<TEnv>(
196
187
  // Wrap callHandler to append Vary: Accept on content-negotiated responses
197
188
  const callHandlerWithVary = async () => {
198
189
  const response = await callHandler();
199
- if (preview.negotiated) {
190
+ if (preview.negotiated && !isWebSocketUpgradeResponse(response)) {
191
+ // Skip Vary on upgrade responses: headers are semantically immutable
192
+ // on some runtimes, and Vary is meaningless for a 101 response.
200
193
  response.headers.append("Vary", "Accept");
201
194
  }
202
195
  return response;