@rsc-kit/core 0.7.2 → 0.8.0

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.
package/dist/headers.d.ts CHANGED
@@ -44,6 +44,26 @@ export declare const HEADER: {
44
44
  * unconditionally.
45
45
  */
46
46
  readonly actionPath: '/_rsc/action';
47
+ /**
48
+ * Where the browser reads queries.
49
+ *
50
+ * A GET, and that is the whole point of it being a separate address: a POST
51
+ * is cacheable by nothing, so a read routed through the action endpoint can
52
+ * never be kept by an HTTP cache, a CDN or a service worker. Only functions
53
+ * declared with `query()` are reachable here — the endpoint checks the mark
54
+ * before invoking anything, because otherwise this address would run any
55
+ * registered action over GET.
56
+ */
57
+ /**
58
+ * Sent on every read, and required by the query endpoint.
59
+ *
60
+ * A GET with no unusual header is a simple request, so any page could
61
+ * trigger one with an <img> and the visitor's cookies would ride along.
62
+ * This header is not CORS-safelisted, so the browser preflights it — the
63
+ * same thing that makes a POST carrying X-RSC-Action safe.
64
+ */
65
+ readonly query: 'X-RSC-Query';
66
+ readonly queryPath: '/_rsc/query';
47
67
  /** Build-time shell for a PPR route, for an edge cache to hold. */
48
68
  readonly pprShellPath: '/_rsc/ppr-shell';
49
69
  /** Finish a shell an edge cache is already serving. */
package/dist/headers.js CHANGED
@@ -53,6 +53,26 @@ export const HEADER = {
53
53
  * unconditionally.
54
54
  */
55
55
  actionPath: '/_rsc/action',
56
+ /**
57
+ * Where the browser reads queries.
58
+ *
59
+ * A GET, and that is the whole point of it being a separate address: a POST
60
+ * is cacheable by nothing, so a read routed through the action endpoint can
61
+ * never be kept by an HTTP cache, a CDN or a service worker. Only functions
62
+ * declared with `query()` are reachable here — the endpoint checks the mark
63
+ * before invoking anything, because otherwise this address would run any
64
+ * registered action over GET.
65
+ */
66
+ /**
67
+ * Sent on every read, and required by the query endpoint.
68
+ *
69
+ * A GET with no unusual header is a simple request, so any page could
70
+ * trigger one with an <img> and the visitor's cookies would ride along.
71
+ * This header is not CORS-safelisted, so the browser preflights it — the
72
+ * same thing that makes a POST carrying X-RSC-Action safe.
73
+ */
74
+ query: 'X-RSC-Query',
75
+ queryPath: '/_rsc/query',
56
76
  /** Build-time shell for a PPR route, for an edge cache to hold. */
57
77
  pprShellPath: '/_rsc/ppr-shell',
58
78
  /** Finish a shell an edge cache is already serving. */
@@ -1 +1 @@
1
- {"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,gCAAgC;AAChC,EAAE;AACF,gFAAgF;AAEhF,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,GAAG,EAAE,OAAO;IAEZ,iFAAiF;IACjF,QAAQ,EAAE,gBAAgB;IAE1B,kEAAkE;IAClE,YAAY,EAAE,qBAAqB;IAEnC,wCAAwC;IACxC,OAAO,EAAE,eAAe;IAExB,gFAAgF;IAChF,OAAO,EAAE,eAAe;IAExB,uDAAuD;IACvD,SAAS,EAAE,iBAAiB;IAE5B,gDAAgD;IAChD,OAAO,EAAE,eAAe;IAExB,uEAAuE;IACvE,UAAU,EAAE,kBAAkB;IAE9B,0CAA0C;IAC1C,MAAM,EAAE,cAAc;IAEtB;;;;;;;OAOG;IACH,QAAQ,EAAE,gBAAgB;IAE1B;;;;;;OAMG;IACH,WAAW,EAAE,oBAAoB;IAEjC;;;;;OAKG;IACH,UAAU,EAAE,cAAc;IAC1B,mEAAmE;IACnE,YAAY,EAAE,iBAAiB;IAC/B,uDAAuD;IACvD,aAAa,EAAE,kBAAkB;CACzB,CAAA;AAEV,sBAAsB;AACtB,MAAM,CAAC,MAAM,WAAW,GAAG,iCAAiC,CAAA;AAE5D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,SAAS,GAAG,0BAA0B,CAAA;AAEnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,GAAG;IACV,MAAM,CAAC,QAAQ;IACf,MAAM,CAAC,UAAU;IACjB,MAAM,CAAC,SAAS;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /** Build-time shell for a PPR route, for an edge cache to hold. */\n pprShellPath: '/_rsc/ppr-shell',\n /** Finish a shell an edge cache is already serving. */\n pprResumePath: '/_rsc/ppr-resume',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n"]}
1
+ {"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,gCAAgC;AAChC,EAAE;AACF,gFAAgF;AAEhF,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,GAAG,EAAE,OAAO;IAEZ,iFAAiF;IACjF,QAAQ,EAAE,gBAAgB;IAE1B,kEAAkE;IAClE,YAAY,EAAE,qBAAqB;IAEnC,wCAAwC;IACxC,OAAO,EAAE,eAAe;IAExB,gFAAgF;IAChF,OAAO,EAAE,eAAe;IAExB,uDAAuD;IACvD,SAAS,EAAE,iBAAiB;IAE5B,gDAAgD;IAChD,OAAO,EAAE,eAAe;IAExB,uEAAuE;IACvE,UAAU,EAAE,kBAAkB;IAE9B,0CAA0C;IAC1C,MAAM,EAAE,cAAc;IAEtB;;;;;;;OAOG;IACH,QAAQ,EAAE,gBAAgB;IAE1B;;;;;;OAMG;IACH,WAAW,EAAE,oBAAoB;IAEjC;;;;;OAKG;IACH,UAAU,EAAE,cAAc;IAC1B;;;;;;;;;OASG;IACH;;;;;;;OAOG;IACH,KAAK,EAAE,aAAa;IAEpB,SAAS,EAAE,aAAa;IACxB,mEAAmE;IACnE,YAAY,EAAE,iBAAiB;IAC/B,uDAAuD;IACvD,aAAa,EAAE,kBAAkB;CACzB,CAAA;AAEV,sBAAsB;AACtB,MAAM,CAAC,MAAM,WAAW,GAAG,iCAAiC,CAAA;AAE5D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,SAAS,GAAG,0BAA0B,CAAA;AAEnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,GAAG;IACV,MAAM,CAAC,QAAQ;IACf,MAAM,CAAC,UAAU;IACjB,MAAM,CAAC,SAAS;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /**\n * Where the browser reads queries.\n *\n * A GET, and that is the whole point of it being a separate address: a POST\n * is cacheable by nothing, so a read routed through the action endpoint can\n * never be kept by an HTTP cache, a CDN or a service worker. Only functions\n * declared with `query()` are reachable here — the endpoint checks the mark\n * before invoking anything, because otherwise this address would run any\n * registered action over GET.\n */\n /**\n * Sent on every read, and required by the query endpoint.\n *\n * A GET with no unusual header is a simple request, so any page could\n * trigger one with an <img> and the visitor's cookies would ride along.\n * This header is not CORS-safelisted, so the browser preflights it — the\n * same thing that makes a POST carrying X-RSC-Action safe.\n */\n query: 'X-RSC-Query',\n\n queryPath: '/_rsc/query',\n /** Build-time shell for a PPR route, for an edge cache to hold. */\n pprShellPath: '/_rsc/ppr-shell',\n /** Finish a shell an edge cache is already serving. */\n pprResumePath: '/_rsc/ppr-resume',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n"]}
package/dist/host.d.ts CHANGED
@@ -49,6 +49,17 @@ export interface RscEngine {
49
49
  handleAction(actionId: string, body: Uint8Array | string | FormData, contentType?: string, page?: unknown, takeRevalidated?: () => string[]): Promise<{
50
50
  stream: ReadableStream;
51
51
  }>;
52
+ /**
53
+ * Answer one read declared with `query()`, or null if that id is not one.
54
+ *
55
+ * Optional so a host can be pointed at a bundle built before queries existed;
56
+ * without it the endpoint 404s rather than throwing, which is what a client
57
+ * built against the same old bundle expects anyway.
58
+ */
59
+ handleQuery?(id: string, args: string, report?: (error: unknown) => string): Promise<{
60
+ stream: ReadableStream;
61
+ cacheControl: string;
62
+ } | null>;
52
63
  }
53
64
  export interface RscHostOptions {
54
65
  /** The built server bundle — `import * as engine from './build/rsc/index.js'`. */
package/dist/host.js CHANGED
@@ -179,6 +179,18 @@ export function actionOriginAllowed(request, url) {
179
179
  return false;
180
180
  }
181
181
  }
182
+ /**
183
+ * How large a query url may be before it is refused.
184
+ *
185
+ * Matched to the client's own limit, and enforced here too because the limit is
186
+ * what keeps an attacker from making this endpoint decode megabytes of
187
+ * attacker-chosen payload per request.
188
+ *
189
+ * Module scope, not inside the handler: everything declared after the handler
190
+ * is returned never initialises, and a `const` read from the closure then
191
+ * throws on every request instead of being undefined.
192
+ */
193
+ const MAX_QUERY = 8_000;
182
194
  export function createRscHandler(options) {
183
195
  const { engine, assets, version } = options;
184
196
  // Annotated rather than inferred: the narrowing below is lost inside the
@@ -303,6 +315,16 @@ export function createRscHandler(options) {
303
315
  }
304
316
  return await handleAction(request, url);
305
317
  }
318
+ if (request.method === 'GET' && url.pathname === HEADER.queryPath) {
319
+ // Same check as an action, for a smaller reason: a cross-origin page
320
+ // cannot read this answer — CORS sees to that — but it can still cause
321
+ // the read to run with the visitor's cookies. A query is side-effect
322
+ // free by contract, so this is depth rather than the only defence.
323
+ if (!actionOriginAllowed(request, url)) {
324
+ return new Response('Cross-origin query', { status: 403 });
325
+ }
326
+ return await handleQuery(request, url);
327
+ }
306
328
  // The two halves an edge cache needs: hand it a shell it may keep, and
307
329
  // finish that shell for a visitor it cannot answer for itself.
308
330
  if (options.prerendered && url.pathname === HEADER.pprShellPath) {
@@ -846,6 +868,44 @@ export function createRscHandler(options) {
846
868
  }),
847
869
  });
848
870
  }
871
+ async function handleQuery(request, url) {
872
+ if (!engine.handleQuery)
873
+ return null;
874
+ // Required, and the reason is CSRF rather than routing. A GET carrying no
875
+ // unusual header is a SIMPLE request: any page anywhere can trigger one
876
+ // with <img src="…/_rsc/query?…"> and it goes out with the visitor's
877
+ // cookies. CORS stops them reading the answer; it does not stop the read
878
+ // running. This header is not CORS-safelisted, so a browser preflights it
879
+ // and nothing here answers a preflight — the same protection a POST
880
+ // carrying X-RSC-Action already had.
881
+ if (!request.headers.get(HEADER.query)) {
882
+ return new Response('Missing ' + HEADER.query, { status: 400 });
883
+ }
884
+ const id = url.searchParams.get('id');
885
+ const args = url.searchParams.get('args');
886
+ if (!id || args === null)
887
+ return new Response('Missing id or args', { status: 400 });
888
+ // Enforced here as well as in the client, because the limit is what keeps
889
+ // an attacker from making this endpoint decode megabytes of their payload
890
+ // per request.
891
+ if (url.search.length > MAX_QUERY)
892
+ return new Response('Query too large', { status: 414 });
893
+ const answered = await engine.handleQuery(id, args);
894
+ // Unknown id and registered-but-not-a-query are the same answer on purpose.
895
+ if (!answered)
896
+ return new Response('No such query', { status: 404 });
897
+ return new Response(answered.stream, {
898
+ headers: withVersion({
899
+ 'Content-Type': FLIGHT_TYPE,
900
+ 'Cache-Control': answered.cacheControl,
901
+ // The answer is narrowed by who is asking whenever a read touches the
902
+ // session, and the request that carries that is the cookie. Without
903
+ // this a shared cache keyed on the url alone hands one visitor
904
+ // another's answer — for any query that opted out of no-store.
905
+ Vary: 'Cookie, ' + HEADER.referer,
906
+ }),
907
+ });
908
+ }
849
909
  async function handleAction(request, url) {
850
910
  const actionId = request.headers.get(HEADER.action);
851
911
  if (!actionId)
package/dist/host.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,mDAAmD;AACnD,EAAE;AACF,2EAA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AE3E,qEAAqE;QACrE,sEAAsE;QACtE,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,OAAO,CAAC,WAAW,EAAE,CAAC,CAAA;QACxD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,0BAA0B,CAAA;QAEzF,uEAAuE;QACvE,2DAA2D;QAC3D,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QACnD,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;QACxF,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QAEnF,wEAAwE;QACxE,yEAAyE;QACzE,gCAAgC;QAChC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,gBAAgB,CAAC,CAAC,KAAK,EAAE,EAAE,CAClD,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,CAAC,CAC9D,CAAA;QAED,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE;YAC1B,OAAO,EAAE,WAAW,CAAC,EAAE,cAAc,EAAE,iCAAiC,EAAE,CAAC;SAC5E,CAAC,CAAA;IACJ,CAAC;AACH,CAAC","sourcesContent":["// Everything a JavaScript host has to do to serve the RSC engine.\n//\n// PHP needs ~2,400 lines for this because it cannot run JavaScript: a socket\n// bridge, a worker pool, a frame protocol. A JS host imports the engine and\n// calls it, and what remains is the part every host would otherwise rewrite —\n// matching a url to a route, negotiating how much of the page to send, and\n// speaking the header protocol the client expects.\n//\n// Deliberately not Hono, or Express, or anything: this takes a Request and\n// returns a Response, so it runs under Bun.serve, Deno, Workers, Node's\n// fetch adapters and any framework built on them. `./hono` is the three-line\n// binding for one of them.\n//\n// const rsc = createRscHandler({ engine, manifest, assets })\n// Bun.serve({ fetch: (req) => rsc(req).then((r) => r ?? new Response('', { status: 404 })) })\n\nimport { matchIntercept, matchRoute, retentionKey, sharedDepth } from './routing.js'\nimport { pathKey, patternKey } from './prerender.js'\nimport { withRevalidation } from './revalidate.js'\nexport { revalidate } from './revalidate.js'\nimport { withRedirect } from './redirect.js'\nimport { withCache } from './cache.js'\nimport { withRequest, withResponseDraft } from './request.js'\nimport type { Redirection } from './redirect.js'\nexport { redirect } from './redirect.js'\n// Re-exported, not redefined: routing.ts is the one implementation, shared with\n// the prerenderer and the generated bundle, and this stays the adapter's\n// public surface so a host imports from one place.\nexport { matchIntercept, matchRoute, sharedDepth } from './routing.js'\nexport type { MatchedRoute } from './routing.js'\nimport { FLIGHT_TYPE, HEADER, HTML_TYPE, PER_CLIENT, REVALIDATE, VARY_ON_RSC } from './headers.js'\nimport type { MatchedRoute } from './routing.js'\nimport { ServerAuthenticationError, ServerAuthorizationError } from './js/errors.js'\nimport type { RouteManifest } from './manifest.js'\n\n/** The built server bundle. Only the parts a host calls. */\nexport interface RscEngine {\n /** The route table this bundle was built from. */\n manifest?(): RouteManifest\n installHostFn(fn: (name: string, ...args: unknown[]) => unknown): void\n handleRscStream(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n from?: number,\n pageKey?: string,\n ): Promise<{ stream: ReadableStream; segmentDepth: number }>\n handleRscHtmlStream(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n nonce?: string,\n pageKey?: string,\n bootstrap?: boolean,\n ): Promise<{ htmlStream: ReadableStream }>\n /**\n * Finish a shell frozen at build time, against data that exists now.\n *\n * Emits only the boundaries the shell left unfinished, meant to be written\n * straight after it. Optional so a host can be pointed at an engine built\n * before resuming existed; without it a shell has no way to be completed and\n * the page is rendered whole instead.\n */\n handleRscResume?(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n postponed?: unknown,\n nonce?: string,\n pageKey?: string,\n ): Promise<{ htmlStream: ReadableStream }>\n handleRscRevalidate?(target: string, page: unknown): Promise<{ rscPayload: string }>\n /**\n * Run a route's middleware without rendering anything.\n *\n * For a frozen page: the host reads it from disk and the engine never sees\n * the request, so the check has to be asked for separately.\n */\n runRouteMiddleware?(component: string, props: Record<string, unknown>): Promise<void>\n handleAction(\n actionId: string,\n body: Uint8Array | string | FormData,\n contentType?: string,\n page?: unknown,\n takeRevalidated?: () => string[],\n ): Promise<{ stream: ReadableStream }>\n}\n\nexport interface RscHostOptions {\n /** The built server bundle — `import * as engine from './build/rsc/index.js'`. */\n engine: RscEngine\n /**\n * The route table. Defaults to the one the bundle was built with, which is\n * almost always what you want — a manifest passed separately can go stale\n * against the bundle it is describing.\n */\n manifest?: RouteManifest\n /**\n * Functions the app's server components call as `await rpc('name', ...args)`.\n *\n * In the Laravel host this crosses a socket into PHP. Here they are just\n * functions, which is the whole reason a JS host is smaller.\n */\n rpc?: Record<string, (...args: unknown[]) => unknown>\n /**\n * Where a host call goes when this process cannot answer it.\n *\n * `rpc` is checked first, so a host can answer some calls in JS and leave\n * the rest to a backend. `httpHostCalls` in `@rsc-kit/core/host-calls`\n * builds one of these over an ordinary POST, which is how a host written in\n * another language answers without implementing the socket framing.\n */\n hostCalls?: (name: string, ...args: unknown[]) => Promise<unknown>\n /**\n * Props for a page, given whatever its url bound.\n *\n * Defaults to the url params alone. A host that loads a user, reads a\n * session or resolves a tenant does it here — this is the one place the\n * engine cannot supply anything for.\n */\n props?: (match: MatchedRoute, request: Request) => Record<string, unknown> | Promise<Record<string, unknown>>\n /**\n * Reads what the prerenderer wrote, if this build has any.\n *\n * A function rather than a directory, because not every host has a\n * filesystem: on an edge runtime these live in a KV store or a static-asset\n * binding. `prerenderedFrom` in `@rsc-kit/core/files` is the one for a disk.\n *\n * Checked before rendering, and anything it cannot find falls through to\n * being rendered now — so a partial prerender is a valid state, not a\n * broken one.\n */\n prerendered?: (name: string) => Promise<string | null> | string | null\n /** Serve a built browser asset. Return null for anything not found. */\n assets?: (pathname: string, request: Request) => Promise<Response | null> | Response | null\n /**\n * Identifies this build to the client, which compares it on every\n * navigation and falls back to a full load when it changes. Without one a\n * client keeps talking to a deployment that no longer exists — worst behind\n * a CDN, where the shell it holds may already be from an older build.\n */\n version?: string\n}\n\n/**\n * The answer to a redirect that was decided before anything was written.\n *\n * A document gets a real status code. A payload request must NOT: `fetch`\n * follows a 3xx transparently, so the client would receive the destination's\n * HTML and hand it to the Flight decoder, which reports its own confusion\n * rather than the redirect. It gets 204 and a header instead, and navigates\n * itself — which is also what makes the redirect an SPA one.\n */\n/**\n * A string safe to write inside a <script> element.\n *\n * `JSON.stringify` escapes for JavaScript, and this is not a JavaScript\n * context — it is HTML that happens to contain JavaScript. The parser ends the\n * element at the first `</script`, wherever it appears, so a destination\n * carrying one closes the tag and whatever follows is markup the browser runs.\n *\n * That destination is routinely computed rather than written — redirect()\n * documents \"remembering where someone was going and sending them back to it\"\n * as the usual case, which is a query string or a cookie arriving verbatim\n * here. U+2028 and U+2029 are escaped too: legal in JSON, line terminators in\n * JavaScript.\n */\nfunction inScript(value: string): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\nfunction redirectResponse(to: Redirection, isPayloadRequest: boolean): Response {\n if (isPayloadRequest) {\n return new Response(null, {\n status: 204,\n headers: { [HEADER.redirect]: to.location, Vary: VARY_ON_RSC },\n })\n }\n\n return new Response(null, {\n status: to.status,\n headers: { Location: to.location, Vary: VARY_ON_RSC },\n })\n}\n\n/**\n * Append the redirect a render asked for after its shell had already gone out.\n *\n * The status line is spent by then, so the instruction travels in the body. A\n * script rather than waiting for hydration to notice the error digest: it runs\n * as the browser parses it, which is sooner, and it is the only path that\n * works at all for a route shipping no client runtime.\n *\n * Read on flush, because that is when the render has finished and a redirect\n * from inside a Suspense boundary is finally known.\n */\nfunction appendLateRedirect(\n stream: ReadableStream,\n taken: () => Redirection | null,\n): ReadableStream {\n // An engine that answered with a finished body rather than a stream has no\n // late window at all: the render was over before this was called, so the\n // caller's own check already saw everything there was to see.\n if (typeof stream?.getReader !== 'function') return stream\n\n const encoder = new TextEncoder()\n const reader = stream.getReader()\n\n // Read-and-re-emit rather than pipeThrough(new TransformStream(...)): a\n // TransformStream from a different realm than the stream it is piped into\n // is rejected outright, and a host embedded in a runtime that supplies its\n // own web streams is exactly that case.\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read()\n\n if (!done) {\n controller.enqueue(value)\n\n return\n }\n\n const to = taken()\n\n // replace, so Back does not return to a url that redirected.\n if (to) {\n controller.enqueue(encoder.encode(`<script>location.replace(${inScript(to.location)})</script>`))\n }\n\n controller.close()\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n}\n\n/**\n * The status a refusal deserves, or null when this was not one.\n *\n * A host answers an unauthenticated call 401 and an unauthorized one 403, and\n * the transport raises each as its own error. Without this they arrive at the\n * render as ordinary failures and leave as 500s — which reads, to anyone\n * looking at a log or a browser, as the application being broken rather than\n * the visitor being turned away.\n */\nfunction refusalStatus(error: unknown): number | null {\n if (error instanceof ServerAuthenticationError) return 401\n if (error instanceof ServerAuthorizationError) return 403\n\n // Named rather than matched by identity, because the error may have been\n // raised by another copy of the module: an app's actions are bundled apart\n // from the engine, and instanceof is false across that seam.\n const name = (error as { name?: string } | null)?.name\n\n if (name === 'ServerAuthenticationError') return 401\n if (name === 'ServerAuthorizationError') return 403\n\n // A status the host chose — a throttle's 429, a policy's 403 — carried on\n // the error by the transport. Bounded to refusals: a host answering 500\n // should not be able to make this look like a client's fault, and one\n // answering 200 should not turn a failed render into a success.\n const carried = (error as { refusalStatus?: unknown } | null)?.refusalStatus\n\n if (typeof carried === 'number' && carried >= 400 && carried <= 499) return carried\n\n return null\n}\n\nfunction refusalMessage(error: unknown): string {\n const message = (error as { message?: string } | null)?.message\n\n return typeof message === 'string' && message !== '' ? message : 'Refused.'\n}\n\n/**\n * Whether a browser was told it could post this action.\n *\n * Defence in depth, not the only defence. An action already requires the\n * X-RSC-Action header, which makes a cross-origin post a non-simple request —\n * so the browser must preflight it, and nothing here answers a preflight. A\n * browser can be tricked into sending cookies; it cannot be tricked into\n * sending a header it does not know. This is the belt to that pair of braces,\n * and it is what Next does for server actions.\n *\n * Compared against X-Forwarded-Host first, because a proxied deployment is the\n * normal one: the backend forwards the name the visitor typed, while Host is\n * this process on loopback. Comparing against Host alone would reject every\n * legitimate action that arrived through a proxy — a check that only fires on\n * correct requests is worse than none.\n *\n * No Origin at all is allowed through. It is absent on same-origin requests in\n * some browsers and on anything that is not a browser, and refusing those would\n * break server-to-server callers to catch an attacker who is already blocked by\n * the preflight.\n */\nexport function actionOriginAllowed(request: Request, url: URL): boolean {\n const origin = request.headers.get('origin')\n\n if (!origin) return true\n\n const expected = request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? url.host\n\n try {\n return new URL(origin).host === expected\n } catch {\n // An Origin that is not a url is not one this can vouch for.\n return false\n }\n}\n\nexport function createRscHandler(options: RscHostOptions): (request: Request) => Promise<Response | null> {\n const { engine, assets, version } = options\n // Annotated rather than inferred: the narrowing below is lost inside the\n // closures that use it, and every one of them runs after the throw.\n const manifest: RouteManifest | undefined = options.manifest ?? engine.manifest?.()\n\n if (!manifest) {\n throw new Error(\n 'No route table. Pass `manifest`, or build with a plugin version that embeds one in the bundle.',\n )\n }\n\n const routes: RouteManifest = manifest\n\n // Only when this host has functions of its own. Installing unconditionally\n // overwrites whatever was already registered — a prerenderer sharing the\n // same engine instance, or a host that set its own up first — and the\n // symptom is every call failing as unregistered.\n if (options.rpc || options.hostCalls) installHostFunctions(options.rpc ?? {}, options.hostCalls)\n\n function installHostFunctions(\n fns: NonNullable<RscHostOptions['rpc']>,\n remote: RscHostOptions['hostCalls'],\n ): void {\n engine.installHostFn(async (name: string, ...args: unknown[]) => {\n const fn = fns[name]\n\n if (fn) return await fn(...args)\n\n // A remote transport cannot enumerate what the backend registered, so\n // an unknown name is the backend's to reject — with a message naming the\n // function, which is more than this side could say.\n if (remote) return await remote(name, ...args)\n\n // Louder than returning null: a typo in a server component otherwise\n // renders as missing data with nothing anywhere saying why.\n throw new Error(\n `No host function named ${JSON.stringify(name)}. Registered: ${Object.keys(fns).join(', ') || '(none)'}`,\n )\n })\n }\n\n async function propsFor(match: MatchedRoute, request: Request): Promise<Record<string, unknown>> {\n return options.props ? await options.props(match, request) : match.params\n }\n\n /** The page a server action was invoked from, so it can re-render regions of it. */\n function pageContext(match: MatchedRoute, props: Record<string, unknown>) {\n return {\n component: match.route.component,\n props,\n layouts: match.route.layouts.map((component) => ({ component, props: {} })),\n loadings: match.route.loadings,\n parallelSlots: match.route.slots,\n // What may be named in X-RSC-Revalidate — see renderRevalidated.\n sections: match.route.sections,\n }\n }\n\n function withVersion(headers: Record<string, string>): Record<string, string> {\n return version ? { ...headers, [HEADER.version]: version } : headers\n }\n\n // A build made for export ships a client that asks for payloads by url,\n // because a static host cannot read a header. Serving that build from a\n // server is a reasonable thing to do — previewing an export, or one build\n // used both ways — and without this every navigation 404s in the console\n // while the page itself looks fine.\n const payloadName = manifest.build?.payloadName || ''\n\n /**\n * The page a payload url belongs to, if this is one.\n *\n * Both the whole-document name and the depth variants beside it: a client\n * built for export asks for index.seg1.rsc when it already holds a layout,\n * and matching only the plain name leaves that as a 404 no page reports.\n */\n const payloadNames = new RegExp(\n '/' + payloadName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/^index\\\\\\./, 'index(\\\\.seg\\\\d+)?\\\\.') + '$',\n )\n\n function pageForPayload(pathname: string): string | null {\n if (payloadName === '') return null\n\n const match = payloadNames.exec(pathname)\n\n if (!match) return null\n\n return pathname.slice(0, match.index) || '/'\n }\n\n // One memo table per request, opened at the outermost point so that\n // everything below shares it: middleware, layouts, the page, and an action. A\n // guard that reads the session and a layout that reads it again are one\n // query, not two.\n return async function handle(request: Request): Promise<Response | null> {\n return await withRequest(request, () =>\n withCache(() =>\n // Open for the whole request and sealed the moment an answer exists,\n // so middleware — which runs before any rendering — can put headers on\n // it, and a component, which runs after, is told why it cannot.\n withResponseDraft(async ({ taken, seal }) => {\n const response = await route(request)\n\n seal()\n\n if (!response) return null\n\n const collected = taken()\n\n collected.forEach((value, name) => {\n // Set-Cookie is applied below, once per cookie: iterating a Headers\n // gives it joined in some runtimes and per-cookie in others, and a\n // joined one is a single malformed cookie the browser discards.\n if (name.toLowerCase() === 'set-cookie') return\n\n // set, not append: a middleware asking for a header means that\n // value, not that value added to whatever the host already chose.\n response.headers.set(name, value)\n })\n\n // Appended, because several cookies are several headers.\n for (const cookie of collected.getSetCookie()) {\n response.headers.append('Set-Cookie', cookie)\n }\n\n return response\n }),\n ),\n )\n }\n\n async function route(request: Request): Promise<Response | null> {\n let url = new URL(request.url)\n const asPayload = pageForPayload(url.pathname)\n\n if (asPayload !== null) {\n // Rewritten to the page it is asking about, with the header the rest of\n // this handler reads — one path through, however the client asked.\n url = new URL(asPayload + url.search, url.origin)\n const headers = new Headers(request.headers)\n\n headers.set(HEADER.rsc, '1')\n request = new Request(url, { method: request.method, headers })\n }\n\n if (assets) {\n const asset = await assets(url.pathname, request)\n\n if (asset) return asset\n }\n\n if (request.method === 'POST' && url.pathname === HEADER.actionPath) {\n if (!actionOriginAllowed(request, url)) {\n return new Response('Cross-origin action', { status: 403 })\n }\n\n return await handleAction(request, url)\n }\n\n // The two halves an edge cache needs: hand it a shell it may keep, and\n // finish that shell for a visitor it cannot answer for itself.\n if (options.prerendered && url.pathname === HEADER.pprShellPath) {\n return await servePprShell(request, url, options.prerendered)\n }\n\n if (\n request.method === 'POST' &&\n options.prerendered &&\n url.pathname === HEADER.pprResumePath\n ) {\n return await servePprResume(request, url, options.prerendered)\n }\n\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n // One named region of this page, asked for without mutating anything to\n // earn it. What an action invalidated does not come through here — that\n // travels back inside the action's own answer, which is the whole point of\n // marking rather than telling the client to go and ask.\n const revalidating = request.headers.get(HEADER.revalidate)\n\n if (revalidating !== null && request.headers.get(HEADER.rsc) !== null) {\n return await handleRevalidate(request, url, revalidating)\n }\n\n // An intercepted navigation renders the page you are already on, with the\n // interceptor dropped into one of its slots — so the modal opens over it\n // and the url changes. Only ever on a client navigation: a hard load has\n // no referer to open over and gets the real page.\n const interceptSlot = request.headers.get(HEADER.intercept)\n\n if (interceptSlot !== null && request.headers.get(HEADER.rsc) !== null) {\n return await handleIntercept(request, url, interceptSlot)\n }\n\n // Only now. A frozen page is a whole page, and both requests above ask for\n // something smaller than one: answering a named region with the whole\n // document puts the entire page inside that region, and answering an\n // interception with it replaces the page the modal was opening over.\n const match = matchRoute(routes, url.pathname)\n\n if (options.prerendered) {\n // A guarded route can still be frozen: whether the content is the same\n // for everyone, and whether this caller may see it, are different\n // questions. The build answers the first; this answers the second, and\n // only then is the frozen page handed over.\n const refusal = await refuseUnlessAllowed(request, match)\n\n if (refusal) return refusal\n\n const frozen = await servePrerendered(request, url, options.prerendered)\n\n if (frozen) return frozen\n }\n\n if (!match) return null\n\n const props = await propsFor(match, request)\n const layouts = match.route.layouts.map((component) => ({ component, props: {} }))\n const chain = match.route.layouts\n\n // A payload request says so with a header on the page's own url, so one\n // route serves both the document and the navigation that follows it.\n if (request.headers.get(HEADER.rsc) === null) {\n // Scoped to this render, so two requests redirecting at once cannot read\n // each other's destination.\n return await withRedirect(async (taken) => {\n // Awaited, and that await is the whole design: React resolves this\n // when the SHELL is ready, so a redirect thrown above every Suspense\n // boundary rejects here — before a byte is written, with a status line\n // still available. Nothing is buffered to make that true.\n let htmlStream: ReadableStream\n\n try {\n ;({ htmlStream } = await engine.handleRscHtmlStream(\n match.route.component,\n props,\n layouts,\n match.route.loadings,\n match.route.slots,\n {},\n undefined,\n url.pathname,\n // A route that ships no runtime gets no bootstrap and no segment\n // boundary — the boundary is itself a client component, so leaving\n // it in means no page could ever be JS-free.\n match.route.clientJs !== false,\n ))\n } catch (error) {\n // A rejected shell is how a redirect above every boundary arrives:\n // React could not finish the shell, because the component that would\n // have produced it left instead.\n //\n // The scope decides, not the error. React catches what a component\n // threw and re-raises its own — whose message is stripped in\n // production — so testing the caught value for a redirect signal\n // fails exactly where it matters, and the answer is a 500 with the\n // destination sitting in a scope nobody read.\n const refused = taken()\n\n if (refused) return redirectResponse(refused, false)\n\n\n // A guard refusing is not a failed render. Without this a visitor\n // who may not see the page gets a 500, which reads as the\n // application being broken rather than them being turned away —\n // and a host middleware refusal arrives exactly here, because the\n // engine asks before it renders anything.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n throw error\n }\n\n const early = taken()\n\n if (early) return redirectResponse(early, false)\n\n return new Response(appendLateRedirect(htmlStream, taken), {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': match.route.middleware?.length ? PER_CLIENT : REVALIDATE,\n }),\n })\n })\n }\n\n const from = sharedDepth(request.headers.get(HEADER.segments), chain)\n\n // Proposed by the host, decided by the engine: an interceptor can force a\n // wider render than the client asked for, so what goes back is the depth\n // that came out, never the one that went in.\n return await withRedirect(async (taken) => {\n let stream: ReadableStream\n let segmentDepth: number\n\n try {\n ;({ stream, segmentDepth } = await engine.handleRscStream(\n match.route.component,\n props,\n layouts,\n match.route.loadings,\n match.route.slots,\n {},\n from,\n url.pathname,\n ))\n } catch (error) {\n // Same reasoning as the document path: what the render recorded is\n // reliable, what React re-raised is not.\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n\n // A payload request is guarded exactly as the document is. Narrowing\n // a request must never narrow what is checked.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n throw error\n }\n\n const early = taken()\n\n // 204 and a header. A payload request that redirected later than this\n // carries the destination in the error digest instead, and the client's\n // RedirectBoundary performs it.\n if (early) return redirectResponse(early, true)\n\n return new Response(stream, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(segmentDepth),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n })\n }\n\n /**\n * A page rendered at build time, if there is one for this url.\n *\n * The payload has to match the depth the client shares, not simply exist.\n * Serving the whole document to a client that already holds the layouts\n * replaces the root — and replacing the root unmounts everything retained\n * behind it, so going back stops restoring what you had.\n */\n /**\n * The shell an edge cache may hold, for a route named by `?url=`.\n *\n * Only ever a build artifact, so there is nothing here that belongs to\n * whoever asked. What it deliberately does NOT return is the postponed\n * state. Next's protocol hands that to the CDN and takes it back on the\n * resume, which makes the resume endpoint parse a blob an attacker can write\n * — the shape of a known denial-of-service against it. Our origin has the\n * file already, so the state never needs to leave.\n *\n * A guarded route is refused outright rather than guarded here. Its shell is\n * not cacheable by a shared cache at all, so handing one to an edge that\n * exists to cache things is an invitation to a mistake nobody would see.\n */\n async function servePprShell(\n request: Request,\n url: URL,\n read: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n const target = url.searchParams.get('url')\n\n if (!target || !target.startsWith('/')) {\n return new Response('A url is required', { status: 400 })\n }\n\n // Matched from the url asked for, never from anything else the caller sent.\n const route = matchRoute(routes, new URL(target, url.origin).pathname)\n\n if (!route) return new Response('No such page', { status: 404 })\n\n if (route.route.middleware?.length) {\n return new Response('This route is not edge-cacheable', { status: 404 })\n }\n\n const key = pathKey(new URL(target, url.origin).pathname)\n const shell = (await read(`${key}.ppr.html`)) ?? (await read(`${patternKey(route.route)}.ppr.html`))\n\n if (shell === null) return new Response('No shell for this page', { status: 404 })\n\n return new Response(JSON.stringify({ shell, version: version ?? null }), {\n headers: withVersion({\n 'Content-Type': 'application/json',\n // Deliberately NOT the REVALIDATE the rest of the host sends. That is\n // `max-age=0, must-revalidate`, which a cache honours by treating the\n // entry as stale the moment it arrives — an edge would store this and\n // never once serve it, so the whole thing would quietly do nothing\n // while looking like it worked, because the miss path serves correct\n // pages.\n //\n // This is build output with nothing of the caller in it, and a guarded\n // route never reaches here at all, so it is genuinely cacheable. An\n // hour bounds how long a deploy can be served against a stale shell;\n // the version below catches it sooner than that.\n 'Cache-Control': 'public, max-age=3600',\n }),\n })\n }\n\n /**\n * Finish a shell for the visitor this request belongs to.\n *\n * The whole security question lives here, because the holes are the part a\n * guard exists to protect — the shell is chrome, and everything private is\n * behind the boundaries this fills in. So it runs exactly the guard chain the\n * page itself would, derived from the url and nothing else, against the\n * cookies and headers the caller actually sent.\n *\n * Which means an edge worker must forward the visitor's request, not make one\n * of its own. A resume asked for with no cookies is an anonymous visitor and\n * gets an anonymous answer.\n */\n async function servePprResume(\n request: Request,\n url: URL,\n read: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n const target = url.searchParams.get('url')\n\n if (!target || !target.startsWith('/')) {\n return new Response('A url is required', { status: 400 })\n }\n\n const pathname = new URL(target, url.origin).pathname\n const route = matchRoute(routes, pathname)\n\n if (!route) return new Response('No such page', { status: 404 })\n\n // The same refusal the document would get, before a byte of the holes is\n // rendered. Nothing below runs for a caller this turns away.\n const refusal = await refuseUnlessAllowed(request, route)\n\n if (refusal) return refusal\n\n if (!engine.handleRscResume) {\n return new Response('This engine cannot resume', { status: 500 })\n }\n\n const key = pathKey(pathname)\n const pattern = patternKey(route.route)\n\n let shellKey: string | null = null\n\n if ((await read(`${key}.ppr.html`)) !== null) shellKey = key\n else if ((await read(`${pattern}.ppr.html`)) !== null) shellKey = pattern\n\n // Read from our own artifacts. Never from the request body — that is the\n // difference between this and the protocol it is modelled on.\n const state = shellKey === null ? null : await read(`${shellKey}.postponed.json`)\n\n if (state === null) return new Response('Nothing to resume', { status: 404 })\n\n const { htmlStream } = await engine.handleRscResume(\n route.route.component,\n route.params,\n route.route.layouts.map((component) => ({ component, props: {} })),\n route.route.loadings,\n route.route.slots,\n {},\n JSON.parse(state),\n undefined,\n shellKey === key ? pathname : '',\n )\n\n // Carries the build version so a caller holding a cached shell can tell\n // that it no longer belongs to this origin. A shell from an older build\n // does not make the resume fail — it replays against slots that have moved\n // and React falls back to client rendering, silently and for good. Nothing\n // else would ever report it.\n return new Response(htmlStream, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n // Rendered for whoever asked. Never cacheable.\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n async function servePrerendered(\n request: Request,\n url: URL,\n source: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n const key = pathKey(url.pathname)\n const read = async (name: string) => await source(name)\n\n // Before anything else: a route that only redirects was frozen as the\n // redirect itself, so there is no page under this url and never will be.\n const frozenRedirect = await read(`${key}.redirect.json`)\n\n if (frozenRedirect !== null) {\n const to = JSON.parse(frozenRedirect) as { status: number; location: string }\n\n return redirectResponse(to, request.headers.get(HEADER.rsc) !== null)\n }\n\n if (request.headers.get(HEADER.rsc) === null) {\n // A frozen page first; then a shell, under this url or under the route's\n // pattern. Nothing in a shell varies by param, so one shell serves every\n // url its route matches — which is the only way a route whose urls were\n // never listed gets anything frozen at all.\n const route = matchRoute(routes, url.pathname)\n const whole = await read(`${key}.html`)\n\n // A whole page is finished. Nothing to resume, nothing to render.\n if (whole !== null) {\n return new Response(whole, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n Vary: VARY_ON_RSC,\n 'Cache-Control': route?.route.middleware?.length ? PER_CLIENT : REVALIDATE,\n }),\n })\n }\n\n // Then a shell, under this url or under the route's pattern. Which of the\n // two answered is tracked, because the state that resumes it sits beside\n // the file that was found rather than beside the url that was asked for.\n let shellKey: string | null = null\n let shell = await read(`${key}.ppr.html`)\n\n if (shell !== null) {\n shellKey = key\n } else if (route) {\n const pattern = patternKey(route.route)\n\n shell = await read(`${pattern}.ppr.html`)\n\n if (shell !== null) shellKey = pattern\n }\n\n if (shell === null || shellKey === null) return null\n\n const state = await read(`${shellKey}.postponed.json`)\n\n // A shell with no state cannot be finished by anyone. It was frozen with\n // its fallbacks showing and there is no record of what came next, so\n // serving it would be serving a page that stays on its loading state for\n // good. Fall through and render the page now instead.\n if (state === null || !engine.handleRscResume || !route) return null\n\n const { htmlStream } = await engine.handleRscResume(\n route.route.component,\n route.params,\n // Empty props, because that is what the build passed. Resuming replays\n // the tree against the slots the shell left, and React matches those by\n // key — so an argument that differs from the frozen render at all is a\n // tree that \"doesn't match\", and every boundary falls back to the\n // client instead of being filled here.\n route.route.layouts.map((component) => ({ component, props: {} })),\n route.route.loadings,\n route.route.slots,\n {},\n JSON.parse(state),\n undefined,\n // A shell found under the route's pattern was frozen for no particular\n // url, so it was rendered with no page key. Handing one over now would\n // key the tree differently from the one being resumed.\n shellKey === key ? url.pathname : '',\n )\n\n // The shell first, then whatever the resume writes. React's own script\n // travels with the resumed segments and moves them into place, so this is\n // a plain concatenation and the holes land without hydration.\n const body = new ReadableStream({\n async start(controller) {\n controller.enqueue(new TextEncoder().encode(shell))\n\n const reader = htmlStream.getReader()\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n\n if (done) break\n\n controller.enqueue(value)\n }\n } finally {\n controller.close()\n }\n },\n })\n\n return new Response(body, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n Vary: VARY_ON_RSC,\n // The shell is cacheable; this response is not. It carries the holes,\n // which were rendered for whoever asked.\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n // Only the document is ever served frozen for a shell. The payload is what\n // fills it in, and it has to be rendered now — answering with a frozen one\n // would hand back the same fallbacks the shell already shows, and the page\n // would never finish loading.\n\n const meta = await read(`${key}.meta.json`)\n\n // Both or neither: without the chain there is no way to know which depth a\n // payload is for, and guessing means handing the client a segment for a\n // boundary it does not have.\n if (meta === null) return null\n\n const chain = (JSON.parse(meta).layouts ?? []) as string[]\n const shared = sharedDepth(request.headers.get(HEADER.segments), chain)\n\n // The variant for exactly this depth, or the whole document. Anything else\n // would be a payload for a boundary the client is not holding.\n const variant = shared > 0 ? await read(`${key}.seg${shared}.flight`) : null\n const payload = variant ?? (await read(`${key}.flight`))\n\n if (payload === null) return null\n\n return new Response(payload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(variant ? shared : 0),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n /**\n * The middleware of a route, or null to go ahead.\n *\n * Used wherever a render can be reached without the engine running the chain\n * itself: a page served from disk, and an interception, which renders a\n * component the route table did not choose.\n *\n * Asked before anything is read or rendered — the answer to a refusal must\n * not be a page that has already been fetched.\n */\n async function refuseUnlessAllowed(\n request: Request,\n match: MatchedRoute | null,\n ): Promise<Response | null> {\n // hostMiddleware as well as the engine's own. A page served from disk\n // never touches the engine, so a route guarded only by the host would be\n // handed over without anyone being asked — the guard would hold right up\n // until the build froze the page, then silently stop.\n if (!match) return null\n\n const guarded =\n (match.route.middleware?.length ?? 0) > 0 || (match.route.hostMiddleware?.length ?? 0) > 0\n\n if (!guarded) return null\n\n // A route that declares middleware and an engine that cannot run it is not\n // \"no middleware\" — it is a check that silently does not happen. Refusing\n // is the only safe reading, and it names the cause rather than serving the\n // guarded page. Reachable when a host runs a bundle built by an older\n // plugin, where the export did not exist.\n if (!engine.runRouteMiddleware) {\n return new Response(\n 'This route declares middleware, and the engine cannot run it. ' +\n 'Rebuild the app against the current @rsc-kit/core.',\n { status: 500 },\n )\n }\n\n const asPayload = request.headers.get(HEADER.rsc) !== null\n\n return await withRedirect(async (taken) => {\n try {\n await engine.runRouteMiddleware!(match.route.component, await propsFor(match, request))\n } catch (error) {\n const refused = taken()\n\n if (refused) return redirectResponse(refused, asPayload)\n\n // A visitor who may not see this page has not caused a server\n // error. Answering 500 makes a guarded route indistinguishable from\n // a broken one, in the logs and to the person looking at it.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n\n throw error\n }\n\n const refused = taken()\n\n return refused ? redirectResponse(refused, asPayload) : null\n })\n }\n\n async function handleRevalidate(request: Request, url: URL, target: string): Promise<Response> {\n if (!engine.handleRscRevalidate) {\n return new Response('This build cannot revalidate', { status: 501 })\n }\n\n const match = matchRoute(routes, url.pathname)\n\n if (!match) return new Response('No such page', { status: 404 })\n\n // Scoped like the render paths: a guard above the target may refuse, and\n // that refusal is an answer rather than a failure.\n return await withRedirect(async (taken) => {\n let rscPayload: string\n\n try {\n ;({ rscPayload } = await engine.handleRscRevalidate!(\n target,\n pageContext(match, await propsFor(match, request)),\n ))\n } catch (error) {\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n throw error\n }\n\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n return new Response(rscPayload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n // Echoed so the client can tell which region it is holding.\n [HEADER.revalidate]: target,\n Vary: VARY_ON_RSC,\n 'Cache-Control': 'private, no-store',\n }),\n })\n })\n }\n\n async function handleIntercept(request: Request, url: URL, slot: string): Promise<Response> {\n const intercept = matchIntercept(routes, url.pathname, slot)\n\n if (!intercept) return new Response('No interceptor for this url', { status: 404 })\n\n // The guards of the route being intercepted, before anything is rendered.\n //\n // An interceptor exists to show the same resource as the route it stands in\n // for — a modal over /orders/[id] shows that order. So it has to be behind\n // the same checks, and nothing else in this path runs them: the engine is\n // handed the interceptor component, which the route table did not choose\n // and whose middleware chain is keyed off manifest().routes, where an\n // interceptor does not appear.\n //\n // Derived from the url, never from X-RSC-Referer. The referer is a header\n // the caller writes, and guarding by it means the caller picks the guard.\n const intercepted = matchRoute(routes, url.pathname)\n\n // Nothing to guard means nothing to serve. A url that matches an\n // interceptor but no route has no middleware chain to consult, so there is\n // no way to know whether this caller may see it — and an interceptor\n // stands in for a route, so a url with no route behind it is not a page\n // anyone was entitled to open a modal over.\n if (!intercepted) return new Response('No such page', { status: 404 })\n\n const refusal = await refuseUnlessAllowed(request, intercepted)\n\n if (refusal) return refusal\n\n const referer = request.headers.get(HEADER.referer)\n const under = referer ? matchRoute(routes, new URL(referer, url.origin).pathname) : null\n\n // Without a page to open over there is nothing to intercept: render the\n // interceptor on its own rather than answering with the wrong page.\n const component = under ? under.route.component : intercept.component\n const props = under ? await propsFor(under, request) : intercept.params\n const chain = under ? under.route.layouts : []\n const slots = under ? under.route.slots : {}\n const loadings = under ? under.route.loadings : []\n\n // The interceptor alone, when there is a page to open it over and this\n // build can render a region on its own.\n //\n // Re-rendering the page underneath would put the modal on screen at the\n // cost of rebuilding everything below the layout that declares the slot —\n // so opening a modal from a half-filled form throws the form away. The\n // page beneath is already mounted and correct; only the slot is new.\n if (under && engine.handleRscRevalidate) {\n const { rscPayload } = await engine.handleRscRevalidate(slot, {\n component: under.route.component,\n // The target's params, not the page's: a modal for /posts/hello opened\n // from /feed is about hello.\n props: intercept.params,\n layouts: [],\n loadings: [],\n // Named as the slot so the renderer finds it there, but pointing at\n // the interceptor rather than the default this route would otherwise\n // fill it with.\n parallelSlots: { [slot]: intercept.component },\n })\n\n return new Response(rscPayload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n // Says what this payload is, so the client puts it in the slot\n // instead of treating it as a segment of the page.\n [HEADER.revalidate]: slot,\n Vary: VARY_ON_RSC,\n // Per-client by construction: which region this is was chosen by a\n // request header, so a shared cache has nothing useful to key on.\n 'Cache-Control': 'private, no-store',\n }),\n })\n }\n\n const { stream, segmentDepth } = await engine.handleRscStream(\n component,\n props,\n chain.map((layout) => ({ component: layout, props: {} })),\n loadings,\n slots,\n {},\n sharedDepth(request.headers.get(HEADER.segments), chain),\n retentionKey(url.pathname, slot),\n )\n\n return new Response(stream, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(segmentDepth),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n async function handleAction(request: Request, url: URL): Promise<Response> {\n const actionId = request.headers.get(HEADER.action)\n\n if (!actionId) return new Response('Missing X-RSC-Action', { status: 400 })\n\n // The body travels as application/octet-stream so a host that parses\n // multipart cannot consume it first; its real type rides in a header.\n const body = new Uint8Array(await request.arrayBuffer())\n const contentType = request.headers.get(HEADER.contentType) ?? 'text/plain;charset=UTF-8'\n\n // Where it was invoked from, so anything the action invalidates can be\n // re-rendered against the page that is actually on screen.\n const referer = request.headers.get(HEADER.referer)\n const match = referer ? matchRoute(routes, new URL(referer, url.origin).pathname) : null\n const page = match ? pageContext(match, await propsFor(match, request)) : undefined\n\n // Scoped to this action: revalidate() called anywhere inside it, at any\n // depth, marks here and nowhere else — two requests can be in flight and\n // marking is per-request state.\n const { stream } = await withRevalidation((taken) =>\n engine.handleAction(actionId, body, contentType, page, taken),\n )\n\n return new Response(stream, {\n headers: withVersion({ 'Content-Type': 'text/x-component; charset=utf-8' }),\n })\n }\n}\n"]}
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,mDAAmD;AACnD,EAAE;AACF,2EAA2E;AAC3E,wEAAwE;AACxE,6EAA6E;AAC7E,2BAA2B;AAC3B,EAAE;AACF,+DAA+D;AAC/D,gGAAgG;AAEhG,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,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AAM,gBAAgB,CAAC,CAAC,KAAK,EAAE,EAAE,CAClD,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,CAAC,CAC9D,CAAA;QAED,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE;YAC1B,OAAO,EAAE,WAAW,CAAC,EAAE,cAAc,EAAE,iCAAiC,EAAE,CAAC;SAC5E,CAAC,CAAA;IACJ,CAAC;AACH,CAAC","sourcesContent":["// Everything a JavaScript host has to do to serve the RSC engine.\n//\n// PHP needs ~2,400 lines for this because it cannot run JavaScript: a socket\n// bridge, a worker pool, a frame protocol. A JS host imports the engine and\n// calls it, and what remains is the part every host would otherwise rewrite —\n// matching a url to a route, negotiating how much of the page to send, and\n// speaking the header protocol the client expects.\n//\n// Deliberately not Hono, or Express, or anything: this takes a Request and\n// returns a Response, so it runs under Bun.serve, Deno, Workers, Node's\n// fetch adapters and any framework built on them. `./hono` is the three-line\n// binding for one of them.\n//\n// const rsc = createRscHandler({ engine, manifest, assets })\n// Bun.serve({ fetch: (req) => rsc(req).then((r) => r ?? new Response('', { status: 404 })) })\n\nimport { matchIntercept, matchRoute, retentionKey, sharedDepth } from './routing.js'\nimport { pathKey, patternKey } from './prerender.js'\nimport { withRevalidation } from './revalidate.js'\nexport { revalidate } from './revalidate.js'\nimport { withRedirect } from './redirect.js'\nimport { withCache } from './cache.js'\nimport { withRequest, withResponseDraft } from './request.js'\nimport type { Redirection } from './redirect.js'\nexport { redirect } from './redirect.js'\n// Re-exported, not redefined: routing.ts is the one implementation, shared with\n// the prerenderer and the generated bundle, and this stays the adapter's\n// public surface so a host imports from one place.\nexport { matchIntercept, matchRoute, sharedDepth } from './routing.js'\nexport type { MatchedRoute } from './routing.js'\nimport { FLIGHT_TYPE, HEADER, HTML_TYPE, PER_CLIENT, REVALIDATE, VARY_ON_RSC } from './headers.js'\nimport type { MatchedRoute } from './routing.js'\nimport { ServerAuthenticationError, ServerAuthorizationError } from './js/errors.js'\nimport type { RouteManifest } from './manifest.js'\n\n/** The built server bundle. Only the parts a host calls. */\nexport interface RscEngine {\n /** The route table this bundle was built from. */\n manifest?(): RouteManifest\n installHostFn(fn: (name: string, ...args: unknown[]) => unknown): void\n handleRscStream(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n from?: number,\n pageKey?: string,\n ): Promise<{ stream: ReadableStream; segmentDepth: number }>\n handleRscHtmlStream(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n nonce?: string,\n pageKey?: string,\n bootstrap?: boolean,\n ): Promise<{ htmlStream: ReadableStream }>\n /**\n * Finish a shell frozen at build time, against data that exists now.\n *\n * Emits only the boundaries the shell left unfinished, meant to be written\n * straight after it. Optional so a host can be pointed at an engine built\n * before resuming existed; without it a shell has no way to be completed and\n * the page is rendered whole instead.\n */\n handleRscResume?(\n component: string,\n props?: Record<string, unknown>,\n layouts?: { component: string; props: Record<string, unknown> }[],\n loadings?: string[],\n parallelSlots?: Record<string, string>,\n slotOverrides?: Record<string, unknown>,\n postponed?: unknown,\n nonce?: string,\n pageKey?: string,\n ): Promise<{ htmlStream: ReadableStream }>\n handleRscRevalidate?(target: string, page: unknown): Promise<{ rscPayload: string }>\n /**\n * Run a route's middleware without rendering anything.\n *\n * For a frozen page: the host reads it from disk and the engine never sees\n * the request, so the check has to be asked for separately.\n */\n runRouteMiddleware?(component: string, props: Record<string, unknown>): Promise<void>\n handleAction(\n actionId: string,\n body: Uint8Array | string | FormData,\n contentType?: string,\n page?: unknown,\n takeRevalidated?: () => string[],\n ): Promise<{ stream: ReadableStream }>\n /**\n * Answer one read declared with `query()`, or null if that id is not one.\n *\n * Optional so a host can be pointed at a bundle built before queries existed;\n * without it the endpoint 404s rather than throwing, which is what a client\n * built against the same old bundle expects anyway.\n */\n handleQuery?(\n id: string,\n args: string,\n report?: (error: unknown) => string,\n ): Promise<{ stream: ReadableStream; cacheControl: string } | null>\n}\n\nexport interface RscHostOptions {\n /** The built server bundle — `import * as engine from './build/rsc/index.js'`. */\n engine: RscEngine\n /**\n * The route table. Defaults to the one the bundle was built with, which is\n * almost always what you want — a manifest passed separately can go stale\n * against the bundle it is describing.\n */\n manifest?: RouteManifest\n /**\n * Functions the app's server components call as `await rpc('name', ...args)`.\n *\n * In the Laravel host this crosses a socket into PHP. Here they are just\n * functions, which is the whole reason a JS host is smaller.\n */\n rpc?: Record<string, (...args: unknown[]) => unknown>\n /**\n * Where a host call goes when this process cannot answer it.\n *\n * `rpc` is checked first, so a host can answer some calls in JS and leave\n * the rest to a backend. `httpHostCalls` in `@rsc-kit/core/host-calls`\n * builds one of these over an ordinary POST, which is how a host written in\n * another language answers without implementing the socket framing.\n */\n hostCalls?: (name: string, ...args: unknown[]) => Promise<unknown>\n /**\n * Props for a page, given whatever its url bound.\n *\n * Defaults to the url params alone. A host that loads a user, reads a\n * session or resolves a tenant does it here — this is the one place the\n * engine cannot supply anything for.\n */\n props?: (match: MatchedRoute, request: Request) => Record<string, unknown> | Promise<Record<string, unknown>>\n /**\n * Reads what the prerenderer wrote, if this build has any.\n *\n * A function rather than a directory, because not every host has a\n * filesystem: on an edge runtime these live in a KV store or a static-asset\n * binding. `prerenderedFrom` in `@rsc-kit/core/files` is the one for a disk.\n *\n * Checked before rendering, and anything it cannot find falls through to\n * being rendered now — so a partial prerender is a valid state, not a\n * broken one.\n */\n prerendered?: (name: string) => Promise<string | null> | string | null\n /** Serve a built browser asset. Return null for anything not found. */\n assets?: (pathname: string, request: Request) => Promise<Response | null> | Response | null\n /**\n * Identifies this build to the client, which compares it on every\n * navigation and falls back to a full load when it changes. Without one a\n * client keeps talking to a deployment that no longer exists — worst behind\n * a CDN, where the shell it holds may already be from an older build.\n */\n version?: string\n}\n\n/**\n * The answer to a redirect that was decided before anything was written.\n *\n * A document gets a real status code. A payload request must NOT: `fetch`\n * follows a 3xx transparently, so the client would receive the destination's\n * HTML and hand it to the Flight decoder, which reports its own confusion\n * rather than the redirect. It gets 204 and a header instead, and navigates\n * itself — which is also what makes the redirect an SPA one.\n */\n/**\n * A string safe to write inside a <script> element.\n *\n * `JSON.stringify` escapes for JavaScript, and this is not a JavaScript\n * context — it is HTML that happens to contain JavaScript. The parser ends the\n * element at the first `</script`, wherever it appears, so a destination\n * carrying one closes the tag and whatever follows is markup the browser runs.\n *\n * That destination is routinely computed rather than written — redirect()\n * documents \"remembering where someone was going and sending them back to it\"\n * as the usual case, which is a query string or a cookie arriving verbatim\n * here. U+2028 and U+2029 are escaped too: legal in JSON, line terminators in\n * JavaScript.\n */\nfunction inScript(value: string): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\nfunction redirectResponse(to: Redirection, isPayloadRequest: boolean): Response {\n if (isPayloadRequest) {\n return new Response(null, {\n status: 204,\n headers: { [HEADER.redirect]: to.location, Vary: VARY_ON_RSC },\n })\n }\n\n return new Response(null, {\n status: to.status,\n headers: { Location: to.location, Vary: VARY_ON_RSC },\n })\n}\n\n/**\n * Append the redirect a render asked for after its shell had already gone out.\n *\n * The status line is spent by then, so the instruction travels in the body. A\n * script rather than waiting for hydration to notice the error digest: it runs\n * as the browser parses it, which is sooner, and it is the only path that\n * works at all for a route shipping no client runtime.\n *\n * Read on flush, because that is when the render has finished and a redirect\n * from inside a Suspense boundary is finally known.\n */\nfunction appendLateRedirect(\n stream: ReadableStream,\n taken: () => Redirection | null,\n): ReadableStream {\n // An engine that answered with a finished body rather than a stream has no\n // late window at all: the render was over before this was called, so the\n // caller's own check already saw everything there was to see.\n if (typeof stream?.getReader !== 'function') return stream\n\n const encoder = new TextEncoder()\n const reader = stream.getReader()\n\n // Read-and-re-emit rather than pipeThrough(new TransformStream(...)): a\n // TransformStream from a different realm than the stream it is piped into\n // is rejected outright, and a host embedded in a runtime that supplies its\n // own web streams is exactly that case.\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read()\n\n if (!done) {\n controller.enqueue(value)\n\n return\n }\n\n const to = taken()\n\n // replace, so Back does not return to a url that redirected.\n if (to) {\n controller.enqueue(encoder.encode(`<script>location.replace(${inScript(to.location)})</script>`))\n }\n\n controller.close()\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n}\n\n/**\n * The status a refusal deserves, or null when this was not one.\n *\n * A host answers an unauthenticated call 401 and an unauthorized one 403, and\n * the transport raises each as its own error. Without this they arrive at the\n * render as ordinary failures and leave as 500s — which reads, to anyone\n * looking at a log or a browser, as the application being broken rather than\n * the visitor being turned away.\n */\nfunction refusalStatus(error: unknown): number | null {\n if (error instanceof ServerAuthenticationError) return 401\n if (error instanceof ServerAuthorizationError) return 403\n\n // Named rather than matched by identity, because the error may have been\n // raised by another copy of the module: an app's actions are bundled apart\n // from the engine, and instanceof is false across that seam.\n const name = (error as { name?: string } | null)?.name\n\n if (name === 'ServerAuthenticationError') return 401\n if (name === 'ServerAuthorizationError') return 403\n\n // A status the host chose — a throttle's 429, a policy's 403 — carried on\n // the error by the transport. Bounded to refusals: a host answering 500\n // should not be able to make this look like a client's fault, and one\n // answering 200 should not turn a failed render into a success.\n const carried = (error as { refusalStatus?: unknown } | null)?.refusalStatus\n\n if (typeof carried === 'number' && carried >= 400 && carried <= 499) return carried\n\n return null\n}\n\nfunction refusalMessage(error: unknown): string {\n const message = (error as { message?: string } | null)?.message\n\n return typeof message === 'string' && message !== '' ? message : 'Refused.'\n}\n\n/**\n * Whether a browser was told it could post this action.\n *\n * Defence in depth, not the only defence. An action already requires the\n * X-RSC-Action header, which makes a cross-origin post a non-simple request —\n * so the browser must preflight it, and nothing here answers a preflight. A\n * browser can be tricked into sending cookies; it cannot be tricked into\n * sending a header it does not know. This is the belt to that pair of braces,\n * and it is what Next does for server actions.\n *\n * Compared against X-Forwarded-Host first, because a proxied deployment is the\n * normal one: the backend forwards the name the visitor typed, while Host is\n * this process on loopback. Comparing against Host alone would reject every\n * legitimate action that arrived through a proxy — a check that only fires on\n * correct requests is worse than none.\n *\n * No Origin at all is allowed through. It is absent on same-origin requests in\n * some browsers and on anything that is not a browser, and refusing those would\n * break server-to-server callers to catch an attacker who is already blocked by\n * the preflight.\n */\nexport function actionOriginAllowed(request: Request, url: URL): boolean {\n const origin = request.headers.get('origin')\n\n if (!origin) return true\n\n const expected = request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? url.host\n\n try {\n return new URL(origin).host === expected\n } catch {\n // An Origin that is not a url is not one this can vouch for.\n return false\n }\n}\n\n/**\n * How large a query url may be before it is refused.\n *\n * Matched to the client's own limit, and enforced here too because the limit is\n * what keeps an attacker from making this endpoint decode megabytes of\n * attacker-chosen payload per request.\n *\n * Module scope, not inside the handler: everything declared after the handler\n * is returned never initialises, and a `const` read from the closure then\n * throws on every request instead of being undefined.\n */\nconst MAX_QUERY = 8_000\n\nexport function createRscHandler(options: RscHostOptions): (request: Request) => Promise<Response | null> {\n const { engine, assets, version } = options\n // Annotated rather than inferred: the narrowing below is lost inside the\n // closures that use it, and every one of them runs after the throw.\n const manifest: RouteManifest | undefined = options.manifest ?? engine.manifest?.()\n\n if (!manifest) {\n throw new Error(\n 'No route table. Pass `manifest`, or build with a plugin version that embeds one in the bundle.',\n )\n }\n\n const routes: RouteManifest = manifest\n\n // Only when this host has functions of its own. Installing unconditionally\n // overwrites whatever was already registered — a prerenderer sharing the\n // same engine instance, or a host that set its own up first — and the\n // symptom is every call failing as unregistered.\n if (options.rpc || options.hostCalls) installHostFunctions(options.rpc ?? {}, options.hostCalls)\n\n function installHostFunctions(\n fns: NonNullable<RscHostOptions['rpc']>,\n remote: RscHostOptions['hostCalls'],\n ): void {\n engine.installHostFn(async (name: string, ...args: unknown[]) => {\n const fn = fns[name]\n\n if (fn) return await fn(...args)\n\n // A remote transport cannot enumerate what the backend registered, so\n // an unknown name is the backend's to reject — with a message naming the\n // function, which is more than this side could say.\n if (remote) return await remote(name, ...args)\n\n // Louder than returning null: a typo in a server component otherwise\n // renders as missing data with nothing anywhere saying why.\n throw new Error(\n `No host function named ${JSON.stringify(name)}. Registered: ${Object.keys(fns).join(', ') || '(none)'}`,\n )\n })\n }\n\n async function propsFor(match: MatchedRoute, request: Request): Promise<Record<string, unknown>> {\n return options.props ? await options.props(match, request) : match.params\n }\n\n /** The page a server action was invoked from, so it can re-render regions of it. */\n function pageContext(match: MatchedRoute, props: Record<string, unknown>) {\n return {\n component: match.route.component,\n props,\n layouts: match.route.layouts.map((component) => ({ component, props: {} })),\n loadings: match.route.loadings,\n parallelSlots: match.route.slots,\n // What may be named in X-RSC-Revalidate — see renderRevalidated.\n sections: match.route.sections,\n }\n }\n\n function withVersion(headers: Record<string, string>): Record<string, string> {\n return version ? { ...headers, [HEADER.version]: version } : headers\n }\n\n // A build made for export ships a client that asks for payloads by url,\n // because a static host cannot read a header. Serving that build from a\n // server is a reasonable thing to do — previewing an export, or one build\n // used both ways — and without this every navigation 404s in the console\n // while the page itself looks fine.\n const payloadName = manifest.build?.payloadName || ''\n\n /**\n * The page a payload url belongs to, if this is one.\n *\n * Both the whole-document name and the depth variants beside it: a client\n * built for export asks for index.seg1.rsc when it already holds a layout,\n * and matching only the plain name leaves that as a 404 no page reports.\n */\n const payloadNames = new RegExp(\n '/' + payloadName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/^index\\\\\\./, 'index(\\\\.seg\\\\d+)?\\\\.') + '$',\n )\n\n function pageForPayload(pathname: string): string | null {\n if (payloadName === '') return null\n\n const match = payloadNames.exec(pathname)\n\n if (!match) return null\n\n return pathname.slice(0, match.index) || '/'\n }\n\n // One memo table per request, opened at the outermost point so that\n // everything below shares it: middleware, layouts, the page, and an action. A\n // guard that reads the session and a layout that reads it again are one\n // query, not two.\n return async function handle(request: Request): Promise<Response | null> {\n return await withRequest(request, () =>\n withCache(() =>\n // Open for the whole request and sealed the moment an answer exists,\n // so middleware — which runs before any rendering — can put headers on\n // it, and a component, which runs after, is told why it cannot.\n withResponseDraft(async ({ taken, seal }) => {\n const response = await route(request)\n\n seal()\n\n if (!response) return null\n\n const collected = taken()\n\n collected.forEach((value, name) => {\n // Set-Cookie is applied below, once per cookie: iterating a Headers\n // gives it joined in some runtimes and per-cookie in others, and a\n // joined one is a single malformed cookie the browser discards.\n if (name.toLowerCase() === 'set-cookie') return\n\n // set, not append: a middleware asking for a header means that\n // value, not that value added to whatever the host already chose.\n response.headers.set(name, value)\n })\n\n // Appended, because several cookies are several headers.\n for (const cookie of collected.getSetCookie()) {\n response.headers.append('Set-Cookie', cookie)\n }\n\n return response\n }),\n ),\n )\n }\n\n async function route(request: Request): Promise<Response | null> {\n let url = new URL(request.url)\n const asPayload = pageForPayload(url.pathname)\n\n if (asPayload !== null) {\n // Rewritten to the page it is asking about, with the header the rest of\n // this handler reads — one path through, however the client asked.\n url = new URL(asPayload + url.search, url.origin)\n const headers = new Headers(request.headers)\n\n headers.set(HEADER.rsc, '1')\n request = new Request(url, { method: request.method, headers })\n }\n\n if (assets) {\n const asset = await assets(url.pathname, request)\n\n if (asset) return asset\n }\n\n if (request.method === 'POST' && url.pathname === HEADER.actionPath) {\n if (!actionOriginAllowed(request, url)) {\n return new Response('Cross-origin action', { status: 403 })\n }\n\n return await handleAction(request, url)\n }\n\n if (request.method === 'GET' && url.pathname === HEADER.queryPath) {\n // Same check as an action, for a smaller reason: a cross-origin page\n // cannot read this answer — CORS sees to that — but it can still cause\n // the read to run with the visitor's cookies. A query is side-effect\n // free by contract, so this is depth rather than the only defence.\n if (!actionOriginAllowed(request, url)) {\n return new Response('Cross-origin query', { status: 403 })\n }\n\n return await handleQuery(request, url)\n }\n\n // The two halves an edge cache needs: hand it a shell it may keep, and\n // finish that shell for a visitor it cannot answer for itself.\n if (options.prerendered && url.pathname === HEADER.pprShellPath) {\n return await servePprShell(request, url, options.prerendered)\n }\n\n if (\n request.method === 'POST' &&\n options.prerendered &&\n url.pathname === HEADER.pprResumePath\n ) {\n return await servePprResume(request, url, options.prerendered)\n }\n\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n // One named region of this page, asked for without mutating anything to\n // earn it. What an action invalidated does not come through here — that\n // travels back inside the action's own answer, which is the whole point of\n // marking rather than telling the client to go and ask.\n const revalidating = request.headers.get(HEADER.revalidate)\n\n if (revalidating !== null && request.headers.get(HEADER.rsc) !== null) {\n return await handleRevalidate(request, url, revalidating)\n }\n\n // An intercepted navigation renders the page you are already on, with the\n // interceptor dropped into one of its slots — so the modal opens over it\n // and the url changes. Only ever on a client navigation: a hard load has\n // no referer to open over and gets the real page.\n const interceptSlot = request.headers.get(HEADER.intercept)\n\n if (interceptSlot !== null && request.headers.get(HEADER.rsc) !== null) {\n return await handleIntercept(request, url, interceptSlot)\n }\n\n // Only now. A frozen page is a whole page, and both requests above ask for\n // something smaller than one: answering a named region with the whole\n // document puts the entire page inside that region, and answering an\n // interception with it replaces the page the modal was opening over.\n const match = matchRoute(routes, url.pathname)\n\n if (options.prerendered) {\n // A guarded route can still be frozen: whether the content is the same\n // for everyone, and whether this caller may see it, are different\n // questions. The build answers the first; this answers the second, and\n // only then is the frozen page handed over.\n const refusal = await refuseUnlessAllowed(request, match)\n\n if (refusal) return refusal\n\n const frozen = await servePrerendered(request, url, options.prerendered)\n\n if (frozen) return frozen\n }\n\n if (!match) return null\n\n const props = await propsFor(match, request)\n const layouts = match.route.layouts.map((component) => ({ component, props: {} }))\n const chain = match.route.layouts\n\n // A payload request says so with a header on the page's own url, so one\n // route serves both the document and the navigation that follows it.\n if (request.headers.get(HEADER.rsc) === null) {\n // Scoped to this render, so two requests redirecting at once cannot read\n // each other's destination.\n return await withRedirect(async (taken) => {\n // Awaited, and that await is the whole design: React resolves this\n // when the SHELL is ready, so a redirect thrown above every Suspense\n // boundary rejects here — before a byte is written, with a status line\n // still available. Nothing is buffered to make that true.\n let htmlStream: ReadableStream\n\n try {\n ;({ htmlStream } = await engine.handleRscHtmlStream(\n match.route.component,\n props,\n layouts,\n match.route.loadings,\n match.route.slots,\n {},\n undefined,\n url.pathname,\n // A route that ships no runtime gets no bootstrap and no segment\n // boundary — the boundary is itself a client component, so leaving\n // it in means no page could ever be JS-free.\n match.route.clientJs !== false,\n ))\n } catch (error) {\n // A rejected shell is how a redirect above every boundary arrives:\n // React could not finish the shell, because the component that would\n // have produced it left instead.\n //\n // The scope decides, not the error. React catches what a component\n // threw and re-raises its own — whose message is stripped in\n // production — so testing the caught value for a redirect signal\n // fails exactly where it matters, and the answer is a 500 with the\n // destination sitting in a scope nobody read.\n const refused = taken()\n\n if (refused) return redirectResponse(refused, false)\n\n\n // A guard refusing is not a failed render. Without this a visitor\n // who may not see the page gets a 500, which reads as the\n // application being broken rather than them being turned away —\n // and a host middleware refusal arrives exactly here, because the\n // engine asks before it renders anything.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n throw error\n }\n\n const early = taken()\n\n if (early) return redirectResponse(early, false)\n\n return new Response(appendLateRedirect(htmlStream, taken), {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': match.route.middleware?.length ? PER_CLIENT : REVALIDATE,\n }),\n })\n })\n }\n\n const from = sharedDepth(request.headers.get(HEADER.segments), chain)\n\n // Proposed by the host, decided by the engine: an interceptor can force a\n // wider render than the client asked for, so what goes back is the depth\n // that came out, never the one that went in.\n return await withRedirect(async (taken) => {\n let stream: ReadableStream\n let segmentDepth: number\n\n try {\n ;({ stream, segmentDepth } = await engine.handleRscStream(\n match.route.component,\n props,\n layouts,\n match.route.loadings,\n match.route.slots,\n {},\n from,\n url.pathname,\n ))\n } catch (error) {\n // Same reasoning as the document path: what the render recorded is\n // reliable, what React re-raised is not.\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n\n // A payload request is guarded exactly as the document is. Narrowing\n // a request must never narrow what is checked.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n throw error\n }\n\n const early = taken()\n\n // 204 and a header. A payload request that redirected later than this\n // carries the destination in the error digest instead, and the client's\n // RedirectBoundary performs it.\n if (early) return redirectResponse(early, true)\n\n return new Response(stream, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(segmentDepth),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n })\n }\n\n /**\n * A page rendered at build time, if there is one for this url.\n *\n * The payload has to match the depth the client shares, not simply exist.\n * Serving the whole document to a client that already holds the layouts\n * replaces the root — and replacing the root unmounts everything retained\n * behind it, so going back stops restoring what you had.\n */\n /**\n * The shell an edge cache may hold, for a route named by `?url=`.\n *\n * Only ever a build artifact, so there is nothing here that belongs to\n * whoever asked. What it deliberately does NOT return is the postponed\n * state. Next's protocol hands that to the CDN and takes it back on the\n * resume, which makes the resume endpoint parse a blob an attacker can write\n * — the shape of a known denial-of-service against it. Our origin has the\n * file already, so the state never needs to leave.\n *\n * A guarded route is refused outright rather than guarded here. Its shell is\n * not cacheable by a shared cache at all, so handing one to an edge that\n * exists to cache things is an invitation to a mistake nobody would see.\n */\n async function servePprShell(\n request: Request,\n url: URL,\n read: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n const target = url.searchParams.get('url')\n\n if (!target || !target.startsWith('/')) {\n return new Response('A url is required', { status: 400 })\n }\n\n // Matched from the url asked for, never from anything else the caller sent.\n const route = matchRoute(routes, new URL(target, url.origin).pathname)\n\n if (!route) return new Response('No such page', { status: 404 })\n\n if (route.route.middleware?.length) {\n return new Response('This route is not edge-cacheable', { status: 404 })\n }\n\n const key = pathKey(new URL(target, url.origin).pathname)\n const shell = (await read(`${key}.ppr.html`)) ?? (await read(`${patternKey(route.route)}.ppr.html`))\n\n if (shell === null) return new Response('No shell for this page', { status: 404 })\n\n return new Response(JSON.stringify({ shell, version: version ?? null }), {\n headers: withVersion({\n 'Content-Type': 'application/json',\n // Deliberately NOT the REVALIDATE the rest of the host sends. That is\n // `max-age=0, must-revalidate`, which a cache honours by treating the\n // entry as stale the moment it arrives — an edge would store this and\n // never once serve it, so the whole thing would quietly do nothing\n // while looking like it worked, because the miss path serves correct\n // pages.\n //\n // This is build output with nothing of the caller in it, and a guarded\n // route never reaches here at all, so it is genuinely cacheable. An\n // hour bounds how long a deploy can be served against a stale shell;\n // the version below catches it sooner than that.\n 'Cache-Control': 'public, max-age=3600',\n }),\n })\n }\n\n /**\n * Finish a shell for the visitor this request belongs to.\n *\n * The whole security question lives here, because the holes are the part a\n * guard exists to protect — the shell is chrome, and everything private is\n * behind the boundaries this fills in. So it runs exactly the guard chain the\n * page itself would, derived from the url and nothing else, against the\n * cookies and headers the caller actually sent.\n *\n * Which means an edge worker must forward the visitor's request, not make one\n * of its own. A resume asked for with no cookies is an anonymous visitor and\n * gets an anonymous answer.\n */\n async function servePprResume(\n request: Request,\n url: URL,\n read: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n const target = url.searchParams.get('url')\n\n if (!target || !target.startsWith('/')) {\n return new Response('A url is required', { status: 400 })\n }\n\n const pathname = new URL(target, url.origin).pathname\n const route = matchRoute(routes, pathname)\n\n if (!route) return new Response('No such page', { status: 404 })\n\n // The same refusal the document would get, before a byte of the holes is\n // rendered. Nothing below runs for a caller this turns away.\n const refusal = await refuseUnlessAllowed(request, route)\n\n if (refusal) return refusal\n\n if (!engine.handleRscResume) {\n return new Response('This engine cannot resume', { status: 500 })\n }\n\n const key = pathKey(pathname)\n const pattern = patternKey(route.route)\n\n let shellKey: string | null = null\n\n if ((await read(`${key}.ppr.html`)) !== null) shellKey = key\n else if ((await read(`${pattern}.ppr.html`)) !== null) shellKey = pattern\n\n // Read from our own artifacts. Never from the request body — that is the\n // difference between this and the protocol it is modelled on.\n const state = shellKey === null ? null : await read(`${shellKey}.postponed.json`)\n\n if (state === null) return new Response('Nothing to resume', { status: 404 })\n\n const { htmlStream } = await engine.handleRscResume(\n route.route.component,\n route.params,\n route.route.layouts.map((component) => ({ component, props: {} })),\n route.route.loadings,\n route.route.slots,\n {},\n JSON.parse(state),\n undefined,\n shellKey === key ? pathname : '',\n )\n\n // Carries the build version so a caller holding a cached shell can tell\n // that it no longer belongs to this origin. A shell from an older build\n // does not make the resume fail — it replays against slots that have moved\n // and React falls back to client rendering, silently and for good. Nothing\n // else would ever report it.\n return new Response(htmlStream, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n // Rendered for whoever asked. Never cacheable.\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n async function servePrerendered(\n request: Request,\n url: URL,\n source: NonNullable<RscHostOptions['prerendered']>,\n ): Promise<Response | null> {\n const key = pathKey(url.pathname)\n const read = async (name: string) => await source(name)\n\n // Before anything else: a route that only redirects was frozen as the\n // redirect itself, so there is no page under this url and never will be.\n const frozenRedirect = await read(`${key}.redirect.json`)\n\n if (frozenRedirect !== null) {\n const to = JSON.parse(frozenRedirect) as { status: number; location: string }\n\n return redirectResponse(to, request.headers.get(HEADER.rsc) !== null)\n }\n\n if (request.headers.get(HEADER.rsc) === null) {\n // A frozen page first; then a shell, under this url or under the route's\n // pattern. Nothing in a shell varies by param, so one shell serves every\n // url its route matches — which is the only way a route whose urls were\n // never listed gets anything frozen at all.\n const route = matchRoute(routes, url.pathname)\n const whole = await read(`${key}.html`)\n\n // A whole page is finished. Nothing to resume, nothing to render.\n if (whole !== null) {\n return new Response(whole, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n Vary: VARY_ON_RSC,\n 'Cache-Control': route?.route.middleware?.length ? PER_CLIENT : REVALIDATE,\n }),\n })\n }\n\n // Then a shell, under this url or under the route's pattern. Which of the\n // two answered is tracked, because the state that resumes it sits beside\n // the file that was found rather than beside the url that was asked for.\n let shellKey: string | null = null\n let shell = await read(`${key}.ppr.html`)\n\n if (shell !== null) {\n shellKey = key\n } else if (route) {\n const pattern = patternKey(route.route)\n\n shell = await read(`${pattern}.ppr.html`)\n\n if (shell !== null) shellKey = pattern\n }\n\n if (shell === null || shellKey === null) return null\n\n const state = await read(`${shellKey}.postponed.json`)\n\n // A shell with no state cannot be finished by anyone. It was frozen with\n // its fallbacks showing and there is no record of what came next, so\n // serving it would be serving a page that stays on its loading state for\n // good. Fall through and render the page now instead.\n if (state === null || !engine.handleRscResume || !route) return null\n\n const { htmlStream } = await engine.handleRscResume(\n route.route.component,\n route.params,\n // Empty props, because that is what the build passed. Resuming replays\n // the tree against the slots the shell left, and React matches those by\n // key — so an argument that differs from the frozen render at all is a\n // tree that \"doesn't match\", and every boundary falls back to the\n // client instead of being filled here.\n route.route.layouts.map((component) => ({ component, props: {} })),\n route.route.loadings,\n route.route.slots,\n {},\n JSON.parse(state),\n undefined,\n // A shell found under the route's pattern was frozen for no particular\n // url, so it was rendered with no page key. Handing one over now would\n // key the tree differently from the one being resumed.\n shellKey === key ? url.pathname : '',\n )\n\n // The shell first, then whatever the resume writes. React's own script\n // travels with the resumed segments and moves them into place, so this is\n // a plain concatenation and the holes land without hydration.\n const body = new ReadableStream({\n async start(controller) {\n controller.enqueue(new TextEncoder().encode(shell))\n\n const reader = htmlStream.getReader()\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n\n if (done) break\n\n controller.enqueue(value)\n }\n } finally {\n controller.close()\n }\n },\n })\n\n return new Response(body, {\n headers: withVersion({\n 'Content-Type': HTML_TYPE,\n Vary: VARY_ON_RSC,\n // The shell is cacheable; this response is not. It carries the holes,\n // which were rendered for whoever asked.\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n // Only the document is ever served frozen for a shell. The payload is what\n // fills it in, and it has to be rendered now — answering with a frozen one\n // would hand back the same fallbacks the shell already shows, and the page\n // would never finish loading.\n\n const meta = await read(`${key}.meta.json`)\n\n // Both or neither: without the chain there is no way to know which depth a\n // payload is for, and guessing means handing the client a segment for a\n // boundary it does not have.\n if (meta === null) return null\n\n const chain = (JSON.parse(meta).layouts ?? []) as string[]\n const shared = sharedDepth(request.headers.get(HEADER.segments), chain)\n\n // The variant for exactly this depth, or the whole document. Anything else\n // would be a payload for a boundary the client is not holding.\n const variant = shared > 0 ? await read(`${key}.seg${shared}.flight`) : null\n const payload = variant ?? (await read(`${key}.flight`))\n\n if (payload === null) return null\n\n return new Response(payload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(variant ? shared : 0),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n /**\n * The middleware of a route, or null to go ahead.\n *\n * Used wherever a render can be reached without the engine running the chain\n * itself: a page served from disk, and an interception, which renders a\n * component the route table did not choose.\n *\n * Asked before anything is read or rendered — the answer to a refusal must\n * not be a page that has already been fetched.\n */\n async function refuseUnlessAllowed(\n request: Request,\n match: MatchedRoute | null,\n ): Promise<Response | null> {\n // hostMiddleware as well as the engine's own. A page served from disk\n // never touches the engine, so a route guarded only by the host would be\n // handed over without anyone being asked — the guard would hold right up\n // until the build froze the page, then silently stop.\n if (!match) return null\n\n const guarded =\n (match.route.middleware?.length ?? 0) > 0 || (match.route.hostMiddleware?.length ?? 0) > 0\n\n if (!guarded) return null\n\n // A route that declares middleware and an engine that cannot run it is not\n // \"no middleware\" — it is a check that silently does not happen. Refusing\n // is the only safe reading, and it names the cause rather than serving the\n // guarded page. Reachable when a host runs a bundle built by an older\n // plugin, where the export did not exist.\n if (!engine.runRouteMiddleware) {\n return new Response(\n 'This route declares middleware, and the engine cannot run it. ' +\n 'Rebuild the app against the current @rsc-kit/core.',\n { status: 500 },\n )\n }\n\n const asPayload = request.headers.get(HEADER.rsc) !== null\n\n return await withRedirect(async (taken) => {\n try {\n await engine.runRouteMiddleware!(match.route.component, await propsFor(match, request))\n } catch (error) {\n const refused = taken()\n\n if (refused) return redirectResponse(refused, asPayload)\n\n // A visitor who may not see this page has not caused a server\n // error. Answering 500 makes a guarded route indistinguishable from\n // a broken one, in the logs and to the person looking at it.\n const status = refusalStatus(error)\n\n if (status) return new Response(refusalMessage(error), { status })\n\n throw error\n }\n\n const refused = taken()\n\n return refused ? redirectResponse(refused, asPayload) : null\n })\n }\n\n async function handleRevalidate(request: Request, url: URL, target: string): Promise<Response> {\n if (!engine.handleRscRevalidate) {\n return new Response('This build cannot revalidate', { status: 501 })\n }\n\n const match = matchRoute(routes, url.pathname)\n\n if (!match) return new Response('No such page', { status: 404 })\n\n // Scoped like the render paths: a guard above the target may refuse, and\n // that refusal is an answer rather than a failure.\n return await withRedirect(async (taken) => {\n let rscPayload: string\n\n try {\n ;({ rscPayload } = await engine.handleRscRevalidate!(\n target,\n pageContext(match, await propsFor(match, request)),\n ))\n } catch (error) {\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n throw error\n }\n\n const refused = taken()\n\n if (refused) return redirectResponse(refused, true)\n\n return new Response(rscPayload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n // Echoed so the client can tell which region it is holding.\n [HEADER.revalidate]: target,\n Vary: VARY_ON_RSC,\n 'Cache-Control': 'private, no-store',\n }),\n })\n })\n }\n\n async function handleIntercept(request: Request, url: URL, slot: string): Promise<Response> {\n const intercept = matchIntercept(routes, url.pathname, slot)\n\n if (!intercept) return new Response('No interceptor for this url', { status: 404 })\n\n // The guards of the route being intercepted, before anything is rendered.\n //\n // An interceptor exists to show the same resource as the route it stands in\n // for — a modal over /orders/[id] shows that order. So it has to be behind\n // the same checks, and nothing else in this path runs them: the engine is\n // handed the interceptor component, which the route table did not choose\n // and whose middleware chain is keyed off manifest().routes, where an\n // interceptor does not appear.\n //\n // Derived from the url, never from X-RSC-Referer. The referer is a header\n // the caller writes, and guarding by it means the caller picks the guard.\n const intercepted = matchRoute(routes, url.pathname)\n\n // Nothing to guard means nothing to serve. A url that matches an\n // interceptor but no route has no middleware chain to consult, so there is\n // no way to know whether this caller may see it — and an interceptor\n // stands in for a route, so a url with no route behind it is not a page\n // anyone was entitled to open a modal over.\n if (!intercepted) return new Response('No such page', { status: 404 })\n\n const refusal = await refuseUnlessAllowed(request, intercepted)\n\n if (refusal) return refusal\n\n const referer = request.headers.get(HEADER.referer)\n const under = referer ? matchRoute(routes, new URL(referer, url.origin).pathname) : null\n\n // Without a page to open over there is nothing to intercept: render the\n // interceptor on its own rather than answering with the wrong page.\n const component = under ? under.route.component : intercept.component\n const props = under ? await propsFor(under, request) : intercept.params\n const chain = under ? under.route.layouts : []\n const slots = under ? under.route.slots : {}\n const loadings = under ? under.route.loadings : []\n\n // The interceptor alone, when there is a page to open it over and this\n // build can render a region on its own.\n //\n // Re-rendering the page underneath would put the modal on screen at the\n // cost of rebuilding everything below the layout that declares the slot —\n // so opening a modal from a half-filled form throws the form away. The\n // page beneath is already mounted and correct; only the slot is new.\n if (under && engine.handleRscRevalidate) {\n const { rscPayload } = await engine.handleRscRevalidate(slot, {\n component: under.route.component,\n // The target's params, not the page's: a modal for /posts/hello opened\n // from /feed is about hello.\n props: intercept.params,\n layouts: [],\n loadings: [],\n // Named as the slot so the renderer finds it there, but pointing at\n // the interceptor rather than the default this route would otherwise\n // fill it with.\n parallelSlots: { [slot]: intercept.component },\n })\n\n return new Response(rscPayload, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n // Says what this payload is, so the client puts it in the slot\n // instead of treating it as a segment of the page.\n [HEADER.revalidate]: slot,\n Vary: VARY_ON_RSC,\n // Per-client by construction: which region this is was chosen by a\n // request header, so a shared cache has nothing useful to key on.\n 'Cache-Control': 'private, no-store',\n }),\n })\n }\n\n const { stream, segmentDepth } = await engine.handleRscStream(\n component,\n props,\n chain.map((layout) => ({ component: layout, props: {} })),\n loadings,\n slots,\n {},\n sharedDepth(request.headers.get(HEADER.segments), chain),\n retentionKey(url.pathname, slot),\n )\n\n return new Response(stream, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n [HEADER.segmentDepth]: String(segmentDepth),\n [HEADER.layouts]: chain.join(','),\n Vary: VARY_ON_RSC,\n 'Cache-Control': PER_CLIENT,\n }),\n })\n }\n\n async function handleQuery(request: Request, url: URL): Promise<Response | null> {\n if (!engine.handleQuery) return null\n\n // Required, and the reason is CSRF rather than routing. A GET carrying no\n // unusual header is a SIMPLE request: any page anywhere can trigger one\n // with <img src=\"…/_rsc/query?…\"> and it goes out with the visitor's\n // cookies. CORS stops them reading the answer; it does not stop the read\n // running. This header is not CORS-safelisted, so a browser preflights it\n // and nothing here answers a preflight — the same protection a POST\n // carrying X-RSC-Action already had.\n if (!request.headers.get(HEADER.query)) {\n return new Response('Missing ' + HEADER.query, { status: 400 })\n }\n\n const id = url.searchParams.get('id')\n const args = url.searchParams.get('args')\n\n if (!id || args === null) return new Response('Missing id or args', { status: 400 })\n\n // Enforced here as well as in the client, because the limit is what keeps\n // an attacker from making this endpoint decode megabytes of their payload\n // per request.\n if (url.search.length > MAX_QUERY) return new Response('Query too large', { status: 414 })\n\n const answered = await engine.handleQuery(id, args)\n\n // Unknown id and registered-but-not-a-query are the same answer on purpose.\n if (!answered) return new Response('No such query', { status: 404 })\n\n return new Response(answered.stream, {\n headers: withVersion({\n 'Content-Type': FLIGHT_TYPE,\n 'Cache-Control': answered.cacheControl,\n // The answer is narrowed by who is asking whenever a read touches the\n // session, and the request that carries that is the cookie. Without\n // this a shared cache keyed on the url alone hands one visitor\n // another's answer — for any query that opted out of no-store.\n Vary: 'Cookie, ' + HEADER.referer,\n }),\n })\n }\n\n async function handleAction(request: Request, url: URL): Promise<Response> {\n const actionId = request.headers.get(HEADER.action)\n\n if (!actionId) return new Response('Missing X-RSC-Action', { status: 400 })\n\n // The body travels as application/octet-stream so a host that parses\n // multipart cannot consume it first; its real type rides in a header.\n const body = new Uint8Array(await request.arrayBuffer())\n const contentType = request.headers.get(HEADER.contentType) ?? 'text/plain;charset=UTF-8'\n\n // Where it was invoked from, so anything the action invalidates can be\n // re-rendered against the page that is actually on screen.\n const referer = request.headers.get(HEADER.referer)\n const match = referer ? matchRoute(routes, new URL(referer, url.origin).pathname) : null\n const page = match ? pageContext(match, await propsFor(match, request)) : undefined\n\n // Scoped to this action: revalidate() called anywhere inside it, at any\n // depth, marks here and nowhere else — two requests can be in flight and\n // marking is per-request state.\n const { stream } = await withRevalidation((taken) =>\n engine.handleAction(actionId, body, contentType, page, taken),\n )\n\n return new Response(stream, {\n headers: withVersion({ 'Content-Type': 'text/x-component; charset=utf-8' }),\n })\n }\n}\n"]}