@rangojs/router 0.0.0-experimental.140 → 0.0.0-experimental.141

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.
@@ -1,386 +0,0 @@
1
- /**
2
- * PPR Shell Cache Middleware
3
- *
4
- * Axis 2 of the two-axis render model (see docs/design/ppr-shell-resume.md).
5
- * Opt-in middleware that caches the rendered HTML *shell* (React's `prelude`
6
- * plus the `postponed` state from a static `prerender` abort) and, on a later
7
- * request, serves those bytes immediately and resumes fizz for just the live
8
- * holes. The browser sees one ordinary streamed document.
9
- *
10
- * The middleware owns only the cheap URL/method gating and the stream
11
- * composition. The RENDER layer (rsc-rendering, integrated by a later stage) is
12
- * the final authority on whether a resume actually happens: it reads
13
- * requestCtx._shellResume, calls the resume strategy, and marks the response
14
- * with the internal `x-rango-shell-resumed` header ONLY when it truly resumed.
15
- * This middleware composes the cached prelude in front of the live response ONLY
16
- * when that marker is present; everything else (redirects, 404s, error renders,
17
- * nonce/allReady bypasses) flows through untouched — every non-resumed path
18
- * fails open to axis 1.
19
- *
20
- * Flow (the middleware calls next() EXACTLY ONCE on every path — the executor's
21
- * per-entry next() is a single-use latch, so a second call throws):
22
- * 1. Bypass matrix (non-GET, _rsc_* params, RSC request, skipPaths, isEnabled,
23
- * store lacks the shell family) → plain next(), axis 1.
24
- * 2. getShell(key) HIT + reactVersion matches → arm _shellResume, await next()
25
- * once. On a stale (SWR) hit, ALSO set the _shellCapture descriptor before
26
- * that same next() so the render layer schedules a background recapture.
27
- * - marker present → strip it, prepend prelude bytes, x-rango-shell: HIT.
28
- * - marker absent → render layer did not resume; return untouched.
29
- * 3. MISS (or reactVersion mismatch) → set the _shellCapture descriptor before
30
- * the single next(), stream the live response to the user with
31
- * x-rango-shell: MISS. The render layer reads the descriptor after building the
32
- * response and schedules a BACKGROUND capture (via router.match under a derived
33
- * context — NOT a second next()); see rsc-rendering.ts + shell-capture.ts.
34
- * The descriptor is cleared in a finally so it never leaks into a reused ctx.
35
- */
36
-
37
- import React from "react";
38
- import type { MiddlewareFn, MiddlewareContext } from "../router/middleware.js";
39
- import {
40
- getRequestContext,
41
- type RequestContext,
42
- } from "../server/request-context.js";
43
- import { mayNeedSSR } from "../rsc/ssr-setup.js";
44
- import type { SegmentCacheStore } from "./types.js";
45
- import { sortedSearchString } from "./cache-key-utils.js";
46
- import { reportCacheError } from "./cache-error.js";
47
-
48
- /** Debug/status header the browser (and e2e assertions) can read: HIT | MISS. */
49
- const SHELL_STATUS_HEADER = "x-rango-shell";
50
-
51
- /**
52
- * Internal marker the render layer sets on the live response when — and only
53
- * when — it actually resumed a cached shell. The middleware composes the prelude
54
- * in front of the body iff this header is present, then strips it before the
55
- * response leaves. It is the whole handshake between the middleware (which arms
56
- * _shellResume optimistically) and the render layer (the final authority).
57
- */
58
- const SHELL_RESUMED_MARKER_HEADER = "x-rango-shell-resumed";
59
-
60
- /**
61
- * React version captured at prerender time is the invalidation gate: a stored
62
- * shell whose reactVersion differs from the running React cannot be resumed (the
63
- * postponed blob is build-coupled), so it is treated as a miss. Read once at
64
- * module load — React.version is stable for the process lifetime.
65
- */
66
- const REACT_VERSION = React.version;
67
-
68
- /** Decode a base64 prelude back into bytes for stream composition. */
69
- function base64ToBytes(b64: string): Uint8Array {
70
- const binary = atob(b64);
71
- const bytes = new Uint8Array(binary.length);
72
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
73
- return bytes;
74
- }
75
-
76
- /**
77
- * Compose the served response: prelude bytes first, then the live (resumed) body.
78
- * React relies on HTML-parser foster-parenting for content streamed after the
79
- * prelude's closing `</body></html>`, so plain byte concatenation is the correct
80
- * composition (POC item 6) — do not try to reopen or splice the document.
81
- *
82
- * Status and headers come from the LIVE next() response: Set-Cookie and friends
83
- * are per-request and belong to the live pass, not the frozen shell. The internal
84
- * marker is stripped and x-rango-shell: HIT is added.
85
- */
86
- function composeShellResponse(
87
- response: Response,
88
- preludeBase64: string,
89
- ): Response {
90
- const preludeBytes = base64ToBytes(preludeBase64);
91
- const body = response.body;
92
- const composed = new ReadableStream<Uint8Array>({
93
- async start(controller) {
94
- controller.enqueue(preludeBytes);
95
- if (body) {
96
- const reader = body.getReader();
97
- try {
98
- for (;;) {
99
- const { done, value } = await reader.read();
100
- if (done) break;
101
- controller.enqueue(value);
102
- }
103
- } finally {
104
- reader.releaseLock();
105
- }
106
- }
107
- controller.close();
108
- },
109
- cancel(reason) {
110
- // Propagate downstream cancellation to the live body so it does not leak.
111
- return body?.cancel(reason);
112
- },
113
- });
114
-
115
- const headers = new Headers(response.headers);
116
- headers.delete(SHELL_RESUMED_MARKER_HEADER);
117
- headers.set(SHELL_STATUS_HEADER, "HIT");
118
- return new Response(composed, {
119
- status: response.status,
120
- statusText: response.statusText,
121
- headers,
122
- });
123
- }
124
-
125
- /** Clone a response with the x-rango-shell status header added. */
126
- function withShellStatus(response: Response, status: "HIT" | "MISS"): Response {
127
- const headers = new Headers(response.headers);
128
- headers.set(SHELL_STATUS_HEADER, status);
129
- return new Response(response.body, {
130
- status: response.status,
131
- statusText: response.statusText,
132
- headers,
133
- });
134
- }
135
-
136
- /**
137
- * Options for the PPR shell-cache middleware.
138
- */
139
- export interface ShellCacheOptions<TEnv = any> {
140
- /**
141
- * Cache store to use. Defaults to the request context's `_cacheStore`
142
- * (the app-level store wired via the router's cache config).
143
- */
144
- store?: SegmentCacheStore<TEnv>;
145
-
146
- /**
147
- * Shell time-to-live in seconds. Defaults to 300.
148
- */
149
- ttlSeconds?: number;
150
-
151
- /**
152
- * Stale-while-revalidate window in seconds. On a stale hit the cached shell is
153
- * still served and a background recapture is scheduled.
154
- */
155
- swrSeconds?: number;
156
-
157
- /**
158
- * Custom cache key generator. Receives the cleaned request URL. The middleware
159
- * appends its own `:shell` namespace suffix, so the returned key never collides
160
- * with a document-cache key.
161
- *
162
- * A custom generator owns the FULL key identity, including host scoping: the
163
- * default key incorporates `url.host` so shells can never leak across tenants
164
- * in multi-host deployments — include it in custom keys too unless the store
165
- * is provably single-host.
166
- */
167
- keyGenerator?: (url: URL) => string;
168
-
169
- /**
170
- * Callback to decide whether shell caching is enabled for this request.
171
- * Return false to fall through to a normal HTML render (axis 1).
172
- */
173
- isEnabled?: (ctx: MiddlewareContext<TEnv>) => boolean | Promise<boolean>;
174
-
175
- /**
176
- * Skip shell caching for specific path prefixes (e.g. admin, API routes).
177
- */
178
- skipPaths?: string[];
179
-
180
- /**
181
- * Enable debug logging for shell cache operations (HIT / MISS / CAPTURED).
182
- * Defaults to false.
183
- */
184
- debug?: boolean;
185
- }
186
-
187
- /**
188
- * Create the PPR shell-cache middleware.
189
- *
190
- * Add it to a router (or a route subtree) to cache the HTML shell and resume
191
- * fizz for just the live holes on subsequent requests. Personalization must live
192
- * in loaders/holes — the shell is shared per URL key (the shell-manifest
193
- * pattern). Actions, progressive enhancement, formState, and per-request nonce
194
- * always take axis 1.
195
- *
196
- * @example
197
- * ```typescript
198
- * const router = createRouter<AppEnv>()
199
- * .use(createShellCacheMiddleware({ ttlSeconds: 600, swrSeconds: 60 }))
200
- * .route("home", (ctx) => <HomePage />);
201
- * ```
202
- */
203
- export function createShellCacheMiddleware<TEnv = any>(
204
- options: ShellCacheOptions<TEnv> = {},
205
- ): MiddlewareFn<TEnv> {
206
- const {
207
- ttlSeconds = 300,
208
- swrSeconds,
209
- keyGenerator,
210
- isEnabled,
211
- skipPaths = [],
212
- debug = false,
213
- } = options;
214
-
215
- const log = debug ? (message: string) => console.log(message) : () => {};
216
-
217
- return async function shellCacheMiddleware(
218
- ctx: MiddlewareContext<TEnv>,
219
- next: () => Promise<Response>,
220
- ): Promise<Response> {
221
- const url = ctx.url;
222
- // ctx.url is stripped of _rsc_* params by the pipeline (stripInternalParams);
223
- // read the raw request URL for internal-param detection, like document-cache.
224
- const rawUrl = new URL(ctx.request.url);
225
-
226
- // --- Bypass matrix (each bypass = plain next(), axis 1) ---
227
-
228
- // Mutations are dynamic — never resume/capture a shell for them.
229
- if (ctx.request.method !== "GET") return next();
230
- // RSC action / loader / partial requests are not HTML document requests.
231
- if (rawUrl.searchParams.has("_rsc_action")) return next();
232
- if (rawUrl.searchParams.has("_rsc_loader")) return next();
233
- if (rawUrl.searchParams.has("_rsc_partial")) return next();
234
- // RSC (Flight) request — the Flight path is untouched by PPR.
235
- if (!mayNeedSSR(ctx.request, rawUrl)) return next();
236
- // Consumer opt-outs.
237
- if (skipPaths.some((path) => url.pathname.startsWith(path))) return next();
238
- if (isEnabled) {
239
- const enabled = await isEnabled(ctx);
240
- if (!enabled) return next();
241
- }
242
-
243
- const requestCtx = getRequestContext();
244
- const store = options.store ?? requestCtx?._cacheStore;
245
-
246
- // Store must implement the shell family — otherwise fail open to axis 1.
247
- if (!store?.getShell || !store?.putShell) return next();
248
-
249
- // Track whether next() has been called so the catch block knows whether it is
250
- // safe to fall through to the handler (mirrors document-cache). cacheKey is
251
- // assigned inside the try (a throwing keyGenerator must degrade, not 500).
252
- let handlerCalled = false;
253
- let cacheKey = "";
254
-
255
- /**
256
- * Build the "capture wanted" descriptor. Set on the request context BEFORE
257
- * the single next() so the render layer can read it after building the
258
- * response and schedule the background capture (via router.match under a
259
- * derived context — NOT a second next()). `store` is the SAME store this
260
- * middleware resolved for getShell, so a store-attached middleware writes
261
- * captures where it reads them. `tags` is intentionally omitted: the capture
262
- * collects the shell's own non-loader tags from its derived render.
263
- */
264
- const captureDescriptor = (): NonNullable<
265
- RequestContext["_shellCapture"]
266
- > => ({
267
- key: cacheKey,
268
- ttl: ttlSeconds,
269
- swr: swrSeconds,
270
- store,
271
- });
272
-
273
- try {
274
- // Namespace the key with a `:shell` suffix (mirrors document-cache's
275
- // `:html`/`:rsc` suffix) so it can never collide with a document-cache key;
276
- // the store further isolates the shell family internally. Built inside the
277
- // try so a throwing keyGenerator degrades to a full render, not a 500.
278
- //
279
- // The default key includes the request HOST: in a multi-tenant host-router
280
- // deployment (one worker, one shared KV/runtime-cache store) a host-less
281
- // key would serve tenant A's captured shell to tenant B's users. The CF
282
- // document family fixed this exact class at the store tier (toDocKVHost);
283
- // the shell family fixes it at the key tier so every store is safe.
284
- let searchSuffix = "";
285
- if (!keyGenerator) {
286
- const sorted = sortedSearchString(url.searchParams);
287
- if (sorted) searchSuffix = `?${sorted}`;
288
- }
289
- cacheKey = keyGenerator
290
- ? `${keyGenerator(url)}:shell`
291
- : `${url.host}${url.pathname}${searchSuffix}:shell`;
292
-
293
- const cached = await store.getShell(cacheKey);
294
- const validHit =
295
- cached != null && cached.entry.reactVersion === REACT_VERSION;
296
-
297
- if (cached && !validHit) {
298
- // reactVersion mismatch: the postponed blob is build-coupled and cannot
299
- // be resumed by the running React. There is no deleteShell primitive in
300
- // v1, so we simply treat it as a MISS — the recapture below overwrites
301
- // the same key, and the entry otherwise ages out via TTL.
302
- log(
303
- `[ShellCache] MISS ${url.pathname} (reactVersion ${cached.entry.reactVersion} != ${REACT_VERSION})`,
304
- );
305
- }
306
-
307
- if (validHit) {
308
- // Arm the resume optimistically. The render layer is the final authority
309
- // (nonce/formState/allReady bypass); it engages resume and marks the
310
- // response only when it actually resumed.
311
- if (requestCtx) {
312
- requestCtx._shellResume = { postponed: cached!.entry.postponed };
313
- // SWR: on a stale hit, also request a background recapture by setting
314
- // the descriptor before this single next(). Resume (foreground) and
315
- // capture-request (background) legitimately coexist now — the render
316
- // layer schedules the recapture off the descriptor after building the
317
- // resumed response. A fresh hit leaves the descriptor unset.
318
- if (cached!.shouldRevalidate) {
319
- requestCtx._shellCapture = captureDescriptor();
320
- }
321
- }
322
- handlerCalled = true;
323
- let response: Response;
324
- try {
325
- response = await next();
326
- } finally {
327
- // Always disarm both single-request flags. A next() throw here (resume
328
- // failure) propagates to the outer catch and rethrows; the
329
- // version-keyed entry self-heals via axis 1 + recapture on the next
330
- // request (v1 has no deleteShell to eagerly remove it).
331
- if (requestCtx) {
332
- requestCtx._shellResume = undefined;
333
- requestCtx._shellCapture = undefined;
334
- }
335
- }
336
-
337
- if (response.headers.has(SHELL_RESUMED_MARKER_HEADER)) {
338
- log(`[ShellCache] HIT ${url.pathname}`);
339
- return composeShellResponse(response, cached!.entry.prelude);
340
- }
341
-
342
- // Marker absent: the render layer did NOT resume (redirect, 404, error
343
- // render, per-request nonce, or allReady buffering). Fail open to axis 1
344
- // — return the live response untouched. Note: no manual onResponse-
345
- // callback drain is needed here (or on any path in this middleware),
346
- // because every path runs a full next() pipeline pass, which already
347
- // drains those callbacks — unlike document-cache, which serves a fully
348
- // cached response bypassing next() and must drain them itself.
349
- log(`[ShellCache] PASS ${url.pathname} (resume not engaged)`);
350
- return response;
351
- }
352
-
353
- // --- MISS (no entry, or reactVersion mismatch) ---
354
- // Set the "capture wanted" descriptor before the single next(). The render
355
- // layer reads it after building the response and, if the response is a
356
- // servable 200 HTML document, schedules a BACKGROUND capture (router.match
357
- // under a derived context — never a second next()). The descriptor's mere
358
- // presence does not change the foreground render (loader masking keys off
359
- // _shellCaptureRun, which only the background derived context sets).
360
- if (requestCtx) requestCtx._shellCapture = captureDescriptor();
361
- handlerCalled = true;
362
- let response: Response;
363
- try {
364
- response = await next();
365
- } finally {
366
- // Clear the descriptor so it never leaks into a reused ctx. The render
367
- // layer already read it (synchronously, inside next()) and captured its
368
- // own reference for the background task, so clearing here is safe.
369
- if (requestCtx) requestCtx._shellCapture = undefined;
370
- }
371
-
372
- log(`[ShellCache] MISS ${url.pathname}`);
373
- return withShellStatus(response, "MISS");
374
- } catch (error) {
375
- reportCacheError(error, "cache-read", "[ShellCache] middleware");
376
- if (handlerCalled) {
377
- // Post-handler failure (resume/render throw, or a stream error): do not
378
- // call next() again — that would re-run handler side effects.
379
- throw error;
380
- }
381
- // Pre-handler failure (cache lookup / key generation): degrade to a full
382
- // render.
383
- return next();
384
- }
385
- };
386
- }
@@ -1,130 +0,0 @@
1
- /**
2
- * live() — the deterministic PPR hole primitive (docs/design/ppr-shell-resume.md).
3
- *
4
- * A PPR shell is captured by masking loaders and freezing everything that
5
- * settles synchronously or on a microtask into the shared prelude. That freeze
6
- * has a sharp edge: a value that is ALREADY resolved — `Promise.resolve(x)`, an
7
- * in-memory lookup, a cached read — settles during the capture's quiet window
8
- * and gets baked into the shell, served to every user of the URL. That is
9
- * usually what you want (deterministic content belongs in the shell), but not
10
- * when the value is per-request. `live()` is the escape hatch: it makes its
11
- * boundary a deterministic HOLE regardless of how fast the data resolves, so the
12
- * capture postpones there and the resumed serve pass streams the fresh value in.
13
- *
14
- * It is the userland analogue of the loader mask (loader-mask.ts): during the
15
- * background shell-capture render `live()` returns a never-settling promise so
16
- * the consuming Suspense subtree suspends and React's static prerender postpones
17
- * it. Outside capture — the ordinary serve pass, and the client — it is a
18
- * passthrough: the thunk runs, or the promise passes through unchanged.
19
- *
20
- * Two forms:
21
- *
22
- * // Thunk (preferred): during capture the fn NEVER runs — no fetch, no cost.
23
- * const price = await live(() => fetchPrice());
24
- *
25
- * // Value: the work already fired before live() saw it, so during capture the
26
- * // real promise is discarded and a hole is returned in its place. Use the
27
- * // thunk form unless you already hold the promise.
28
- * const price = await live(pricePromise);
29
- *
30
- * The consumer story in one line: a hole even when the data is already resolved —
31
- * const x = await live(() => Promise.resolve(value)); // postpones under capture
32
- *
33
- * @see docs/design/ppr-shell-resume.md ("The live() hole primitive")
34
- */
35
-
36
- import { _getRequestContext } from "./request-context.js";
37
- import { isInsideCacheScope } from "./context.js";
38
- import { INSIDE_CACHE_EXEC } from "../cache/taint.js";
39
-
40
- /**
41
- * A promise that never settles — the capture-time hole. Same mechanism and
42
- * lifecycle as the loader mask (loader-mask.ts createMaskedLoaderPromise): the
43
- * consuming Suspense subtree suspends forever, so the static prerender postpones
44
- * it as a hole instead of baking a per-request value into the shared shell.
45
- * Nothing awaits it to settle — the capture aborts fizz to freeze the prelude
46
- * (maxWaitMs in captureShellHTML bounds that), and workerd/GC reclaims the
47
- * pending promise when the capture render tree is dropped. Kept never-settling
48
- * (not reject-on-abort) deliberately, to stay identical to the loader mask: a
49
- * capture-scoped reject signal would buy no capture-behavior difference, since
50
- * the abort — not the hole promise — is what ends the render.
51
- */
52
- function captureHole<T>(): Promise<T> {
53
- return new Promise<T>(() => {});
54
- }
55
-
56
- /** True only inside the background shell-capture render (shell-capture.ts sets
57
- * `_shellCaptureRun` on its derived context). Non-throwing: outside any request
58
- * context this is simply false, so live() passes through. */
59
- function isShellCaptureActive(): boolean {
60
- return _getRequestContext()?._shellCaptureRun === true;
61
- }
62
-
63
- /**
64
- * Mark a Suspense boundary as a deterministic PPR hole (see the module doc).
65
- *
66
- * @param fn - Thunk producing the live value. During shell capture it is NOT
67
- * invoked (no side effects, no cost); a never-settling promise is returned so
68
- * the boundary postpones. Outside capture it runs and its result is returned
69
- * as a promise.
70
- */
71
- export function live<T>(fn: () => Promise<T> | T): Promise<T>;
72
- /**
73
- * @param promise - A promise whose work has already fired. During shell capture
74
- * the promise is discarded and a hole is returned in its place (the work still
75
- * ran — prefer the thunk form to avoid that). Outside capture the promise
76
- * passes through unchanged.
77
- */
78
- export function live<T>(promise: Promise<T>): Promise<T>;
79
- export function live<T>(
80
- input: (() => Promise<T> | T) | Promise<T>,
81
- ): Promise<T> {
82
- assertNotInsideCacheBoundary();
83
- if (isShellCaptureActive()) {
84
- return captureHole<T>();
85
- }
86
- return typeof input === "function"
87
- ? Promise.resolve((input as () => Promise<T> | T)())
88
- : input;
89
- }
90
-
91
- /**
92
- * Throw when live() is called inside a cache boundary — a "use cache" function
93
- * (INSIDE_CACHE_EXEC stamped on the request context) or a cache() DSL scope.
94
- *
95
- * live() only masks during the SHELL capture (ring 4). The inner cache rings
96
- * freeze first: a cache()/prerender write deep-settles the promise and stores
97
- * its VALUE in the segment cache, and the handler never re-runs on replay — so
98
- * a live() there is silently inert, and if the value is per-request it is the
99
- * same shared-cache leak cookies()/headers() guard against, defeated by the
100
- * very primitive the caller believed made it safe. A "use cache" miss during a
101
- * capture render is worse: the fn body runs under the capture flag, live()
102
- * returns a never-settling promise, and the cache write wedges awaiting it.
103
- * Same guard shape as assertNotInsideCacheContext in cookie-store.ts.
104
- */
105
- function assertNotInsideCacheBoundary(): void {
106
- const ctx = _getRequestContext();
107
- if (
108
- ctx !== null &&
109
- ctx !== undefined &&
110
- (INSIDE_CACHE_EXEC as symbol) in (ctx as unknown as Record<symbol, unknown>)
111
- ) {
112
- throw new Error(
113
- `live() cannot be called inside a "use cache" function. The cached ` +
114
- `function's value is stored and replayed, so nothing inside it can ` +
115
- `stay live — and per-request data would be frozen into a shared ` +
116
- `cache entry. Read live data in a loader instead (loaders are never ` +
117
- `cached), or move the live() call outside the cached function.`,
118
- );
119
- }
120
- if (isInsideCacheScope()) {
121
- throw new Error(
122
- `live() cannot be called inside a cache() boundary. The segment cache ` +
123
- `deep-settles and stores the resolved VALUE at write time, and the ` +
124
- `handler never re-runs on a cache hit — so live() cannot keep this ` +
125
- `value live, and per-request data would be frozen into the shared ` +
126
- `cached segments. Use a loader behind loading() instead: loaders are ` +
127
- `the live lane through every cache ring.`,
128
- );
129
- }
130
- }