@rshono/core 1.0.0-rc.13 → 1.0.0-rc.15
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/LICENSE +21 -0
- package/README.md +29 -8
- package/dist/builder/env-shadow-loader.cjs +20 -1
- package/dist/builder/react-versions.d.ts +13 -0
- package/dist/builder/react-versions.d.ts.map +1 -0
- package/dist/builder/react-versions.js +74 -0
- package/dist/builder/react-versions.js.map +1 -0
- package/dist/builder/rspack-config.d.ts.map +1 -1
- package/dist/builder/rspack-config.js +45 -5
- package/dist/builder/rspack-config.js.map +1 -1
- package/dist/cli/build.d.ts.map +1 -1
- package/dist/cli/build.js +4 -0
- package/dist/cli/build.js.map +1 -1
- package/dist/cli/index.js +2 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/start.d.ts.map +1 -1
- package/dist/cli/start.js +10 -13
- package/dist/cli/start.js.map +1 -1
- package/dist/deploy/cloudflare/runtime.js +1 -1
- package/dist/deploy/cloudflare/runtime.js.map +1 -1
- package/dist/deploy/contract.d.ts +6 -1
- package/dist/deploy/contract.d.ts.map +1 -1
- package/dist/deploy/contract.js.map +1 -1
- package/dist/deploy/filesystem.d.ts.map +1 -1
- package/dist/deploy/filesystem.js +8 -0
- package/dist/deploy/filesystem.js.map +1 -1
- package/dist/deploy/presets.d.ts.map +1 -1
- package/dist/deploy/presets.js +24 -0
- package/dist/deploy/presets.js.map +1 -1
- package/dist/deploy/vercel/build.d.ts.map +1 -1
- package/dist/deploy/vercel/build.js +10 -4
- package/dist/deploy/vercel/build.js.map +1 -1
- package/dist/deploy/vercel/runtime.d.ts +8 -1
- package/dist/deploy/vercel/runtime.d.ts.map +1 -1
- package/dist/deploy/vercel/runtime.js +46 -3
- package/dist/deploy/vercel/runtime.js.map +1 -1
- package/dist/runtime/context.d.ts.map +1 -1
- package/dist/runtime/context.js +15 -0
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/entry.client.js +55 -11
- package/dist/runtime/entry.client.js.map +1 -1
- package/dist/runtime/entry.rsc.d.ts.map +1 -1
- package/dist/runtime/entry.rsc.js +74 -8
- package/dist/runtime/entry.rsc.js.map +1 -1
- package/dist/runtime/flight-inject.d.ts.map +1 -1
- package/dist/runtime/flight-inject.js +31 -4
- package/dist/runtime/flight-inject.js.map +1 -1
- package/dist/runtime/request.d.ts +12 -4
- package/dist/runtime/request.d.ts.map +1 -1
- package/dist/runtime/request.js +28 -7
- package/dist/runtime/request.js.map +1 -1
- package/dist/server/prerendered.d.ts +11 -3
- package/dist/server/prerendered.d.ts.map +1 -1
- package/dist/server/prerendered.js +31 -5
- package/dist/server/prerendered.js.map +1 -1
- package/dist/server/shutdown.d.ts +4 -1
- package/dist/server/shutdown.d.ts.map +1 -1
- package/dist/server/shutdown.js +4 -1
- package/dist/server/shutdown.js.map +1 -1
- package/dist/server/ssg.js +1 -1
- package/dist/server/ssg.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/runtime/context.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,6FAA6F;AAC7F,qEAAqE;AACrE,oDAAoD;AACpD;;;;;;;GAOG;AAGH,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAc9D,MAAM,cAAc,GAAG,IAAI,iBAAiB,EAAW,CAAC;AAExD,2HAA2H;AAC3H,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA2B,CAAC;AAExD,sGAAsG;AACtG,iDAAiD;AACjD,MAAM,SAAS,GAAG,IAAI,OAAO,EAAW,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,CAAU;IACxC,SAAS,CAAC,GAAG,CAAC,CAA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;;;;;;;;GAiBG;AACH,MAAM,UAAU,QAAQ,CAAC,QAAgB,EAAE,MAAM,GAAmB,GAAG;IACrE,MAAM,IAAI,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC7C,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,QAAQ;IACtB,MAAM,IAAI,cAAc,EAAE,CAAC;AAC7B,CAAC;AAwBD,IAAI,YAA4C,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,aAAa,CAAC,OAA2B;IACvD,YAAY,GAAG,OAAO,CAAC;AACzB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc,EAAE,IAA8C;IAC9F,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACnC,IAAI,CAAC,YAAY;QAAE,OAAO;IAC1B,IAAI,CAAC;QACH,YAAY,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,YAAY,EAAE,CAAC;QACtB,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,YAAY,CAAC,CAAC;IAC3E,CAAC;AACH,CAAC","sourcesContent":["// `__RSHONO_CONFIG__` is a global const, and an `import` cannot bring one into scope — a path reference is\n// the only way to reach it, which is the whole reason that file is separate. See its header.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../types/rshono-config.d.ts\" />\n/**\n * The request context: {@link getRequestContext} and the {@link RequestContext} it returns, the\n * {@link redirect} / {@link notFound} control-flow helpers, and the {@link onServerError} reporting\n * funnel — plus the `@internal` plumbing that binds a request to the async context.\n *\n * The public half is re-exported by `runtime/server.ts`, which is what `@rshono/core/server` resolves\n * to; an app imports that.\n */\n\nimport type { Context, Env } from 'hono';\nimport { deleteCookie, getCookie, setCookie } from 'hono/cookie';\nimport type { CookieOptions } from 'hono/utils/cookie';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { NotFoundSignal, RedirectSignal } from './control.js';\n\n/**\n * HTTP status codes accepted by {@link redirect}.\n *\n * - `301` Moved Permanently, `308` Permanent Redirect — cacheable, permanent.\n * - `302` Found, `307` Temporary Redirect — temporary.\n * - `303` See Other — the default; forces a `GET` on the target, which is what you almost always want\n * after a form action (post/redirect/get).\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status#redirection_messages | MDN — redirection status codes}\n */\nexport type RedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nconst contextStorage = new AsyncLocalStorage<Context>();\n\n/** One {@link RequestContext} per Hono {@link Context}, so repeated `getRequestContext()` calls share its lazy getters. */\nconst wrappers = new WeakMap<Context, RequestContext>();\n\n// Keyed on the Hono context rather than held as a field, so marking a request never forces the lazily\n// built `RequestContext` wrapper into existence.\nconst rendering = new WeakSet<Context>();\n\n/**\n * Marks the request as having entered its page render, which is what makes\n * {@link RequestContext.setHeader} and `ctx.cookies.set()` start throwing.\n *\n * @internal\n */\nexport function beginPageRender(c: Context): void {\n rendering.add(c);\n}\n\n/** The shared refusal for a response write that arrived too late — the message names where it belongs instead. */\nfunction tooLateToWrite(call: string): never {\n throw new Error(\n `[rshono] ${call} was called while rendering a page, which is too late to affect the response. ` +\n 'A page streams, so its response head is already committed by the time the component runs — the ' +\n 'write would land on a full page load and be silently dropped on a soft navigation. Do it from a ' +\n \"'use server' action instead; or, in middleware and { type: 'endpoint' } routes — which are handed \" +\n \"Hono's `c` directly and run outside the request context — with `c.header(…)` / `setCookie(c, …)`.\",\n );\n}\n\n/** The shared refusal for a Hono `Context` member a page has no way to use. See the stubs on {@link RequestContext}. */\nfunction notOnContext(call: string, instead: string): never {\n throw new Error(\n `[rshono] ctx.${call} does not exist. A page returns JSX and the framework builds the response from it, ` +\n `so Hono's response builders have nothing to return to. ${instead}`,\n );\n}\n\n// Snapshotted rather than spread per request: enumerating `process.env` crosses into the host\n// environment (~20µs). Lazily, because `loadEnvFiles()` runs after this module is imported — so a\n// mutation after the first `ctx.env` read is not picked up.\nlet envSnapshot: Record<string, string | undefined> | undefined;\n\nfunction processEnv(): Record<string, string | undefined> {\n return (envSnapshot ??= typeof process !== 'undefined' && process.env ? { ...process.env } : {});\n}\n\n// Set by `build.ts` before it imports the app bundle, which inlines its own copy of this module — so\n// `process.env` is what crosses that boundary rather than a module-level flag.\nconst prerendering = typeof process !== 'undefined' && !!process.env?.RSHONO_PRERENDER;\n\n/**\n * Runs `fn` with `c` bound as the ambient request context, so {@link getRequestContext} resolves to it\n * anywhere in the call tree.\n *\n * @internal\n */\nexport function runWithContext<T>(c: Context, fn: () => T): T {\n return contextStorage.run(c, fn);\n}\n\n/**\n * The matched route params, or an empty object when there is no active match.\n *\n * @internal\n */\nexport function readParams(c: Context): Record<string, string> {\n try {\n return c.req.param();\n } catch {\n return {};\n }\n}\n\n/** A proxy chain appends to these headers, so the client-facing value is the first entry. */\nfunction firstForwardedValue(header: string | undefined): string | undefined {\n const first = header?.split(',')[0]?.trim();\n return first || undefined;\n}\n\n// Read through `typeof`: DefinePlugin inlines this into the server bundle, but the module is also the\n// public `@rshono/core/server` entry, which tooling can load without one. Absent means don't trust.\nconst trustProxy = typeof __RSHONO_CONFIG__ !== 'undefined' && __RSHONO_CONFIG__.trustProxy;\n\n/**\n * The browser-facing {@link URL} for a request, resolved from Hono's {@link Context} — a fresh\n * instance per call.\n *\n * `c.req.url` is the internal address the server was reached on, which is wrong behind a proxy;\n * `X-Forwarded-Host` / `-Proto` correct it, but only when `trustProxy` is enabled in\n * `rshono.config.ts` — they are client-supplied, so trusting them unconditionally would let anyone\n * dictate the origin of every absolute URL the app builds.\n *\n * This is the form for **middleware**, which is handed `c` and runs outside the request context — and\n * so the way to give Hono's own middleware the origin the browser actually used. In a server component\n * or action, prefer {@link RequestContext.url}, the same value cached per request.\n *\n * @param c - The Hono {@link Context} for the request.\n * @returns The browser-facing URL — proxy-corrected under `trustProxy`, `c.req.url` otherwise.\n *\n * @example\n * ```ts\n * // src/server.ts — a CSRF check that still works behind a proxy that rewrites Host\n * import { publicUrl } from '@rshono/core/server';\n * import { csrf } from 'hono/csrf';\n *\n * server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));\n * ```\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\nexport function publicUrl(c: Context): URL {\n const url = new URL(c.req.url);\n if (!trustProxy) return url;\n\n const forwardedHost = firstForwardedValue(c.req.header('x-forwarded-host'));\n // Parsed, not assigned to `url.host`: that setter keeps the existing port when the new value has none.\n const forwarded = forwardedHost ? URL.parse(`http://${forwardedHost}`) : null;\n if (forwarded) {\n url.hostname = forwarded.hostname;\n url.port = forwarded.port;\n }\n\n // Only the two schemes a browser could have requested; anything else leaves the scheme alone.\n const forwardedProto = firstForwardedValue(c.req.header('x-forwarded-proto'));\n if (forwardedProto === 'http' || forwardedProto === 'https') url.protocol = forwardedProto;\n\n return url;\n}\n\n/**\n * The environment available to a request: Workers `Bindings` merged with process env vars. Values not\n * declared in `Bindings` are typed as `string | undefined`. See {@link RequestContext.env}.\n *\n * @see {@link https://hono.dev/docs/getting-started/cloudflare-workers#bindings | Hono — bindings}\n */\nexport type EnvVars<E extends Env> = E['Bindings'] & Record<string, string | undefined>;\n\n/**\n * Read-mostly wrapper around Hono's {@link Context}, for server components and server actions.\n *\n * Obtain one with {@link getRequestContext}, or take it off a page's `ctx` prop — the same object.\n * Never construct it yourself. One instance is reused for the whole request, so its lazy getters\n * ({@link RequestContext.url}, {@link RequestContext.env}) are computed at most once.\n *\n * @typeParam E - The Hono {@link Env} describing this app's `Bindings` and `Variables`, so\n * {@link RequestContext.var} and {@link RequestContext.env} stay typed.\n *\n * @example\n * ```tsx\n * import { getRequestContext } from '@rshono/core/server';\n *\n * export default async function Whoami() {\n * const ctx = getRequestContext();\n * const session = ctx.cookies.get('session');\n * return <p>{ctx.url.pathname} — {session ?? 'anonymous'}</p>;\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}, reachable in full via {@link RequestContext.hono}\n */\nexport class RequestContext<E extends Env = Env> {\n #raw: Context<E>;\n #url?: URL;\n #env?: EnvVars<E>;\n #params?: Record<string, string>;\n\n /**\n * One instance is created per request and handed out by {@link getRequestContext} or the `ctx` page\n * prop. Application code never calls this.\n *\n * @internal\n */\n constructor(c: Context<E>) {\n this.#raw = c;\n }\n\n /**\n * The underlying Hono {@link Context} — the escape hatch for what this wrapper does not expose, such\n * as `executionCtx.waitUntil()` on Workers.\n *\n * Its response builders (`redirect`, `json`, `body`, `status`, …) still do nothing from inside a\n * page: reaching them through here bypasses the errors the stubs on this class throw, it does not\n * make them work.\n *\n * @example\n * ```ts\n * getRequestContext().hono.executionCtx.waitUntil(logAsync()); // Workers\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}\n */\n // Every member here is a getter or method so that none is *own enumerable*: React's \"you cannot pass\n // this to a client component\" diagnostic walks `Object.keys` recursively with no cycle guard, and the\n // Hono context graph reaches the socket through `req.raw`. `cookies` is the one own property, and it\n // is a shallow object of four functions.\n get hono(): Context<E> {\n return this.#raw;\n }\n\n /**\n * The parsed request — method, headers, path params, query and the body readers. Hono's\n * {@link Context.req}, unwrapped, so `ctx.req.header('authorization')` rather than\n * `ctx.hono.req.header(…)`.\n *\n * Reads only; setting a *response* header is {@link RequestContext.setHeader}, deliberately spelled\n * differently.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.req.method; // 'GET'\n * ctx.req.header('authorization'); // string | undefined\n * ctx.req.query('tab'); // string | undefined\n * ```\n *\n * @see {@link https://hono.dev/docs/api/request | Hono — HonoRequest}\n */\n get req(): Context<E>['req'] {\n return this.#raw.req;\n }\n\n /**\n * Matched route params for this request, e.g. `{ id: '42' }` for `/profile/:id`. Empty when no route\n * matched.\n *\n * A page is handed the same record as its `params` prop, typed key-by-key from its route path, and\n * that is the better read where it exists. This is for everywhere else — a nested server component,\n * or a `'use server'` action.\n */\n get params(): Record<string, string> {\n return (this.#params ??= readParams(this.#raw as Context));\n }\n\n /**\n * The browser-facing request URL. Parsed once and cached, so every read within a request returns the\n * same instance — treat it as read-only.\n *\n * `X-Forwarded-Host` / `-Proto` are honoured only when `trustProxy` is enabled in\n * `rshono.config.ts`, since any client can send them.\n *\n * @example `const tab = getRequestContext().url.searchParams.get('tab');`\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\n get url(): URL {\n return (this.#url ??= publicUrl(this.#raw as Context));\n }\n\n /**\n * Typed variables set by middleware via `c.set('user', …)`, read here as `ctx.var.user`. Type them by\n * parameterising this class's {@link Env}.\n *\n * @example\n * ```ts\n * type AppEnv = { Variables: { user: { id: string } } };\n * const { user } = getRequestContext<AppEnv>().var; // typed, set by your middleware\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context#var | Hono — c.var}\n * @see {@link https://www.rshono.com/docs/hono#typing-the-context | Docs — typing the context}\n */\n get var(): Readonly<E['Variables']> {\n return this.#raw.var;\n }\n\n /**\n * Environment for the request: process env vars merged with runtime bindings, which win on conflict.\n * Computed once and cached.\n *\n * @example `const key = getRequestContext().env.STRIPE_SECRET_KEY;`\n *\n * @see {@link https://hono.dev/docs/api/context#env | Hono — c.env}\n * @see {@link https://www.rshono.com/docs/configuration#environment-and-secrets | Docs — environment and secrets}\n */\n get env(): EnvVars<E> {\n if (this.#env) return this.#env;\n const bindings = this.#raw.env as Record<string, unknown> | undefined;\n return (this.#env = (bindings ? { ...processEnv(), ...bindings } : processEnv()) as EnvVars<E>);\n }\n\n /**\n * Read and write request/response cookies.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.cookies.get('session'); // string | undefined\n * ctx.cookies.set('session', id, { httpOnly: true, sameSite: 'Lax', path: '/' });\n * ctx.cookies.delete('session', { path: '/' });\n * ```\n *\n * @see {@link https://hono.dev/docs/helpers/cookie | Hono — cookie helper}, which this wraps\n */\n cookies = {\n /** Reads a single cookie by name, or `undefined` if absent. Safe anywhere, a page included. */\n get: (name: string): string | undefined => getCookie(this.#raw, name),\n /** Reads every cookie as a `{ name: value }` record. Safe anywhere, a page included. */\n all: (): Record<string, string> => getCookie(this.#raw),\n /**\n * Sets a cookie on the response. See Hono's {@link CookieOptions} for `path`, `httpOnly`, `maxAge`\n * and the rest.\n *\n * **Throws inside a page render** — a `Set-Cookie` is a special case of\n * {@link RequestContext.setHeader}. Set cookies from a `'use server'` action, or with Hono's\n * `setCookie(c, …)` in middleware and endpoint routes.\n *\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @see {@link https://hono.dev/docs/helpers/cookie#options | Hono — cookie options}\n */\n set: (name: string, value: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.set()');\n setCookie(this.#raw, name, value, options);\n },\n /**\n * Clears a cookie. Pass the same `path`/`domain` it was set with so the browser matches it.\n * Throws inside a page render, exactly as `set` does.\n *\n * @throws If called while a page is rendering.\n */\n delete: (name: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.delete()');\n deleteCookie(this.#raw, name, options);\n },\n };\n\n #assertWritable(call: string): void {\n if (rendering.has(this.#raw as Context)) tooLateToWrite(call);\n }\n\n /**\n * Sets a header on the response — from a `'use server'` action, which is the one place a request\n * context exists *and* the response is still open.\n *\n * From inside a page it throws: a page streams, so its response head is already committed by then,\n * and the write would land on a full page load but vanish on a soft navigation.\n *\n * Middleware and `{ type: 'endpoint' }` routes are handed Hono's `c` directly and use `c.header(…)`.\n * That is also where a header belonging to the *page* goes — `Cache-Control`, `X-Robots-Tag` — since\n * middleware runs before the render.\n *\n * @param name - Header name, case-insensitive.\n * @param value - Header value.\n * @param options - `{ append: true }` to add another value rather than replace.\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @example\n * ```ts\n * 'use server';\n * export async function logout() {\n * const ctx = getRequestContext();\n * ctx.cookies.delete('session', { path: '/' });\n * ctx.setHeader('clear-site-data', '\"cache\", \"storage\"');\n * redirect('/');\n * }\n * ```\n */\n setHeader(name: string, value: string, options?: { append?: boolean }): void {\n this.#assertWritable('ctx.setHeader()');\n this.#raw.header(name, value, options);\n }\n\n // Hono's response builders, restated as errors naming what to use instead — through `ctx.hono` every\n // one of them is a silent no-op from a page. `@deprecated` strikes them through in autocomplete; the\n // unread `..._args` is so `ctx.redirect('/x')` reaches the thrown message rather than an arity error.\n\n /** @deprecated Not available on a page's context — use `redirect()` from `@rshono/core/server`. */\n redirect(..._args: unknown[]): never {\n return notOnContext(\n 'redirect(location, status?)',\n \"Use `redirect()` from '@rshono/core/server', which throws a signal the framework turns into a real redirect.\",\n );\n }\n\n /** @deprecated Not available on a page's context — use `notFound()` from `@rshono/core/server`. */\n notFound(..._args: unknown[]): never {\n return notOnContext('notFound()', \"Use `notFound()` from '@rshono/core/server', which aborts the render and shows the app's not-found page.\");\n }\n\n /** @deprecated A page renders JSX. For a JSON response, use an `{ type: 'endpoint' }` route. */\n json(..._args: unknown[]): never {\n return notOnContext('json(object)', \"For a JSON response use an { type: 'endpoint' } route; to read the request body use `ctx.req.json()`.\");\n }\n\n /** @deprecated A page renders JSX. For a text response, use an `{ type: 'endpoint' }` route. */\n text(..._args: unknown[]): never {\n return notOnContext('text(string)', \"For a text response use an { type: 'endpoint' } route; to read the request body use `ctx.req.text()`.\");\n }\n\n /** @deprecated A page renders JSX, which the framework turns into HTML for you. */\n html(..._args: unknown[]): never {\n return notOnContext('html(string)', \"A page's JSX is already its HTML; for a hand-built HTML response use an { type: 'endpoint' } route.\");\n }\n\n /** @deprecated Not available on a page's context. To read the request body, use `ctx.req`. */\n body(..._args: unknown[]): never {\n return notOnContext(\n 'body(data, …)',\n \"To read the *request* body use `ctx.req.json()` / `ctx.req.text()` / `ctx.req.formData()`; to build a response, use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated A page's status is set by the framework — use `notFound()`, or an endpoint route. */\n status(..._args: unknown[]): never {\n return notOnContext(\n 'status(code)',\n \"A page's status is the framework's: 200, 404 via `notFound()`, 500 when it throws. For any other code use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated Renamed — use `ctx.setHeader(name, value)`, which is valid from a `'use server'` action. */\n header(..._args: unknown[]): never {\n return notOnContext(\n 'header(name, value)',\n \"Use `ctx.setHeader(name, value)` from a 'use server' action, or `c.header(…)` in middleware — a page renders too late to set one.\",\n );\n }\n}\n\n/**\n * The {@link RequestContext} for the current request — URL, cookies, params, env and middleware\n * variables — read from a server component or a server action. Memoised per request, so repeated calls\n * return the same instance.\n *\n * A page is handed that same object as its `ctx` prop, so this import is for everywhere else: a nested\n * server component, or a `'use server'` action module.\n *\n * @typeParam E - The app's Hono {@link Env}, to type {@link RequestContext.var} and {@link RequestContext.env}.\n * @throws If called at module load, where there is no ambient context to resolve.\n * @throws If called while prerendering a `render: 'static'` route, which has no\n * per-request context at build time — mark the route `render: 'dynamic'` instead.\n *\n * @example\n * ```ts\n * 'use server';\n * import { getRequestContext, redirect } from '@rshono/core/server';\n *\n * export async function login(form: FormData) {\n * getRequestContext().cookies.set('session', String(form.get('email')), { httpOnly: true });\n * redirect('/dashboard');\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n */\nexport function getRequestContext<E extends Env = Env>(): RequestContext<E> {\n if (prerendering) {\n throw new Error(\n \"[rshono] getRequestContext() was called while prerendering a `render: 'static'` route. A static page \" +\n 'is rendered once at build time, so it has no per-request context to read (URL, cookies, ' +\n \"headers, env). Change this route to `render: 'dynamic'` so it renders per request, or remove \" +\n 'the getRequestContext() call.',\n );\n }\n const c = contextStorage.getStore();\n if (!c) {\n throw new Error(\n '[rshono] getRequestContext() was called outside a request. It only works inside a server component or a server action, not at module load.',\n );\n }\n let ctx = wrappers.get(c);\n if (!ctx) {\n ctx = new RequestContext(c);\n wrappers.set(c, ctx);\n }\n return ctx as unknown as RequestContext<E>;\n}\n\n/**\n * Redirects the request to `location`, by throwing a control signal the framework turns into an HTTP\n * redirect.\n *\n * Because it throws it never returns, so TypeScript narrows away everything after the call and there\n * is nothing to `return`. Don't wrap it in a `try/catch` that swallows the signal.\n *\n * @param location - Absolute path or URL to redirect to, e.g. `/dashboard`.\n * @param status - Redirect {@link RedirectStatus}; defaults to `303` (See Other), which is what makes\n * the browser follow up with a `GET` after a form action.\n *\n * @example\n * ```ts\n * const session = getRequestContext().cookies.get('session');\n * if (!session) redirect('/login');\n * // session is defined below this line\n * ```\n */\nexport function redirect(location: string, status: RedirectStatus = 303): never {\n throw new RedirectSignal(location, status);\n}\n\n/**\n * Aborts the current render with a 404, rendering the app's `notFound` page.\n *\n * Like {@link redirect} it throws a control signal and never returns, so TypeScript narrows away\n * everything after the call. Don't catch-and-swallow it.\n *\n * @example\n * ```tsx\n * export default async function Page({ params }: PageProps<'/users/:id'>) {\n * const user = await db.user.find(params.id);\n * if (!user) notFound();\n * return <Profile user={user} />; // user is non-null here\n * }\n * ```\n */\nexport function notFound(): never {\n throw new NotFoundSignal();\n}\n\n/**\n * Which stage of a request produced an error handed to a {@link ServerErrorHandler}.\n *\n * - `action` — a `'use server'` function threw. React sends the client an opaque marker with no\n * message in production, so this is the only place the real error is visible.\n * - `render` — a server component threw while the flight payload was being produced.\n * - `ssr` — SSR failed before the HTML shell could be sent, so the `error` page was unreachable too.\n * - `request` — anything else that reached the top-level handler, a thrown endpoint route included.\n */\nexport type ServerErrorSource = 'action' | 'render' | 'ssr' | 'request';\n\n/** What an {@link ServerErrorHandler} is told about an error, beyond the error itself. */\nexport interface ServerErrorContext {\n /** The stage that produced it — see {@link ServerErrorSource}. */\n source: ServerErrorSource;\n /** The request being served, for the URL, method and headers. */\n request: Request;\n}\n\n/** Handler registered with {@link onServerError}. Called for the side effect; its return value is ignored. */\nexport type ServerErrorHandler = (error: unknown, context: ServerErrorContext) => void;\n\nlet errorHandler: ServerErrorHandler | undefined;\n\n/**\n * Registers a handler for every error the framework catches, so they can reach an error tracker\n * (Sentry, Datadog, a log pipeline) instead of only `stderr`.\n *\n * Call it once, at the top level of `src/server.ts`, which is imported as the server starts.\n * Registering again replaces the previous handler. Errors still go to `stderr` either way, and a\n * handler that throws is caught and logged — reporting can never fail a request.\n *\n * @example\n * ```ts\n * // src/server.ts\n * import * as Sentry from '@sentry/node';\n * import { onServerError } from '@rshono/core/server';\n *\n * onServerError((error, { source, request }) => {\n * Sentry.captureException(error, { tags: { source }, extra: { url: request.url } });\n * });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/hono#error-reporting | Docs — error reporting}\n */\nexport function onServerError(handler: ServerErrorHandler): void {\n errorHandler = handler;\n}\n\n/**\n * Logs an error and forwards it to the registered {@link ServerErrorHandler} — the single funnel every\n * caught server-side error goes through.\n *\n * @internal\n */\nexport function reportServerError(error: unknown, info: ServerErrorContext & { message: string }): void {\n console.error(info.message, error);\n if (!errorHandler) return;\n try {\n errorHandler(error, { source: info.source, request: info.request });\n } catch (handlerError) {\n console.error('[rshono] the onServerError handler threw:', handlerError);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/runtime/context.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,6FAA6F;AAC7F,qEAAqE;AACrE,oDAAoD;AACpD;;;;;;;GAOG;AAGH,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAc9D,MAAM,cAAc,GAAG,IAAI,iBAAiB,EAAW,CAAC;AAExD,2HAA2H;AAC3H,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA2B,CAAC;AAExD,sGAAsG;AACtG,i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Y,CAAC,CAAC;IAC3E,CAAC;AACH,CAAC","sourcesContent":["// `__RSHONO_CONFIG__` is a global const, and an `import` cannot bring one into scope — a path reference is\n// the only way to reach it, which is the whole reason that file is separate. See its header.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../types/rshono-config.d.ts\" />\n/**\n * The request context: {@link getRequestContext} and the {@link RequestContext} it returns, the\n * {@link redirect} / {@link notFound} control-flow helpers, and the {@link onServerError} reporting\n * funnel — plus the `@internal` plumbing that binds a request to the async context.\n *\n * The public half is re-exported by `runtime/server.ts`, which is what `@rshono/core/server` resolves\n * to; an app imports that.\n */\n\nimport type { Context, Env } from 'hono';\nimport { deleteCookie, getCookie, setCookie } from 'hono/cookie';\nimport type { CookieOptions } from 'hono/utils/cookie';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { NotFoundSignal, RedirectSignal } from './control.js';\n\n/**\n * HTTP status codes accepted by {@link redirect}.\n *\n * - `301` Moved Permanently, `308` Permanent Redirect — cacheable, permanent.\n * - `302` Found, `307` Temporary Redirect — temporary.\n * - `303` See Other — the default; forces a `GET` on the target, which is what you almost always want\n * after a form action (post/redirect/get).\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status#redirection_messages | MDN — redirection status codes}\n */\nexport type RedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nconst contextStorage = new AsyncLocalStorage<Context>();\n\n/** One {@link RequestContext} per Hono {@link Context}, so repeated `getRequestContext()` calls share its lazy getters. */\nconst wrappers = new WeakMap<Context, RequestContext>();\n\n// Keyed on the Hono context rather than held as a field, so marking a request never forces the lazily\n// built `RequestContext` wrapper into existence.\nconst rendering = new WeakSet<Context>();\n\n/**\n * Marks the request as having entered its page render, which is what makes\n * {@link RequestContext.setHeader} and `ctx.cookies.set()` start throwing.\n *\n * @internal\n */\nexport function beginPageRender(c: Context): void {\n rendering.add(c);\n}\n\n/** The shared refusal for a response write that arrived too late — the message names where it belongs instead. */\nfunction tooLateToWrite(call: string): never {\n throw new Error(\n `[rshono] ${call} was called while rendering a page, which is too late to affect the response. ` +\n 'A page streams, so its response head is already committed by the time the component runs — the ' +\n 'write would land on a full page load and be silently dropped on a soft navigation. Do it from a ' +\n \"'use server' action instead; or, in middleware and { type: 'endpoint' } routes — which are handed \" +\n \"Hono's `c` directly and run outside the request context — with `c.header(…)` / `setCookie(c, …)`.\",\n );\n}\n\n/** The shared refusal for a Hono `Context` member a page has no way to use. See the stubs on {@link RequestContext}. */\nfunction notOnContext(call: string, instead: string): never {\n throw new Error(\n `[rshono] ctx.${call} does not exist. A page returns JSX and the framework builds the response from it, ` +\n `so Hono's response builders have nothing to return to. ${instead}`,\n );\n}\n\n// Snapshotted rather than spread per request: enumerating `process.env` crosses into the host\n// environment (~20µs). Lazily, because `loadEnvFiles()` runs after this module is imported — so a\n// mutation after the first `ctx.env` read is not picked up.\nlet envSnapshot: Record<string, string | undefined> | undefined;\n\nfunction processEnv(): Record<string, string | undefined> {\n return (envSnapshot ??= typeof process !== 'undefined' && process.env ? { ...process.env } : {});\n}\n\n// Set by `build.ts` before it imports the app bundle, which inlines its own copy of this module — so\n// `process.env` is what crosses that boundary rather than a module-level flag.\nconst prerendering = typeof process !== 'undefined' && !!process.env?.RSHONO_PRERENDER;\n\n/**\n * Runs `fn` with `c` bound as the ambient request context, so {@link getRequestContext} resolves to it\n * anywhere in the call tree.\n *\n * @internal\n */\nexport function runWithContext<T>(c: Context, fn: () => T): T {\n return contextStorage.run(c, fn);\n}\n\n/**\n * The matched route params, or an empty object when there is no active match.\n *\n * @internal\n */\nexport function readParams(c: Context): Record<string, string> {\n try {\n return c.req.param();\n } catch {\n return {};\n }\n}\n\n/** A proxy chain appends to these headers, so the client-facing value is the first entry. */\nfunction firstForwardedValue(header: string | undefined): string | undefined {\n const first = header?.split(',')[0]?.trim();\n return first || undefined;\n}\n\n// Read through `typeof`: DefinePlugin inlines this into the server bundle, but the module is also the\n// public `@rshono/core/server` entry, which tooling can load without one. Absent means don't trust.\nconst trustProxy = typeof __RSHONO_CONFIG__ !== 'undefined' && __RSHONO_CONFIG__.trustProxy;\n\n/**\n * The browser-facing {@link URL} for a request, resolved from Hono's {@link Context} — a fresh\n * instance per call.\n *\n * `c.req.url` is the internal address the server was reached on, which is wrong behind a proxy;\n * `X-Forwarded-Host` / `-Proto` correct it, but only when `trustProxy` is enabled in\n * `rshono.config.ts` — they are client-supplied, so trusting them unconditionally would let anyone\n * dictate the origin of every absolute URL the app builds.\n *\n * This is the form for **middleware**, which is handed `c` and runs outside the request context — and\n * so the way to give Hono's own middleware the origin the browser actually used. In a server component\n * or action, prefer {@link RequestContext.url}, the same value cached per request.\n *\n * @param c - The Hono {@link Context} for the request.\n * @returns The browser-facing URL — proxy-corrected under `trustProxy`, `c.req.url` otherwise.\n *\n * @example\n * ```ts\n * // src/server.ts — a CSRF check that still works behind a proxy that rewrites Host\n * import { publicUrl } from '@rshono/core/server';\n * import { csrf } from 'hono/csrf';\n *\n * server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));\n * ```\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\nexport function publicUrl(c: Context): URL {\n const url = new URL(c.req.url);\n if (!trustProxy) return url;\n\n const forwardedHost = firstForwardedValue(c.req.header('x-forwarded-host'));\n // Parsed, not assigned to `url.host`: that setter keeps the existing port when the new value has none.\n const forwarded = forwardedHost ? URL.parse(`http://${forwardedHost}`) : null;\n if (forwarded) {\n url.hostname = forwarded.hostname;\n url.port = forwarded.port;\n }\n\n // Only the two schemes a browser could have requested; anything else leaves the scheme alone.\n const forwardedProto = firstForwardedValue(c.req.header('x-forwarded-proto'));\n if (forwardedProto === 'http' || forwardedProto === 'https') url.protocol = forwardedProto;\n\n return url;\n}\n\n/**\n * The environment available to a request: Workers `Bindings` merged with process env vars. Values not\n * declared in `Bindings` are typed as `string | undefined`. See {@link RequestContext.env}.\n *\n * @see {@link https://hono.dev/docs/getting-started/cloudflare-workers#bindings | Hono — bindings}\n */\nexport type EnvVars<E extends Env> = E['Bindings'] & Record<string, string | undefined>;\n\n/**\n * Read-mostly wrapper around Hono's {@link Context}, for server components and server actions.\n *\n * Obtain one with {@link getRequestContext}, or take it off a page's `ctx` prop — the same object.\n * Never construct it yourself. One instance is reused for the whole request, so its lazy getters\n * ({@link RequestContext.url}, {@link RequestContext.env}) are computed at most once.\n *\n * @typeParam E - The Hono {@link Env} describing this app's `Bindings` and `Variables`, so\n * {@link RequestContext.var} and {@link RequestContext.env} stay typed.\n *\n * @example\n * ```tsx\n * import { getRequestContext } from '@rshono/core/server';\n *\n * export default async function Whoami() {\n * const ctx = getRequestContext();\n * const session = ctx.cookies.get('session');\n * return <p>{ctx.url.pathname} — {session ?? 'anonymous'}</p>;\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}, reachable in full via {@link RequestContext.hono}\n */\nexport class RequestContext<E extends Env = Env> {\n #raw: Context<E>;\n #url?: URL;\n #env?: EnvVars<E>;\n #params?: Record<string, string>;\n\n /**\n * One instance is created per request and handed out by {@link getRequestContext} or the `ctx` page\n * prop. Application code never calls this.\n *\n * @internal\n */\n constructor(c: Context<E>) {\n this.#raw = c;\n }\n\n /**\n * The underlying Hono {@link Context} — the escape hatch for what this wrapper does not expose, such\n * as `executionCtx.waitUntil()` on Workers.\n *\n * Its response builders (`redirect`, `json`, `body`, `status`, …) still do nothing from inside a\n * page: reaching them through here bypasses the errors the stubs on this class throw, it does not\n * make them work.\n *\n * @example\n * ```ts\n * getRequestContext().hono.executionCtx.waitUntil(logAsync()); // Workers\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}\n */\n // Every member here is a getter or method so that none is *own enumerable*: React's \"you cannot pass\n // this to a client component\" diagnostic walks `Object.keys` recursively with no cycle guard, and the\n // Hono context graph reaches the socket through `req.raw`. `cookies` is the one own property, and it\n // is a shallow object of four functions.\n get hono(): Context<E> {\n return this.#raw;\n }\n\n /**\n * The parsed request — method, headers, path params, query and the body readers. Hono's\n * {@link Context.req}, unwrapped, so `ctx.req.header('authorization')` rather than\n * `ctx.hono.req.header(…)`.\n *\n * Reads only; setting a *response* header is {@link RequestContext.setHeader}, deliberately spelled\n * differently.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.req.method; // 'GET'\n * ctx.req.header('authorization'); // string | undefined\n * ctx.req.query('tab'); // string | undefined\n * ```\n *\n * @see {@link https://hono.dev/docs/api/request | Hono — HonoRequest}\n */\n get req(): Context<E>['req'] {\n return this.#raw.req;\n }\n\n /**\n * Matched route params for this request, e.g. `{ id: '42' }` for `/profile/:id`. Empty when no route\n * matched.\n *\n * A page is handed the same record as its `params` prop, typed key-by-key from its route path, and\n * that is the better read where it exists. This is for everywhere else — a nested server component,\n * or a `'use server'` action.\n */\n get params(): Record<string, string> {\n return (this.#params ??= readParams(this.#raw as Context));\n }\n\n /**\n * The browser-facing request URL. Parsed once and cached, so every read within a request returns the\n * same instance — treat it as read-only.\n *\n * `X-Forwarded-Host` / `-Proto` are honoured only when `trustProxy` is enabled in\n * `rshono.config.ts`, since any client can send them.\n *\n * @example `const tab = getRequestContext().url.searchParams.get('tab');`\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\n get url(): URL {\n return (this.#url ??= publicUrl(this.#raw as Context));\n }\n\n /**\n * Typed variables set by middleware via `c.set('user', …)`, read here as `ctx.var.user`. Type them by\n * parameterising this class's {@link Env}.\n *\n * @example\n * ```ts\n * type AppEnv = { Variables: { user: { id: string } } };\n * const { user } = getRequestContext<AppEnv>().var; // typed, set by your middleware\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context#var | Hono — c.var}\n * @see {@link https://www.rshono.com/docs/hono#typing-the-context | Docs — typing the context}\n */\n get var(): Readonly<E['Variables']> {\n return this.#raw.var;\n }\n\n /**\n * Environment for the request: process env vars merged with runtime bindings, which win on conflict.\n * Computed once and cached.\n *\n * @example `const key = getRequestContext().env.STRIPE_SECRET_KEY;`\n *\n * @see {@link https://hono.dev/docs/api/context#env | Hono — c.env}\n * @see {@link https://www.rshono.com/docs/configuration#environment-and-secrets | Docs — environment and secrets}\n */\n get env(): EnvVars<E> {\n if (this.#env) return this.#env;\n const bindings = this.#raw.env as Record<string, unknown> | undefined;\n return (this.#env = (bindings ? { ...processEnv(), ...bindings } : processEnv()) as EnvVars<E>);\n }\n\n /**\n * Read and write request/response cookies.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.cookies.get('session'); // string | undefined\n * ctx.cookies.set('session', id, { httpOnly: true, sameSite: 'Lax', path: '/' });\n * ctx.cookies.delete('session', { path: '/' });\n * ```\n *\n * @see {@link https://hono.dev/docs/helpers/cookie | Hono — cookie helper}, which this wraps\n */\n cookies = {\n /** Reads a single cookie by name, or `undefined` if absent. Safe anywhere, a page included. */\n get: (name: string): string | undefined => getCookie(this.#raw, name),\n /** Reads every cookie as a `{ name: value }` record. Safe anywhere, a page included. */\n all: (): Record<string, string> => getCookie(this.#raw),\n /**\n * Sets a cookie on the response. See Hono's {@link CookieOptions} for `path`, `httpOnly`, `maxAge`\n * and the rest.\n *\n * **Throws inside a page render** — a `Set-Cookie` is a special case of\n * {@link RequestContext.setHeader}. Set cookies from a `'use server'` action, or with Hono's\n * `setCookie(c, …)` in middleware and endpoint routes.\n *\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @see {@link https://hono.dev/docs/helpers/cookie#options | Hono — cookie options}\n */\n set: (name: string, value: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.set()');\n setCookie(this.#raw, name, value, options);\n },\n /**\n * Clears a cookie. Pass the same `path`/`domain` it was set with so the browser matches it.\n * Throws inside a page render, exactly as `set` does.\n *\n * @throws If called while a page is rendering.\n */\n delete: (name: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.delete()');\n deleteCookie(this.#raw, name, options);\n },\n };\n\n #assertWritable(call: string): void {\n if (rendering.has(this.#raw as Context)) tooLateToWrite(call);\n }\n\n /**\n * Sets a header on the response — from a `'use server'` action, which is the one place a request\n * context exists *and* the response is still open.\n *\n * From inside a page it throws: a page streams, so its response head is already committed by then,\n * and the write would land on a full page load but vanish on a soft navigation.\n *\n * Middleware and `{ type: 'endpoint' }` routes are handed Hono's `c` directly and use `c.header(…)`.\n * That is also where a header belonging to the *page* goes — `Cache-Control`, `X-Robots-Tag` — since\n * middleware runs before the render.\n *\n * @param name - Header name, case-insensitive.\n * @param value - Header value.\n * @param options - `{ append: true }` to add another value rather than replace.\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @example\n * ```ts\n * 'use server';\n * export async function logout() {\n * const ctx = getRequestContext();\n * ctx.cookies.delete('session', { path: '/' });\n * ctx.setHeader('clear-site-data', '\"cache\", \"storage\"');\n * redirect('/');\n * }\n * ```\n */\n setHeader(name: string, value: string, options?: { append?: boolean }): void {\n this.#assertWritable('ctx.setHeader()');\n this.#raw.header(name, value, options);\n }\n\n // Hono's response builders, restated as errors naming what to use instead — through `ctx.hono` every\n // one of them is a silent no-op from a page. `@deprecated` strikes them through in autocomplete; the\n // unread `..._args` is so `ctx.redirect('/x')` reaches the thrown message rather than an arity error.\n\n /** @deprecated Not available on a page's context — use `redirect()` from `@rshono/core/server`. */\n redirect(..._args: unknown[]): never {\n return notOnContext(\n 'redirect(location, status?)',\n \"Use `redirect()` from '@rshono/core/server', which throws a signal the framework turns into a real redirect.\",\n );\n }\n\n /** @deprecated Not available on a page's context — use `notFound()` from `@rshono/core/server`. */\n notFound(..._args: unknown[]): never {\n return notOnContext('notFound()', \"Use `notFound()` from '@rshono/core/server', which aborts the render and shows the app's not-found page.\");\n }\n\n /** @deprecated A page renders JSX. For a JSON response, use an `{ type: 'endpoint' }` route. */\n json(..._args: unknown[]): never {\n return notOnContext('json(object)', \"For a JSON response use an { type: 'endpoint' } route; to read the request body use `ctx.req.json()`.\");\n }\n\n /** @deprecated A page renders JSX. For a text response, use an `{ type: 'endpoint' }` route. */\n text(..._args: unknown[]): never {\n return notOnContext('text(string)', \"For a text response use an { type: 'endpoint' } route; to read the request body use `ctx.req.text()`.\");\n }\n\n /** @deprecated A page renders JSX, which the framework turns into HTML for you. */\n html(..._args: unknown[]): never {\n return notOnContext('html(string)', \"A page's JSX is already its HTML; for a hand-built HTML response use an { type: 'endpoint' } route.\");\n }\n\n /** @deprecated Not available on a page's context. To read the request body, use `ctx.req`. */\n body(..._args: unknown[]): never {\n return notOnContext(\n 'body(data, …)',\n \"To read the *request* body use `ctx.req.json()` / `ctx.req.text()` / `ctx.req.formData()`; to build a response, use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated A page's status is set by the framework — use `notFound()`, or an endpoint route. */\n status(..._args: unknown[]): never {\n return notOnContext(\n 'status(code)',\n \"A page's status is the framework's: 200, 404 via `notFound()`, 500 when it throws. For any other code use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated Renamed — use `ctx.setHeader(name, value)`, which is valid from a `'use server'` action. */\n header(..._args: unknown[]): never {\n return notOnContext(\n 'header(name, value)',\n \"Use `ctx.setHeader(name, value)` from a 'use server' action, or `c.header(…)` in middleware — a page renders too late to set one.\",\n );\n }\n}\n\n/**\n * The {@link RequestContext} for the current request — URL, cookies, params, env and middleware\n * variables — read from a server component or a server action. Memoised per request, so repeated calls\n * return the same instance.\n *\n * A page is handed that same object as its `ctx` prop, so this import is for everywhere else: a nested\n * server component, or a `'use server'` action module.\n *\n * @typeParam E - The app's Hono {@link Env}, to type {@link RequestContext.var} and {@link RequestContext.env}.\n * @throws If called at module load, where there is no ambient context to resolve.\n * @throws If called while prerendering a `render: 'static'` route, which has no\n * per-request context at build time — mark the route `render: 'dynamic'` instead.\n *\n * @example\n * ```ts\n * 'use server';\n * import { getRequestContext, redirect } from '@rshono/core/server';\n *\n * export async function login(form: FormData) {\n * getRequestContext().cookies.set('session', String(form.get('email')), { httpOnly: true });\n * redirect('/dashboard');\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n */\nexport function getRequestContext<E extends Env = Env>(): RequestContext<E> {\n if (prerendering) {\n throw new Error(\n \"[rshono] getRequestContext() was called while prerendering a `render: 'static'` route. A static page \" +\n 'is rendered once at build time, so it has no per-request context to read (URL, cookies, ' +\n \"headers, env). Change this route to `render: 'dynamic'` so it renders per request, or remove \" +\n 'the getRequestContext() call.',\n );\n }\n const c = contextStorage.getStore();\n if (!c) {\n throw new Error(\n '[rshono] getRequestContext() was called outside a request. It only works inside a server component or a server action, not at module load.',\n );\n }\n let ctx = wrappers.get(c);\n if (!ctx) {\n ctx = new RequestContext(c);\n wrappers.set(c, ctx);\n }\n return ctx as unknown as RequestContext<E>;\n}\n\n/**\n * Redirects the request to `location`, by throwing a control signal the framework turns into an HTTP\n * redirect.\n *\n * Because it throws it never returns, so TypeScript narrows away everything after the call and there\n * is nothing to `return`. Don't wrap it in a `try/catch` that swallows the signal.\n *\n * @param location - Absolute path or URL to redirect to, e.g. `/dashboard`.\n * @param status - Redirect {@link RedirectStatus}; defaults to `303` (See Other), which is what makes\n * the browser follow up with a `GET` after a form action.\n *\n * @example\n * ```ts\n * const session = getRequestContext().cookies.get('session');\n * if (!session) redirect('/login');\n * // session is defined below this line\n * ```\n */\nexport function redirect(location: string, status: RedirectStatus = 303): never {\n throw new RedirectSignal(location, status);\n}\n\n/**\n * Aborts the current render with a 404, rendering the app's `notFound` page.\n *\n * Like {@link redirect} it throws a control signal and never returns, so TypeScript narrows away\n * everything after the call. Don't catch-and-swallow it.\n *\n * @example\n * ```tsx\n * export default async function Page({ params }: PageProps<'/users/:id'>) {\n * const user = await db.user.find(params.id);\n * if (!user) notFound();\n * return <Profile user={user} />; // user is non-null here\n * }\n * ```\n */\nexport function notFound(): never {\n throw new NotFoundSignal();\n}\n\n/**\n * Which stage of a request produced an error handed to a {@link ServerErrorHandler}.\n *\n * - `action` — a `'use server'` function threw. React sends the client an opaque marker with no\n * message in production, so this is the only place the real error is visible.\n * - `render` — a server component threw while the flight payload was being produced.\n * - `ssr` — SSR failed before the HTML shell could be sent, so the `error` page was unreachable too.\n * - `request` — anything else that reached the top-level handler, a thrown endpoint route included.\n */\nexport type ServerErrorSource = 'action' | 'render' | 'ssr' | 'request';\n\n/** What an {@link ServerErrorHandler} is told about an error, beyond the error itself. */\nexport interface ServerErrorContext {\n /** The stage that produced it — see {@link ServerErrorSource}. */\n source: ServerErrorSource;\n /** The request being served, for the URL, method and headers. */\n request: Request;\n}\n\n/** Handler registered with {@link onServerError}. Called for the side effect; its return value is ignored. */\nexport type ServerErrorHandler = (error: unknown, context: ServerErrorContext) => void;\n\nlet errorHandler: ServerErrorHandler | undefined;\n\n/**\n * Errors already forwarded, so one fault is reported once however many stages it crosses.\n *\n * A thrown server action is reported where it is known to be an action and then re-thrown, which lands it in\n * the top-level handler as well — and a funnel that counts the same error twice, under two different\n * `source`s, is worse than one that only ever names the outer stage.\n */\nconst alreadyReported = new WeakSet<object>();\n\n/**\n * Registers a handler for every error the framework catches, so they can reach an error tracker\n * (Sentry, Datadog, a log pipeline) instead of only `stderr`.\n *\n * Call it once, at the top level of `src/server.ts`, which is imported as the server starts.\n * Registering again replaces the previous handler. Errors still go to `stderr` either way, and a\n * handler that throws is caught and logged — reporting can never fail a request.\n *\n * @example\n * ```ts\n * // src/server.ts\n * import * as Sentry from '@sentry/node';\n * import { onServerError } from '@rshono/core/server';\n *\n * onServerError((error, { source, request }) => {\n * Sentry.captureException(error, { tags: { source }, extra: { url: request.url } });\n * });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/hono#error-reporting | Docs — error reporting}\n */\nexport function onServerError(handler: ServerErrorHandler): void {\n errorHandler = handler;\n}\n\n/**\n * Logs an error and forwards it to the registered {@link ServerErrorHandler} — the single funnel every\n * caught server-side error goes through.\n *\n * @internal\n */\nexport function reportServerError(error: unknown, info: ServerErrorContext & { message: string }): void {\n // The first stage to recognise it wins, since that is the one that knows what it was. A primitive throw\n // cannot be tracked and is reported wherever it is caught.\n if (typeof error === 'object' && error !== null) {\n if (alreadyReported.has(error)) return;\n alreadyReported.add(error);\n }\n console.error(info.message, error);\n if (!errorHandler) return;\n try {\n errorHandler(error, { source: info.source, request: info.request });\n } catch (handlerError) {\n console.error('[rshono] the onServerError handler threw:', handlerError);\n }\n}\n"]}
|
|
@@ -35,6 +35,11 @@ function readFlightPayload() {
|
|
|
35
35
|
}
|
|
36
36
|
/** Created at module evaluation, not inside `main()`, so no chunk can be pushed before it is watching. */
|
|
37
37
|
const flightStream = readFlightPayload();
|
|
38
|
+
/**
|
|
39
|
+
* The part of the location a payload is rendered for — the document, without the fragment, which the server
|
|
40
|
+
* never sees. Two URLs that differ only by `#hash` describe the same payload.
|
|
41
|
+
*/
|
|
42
|
+
const documentUrl = () => location.pathname + location.search;
|
|
38
43
|
/** Guarantees somewhere to attach the fatal overlay: the root container is `document`, so a teardown can take `<body>` with it. */
|
|
39
44
|
function overlayHost() {
|
|
40
45
|
if (!document.documentElement)
|
|
@@ -92,8 +97,8 @@ function showFatal(error, componentStack) {
|
|
|
92
97
|
* Asks a URL for its flight payload. Deliberately uncached — a payload can never be staler than the click
|
|
93
98
|
* that wanted it, and the browser's own HTTP cache is what makes a repeat visit cheap.
|
|
94
99
|
*/
|
|
95
|
-
function requestPayload(href) {
|
|
96
|
-
return createFromFetch(fetch(createRscRequest(new URL(href, location.href).href)));
|
|
100
|
+
function requestPayload(href, signal) {
|
|
101
|
+
return createFromFetch(fetch(createRscRequest(new URL(href, location.href).href, undefined, signal)));
|
|
97
102
|
}
|
|
98
103
|
async function main() {
|
|
99
104
|
// The assertion is load-bearing under the compiler that builds this: TypeScript 7 declares `nonce` on
|
|
@@ -161,19 +166,49 @@ async function main() {
|
|
|
161
166
|
}
|
|
162
167
|
return true;
|
|
163
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* The navigation whose payload the screen is allowed to show. React runs async transitions concurrently, so
|
|
171
|
+
* two overlapping navigations are two live fetches with no ordering between them — without this, a slow
|
|
172
|
+
* first response landing after a fast second one renders the page the user already left while the address
|
|
173
|
+
* bar shows the one they asked for.
|
|
174
|
+
*/
|
|
175
|
+
let currentNavigation = 0;
|
|
176
|
+
/** The in-flight navigation's fetch, so a newer one can stop paying for it. */
|
|
177
|
+
let navigationFetch = null;
|
|
178
|
+
/**
|
|
179
|
+
* Fetches the payload for the current URL and applies it, unless a newer navigation started meanwhile.
|
|
180
|
+
*
|
|
181
|
+
* @returns `true` when this navigation is the one that settled the screen, `false` when it was superseded.
|
|
182
|
+
* The distinction is what keeps a stale response from scrolling a page it is no longer rendering — and
|
|
183
|
+
* why being superseded resolves rather than throws: both callers answer a rejection with a full reload,
|
|
184
|
+
* so surfacing the abort would turn every fast second click into one.
|
|
185
|
+
*/
|
|
164
186
|
async function fetchRscPayload() {
|
|
187
|
+
const navigation = ++currentNavigation;
|
|
188
|
+
navigationFetch?.abort();
|
|
189
|
+
const controller = (navigationFetch = new AbortController());
|
|
190
|
+
const superseded = () => navigation !== currentNavigation;
|
|
165
191
|
let payload;
|
|
166
192
|
try {
|
|
167
|
-
payload = await requestPayload(window.location.href);
|
|
193
|
+
payload = await requestPayload(window.location.href, controller.signal);
|
|
168
194
|
}
|
|
169
195
|
catch (error) {
|
|
196
|
+
// Checked before the error is read: an abort is this navigation being replaced, and the one that
|
|
197
|
+
// replaced it owns the outcome.
|
|
198
|
+
if (superseded())
|
|
199
|
+
return false;
|
|
170
200
|
if (handleControlDigest(error))
|
|
171
|
-
return;
|
|
201
|
+
return true;
|
|
172
202
|
throw error;
|
|
173
203
|
}
|
|
174
|
-
if (
|
|
175
|
-
return
|
|
204
|
+
if (superseded())
|
|
205
|
+
return false;
|
|
206
|
+
if (payload.redirect) {
|
|
207
|
+
push(payload.redirect);
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
176
210
|
setPayload(payload);
|
|
211
|
+
return true;
|
|
177
212
|
}
|
|
178
213
|
function BrowserRoot() {
|
|
179
214
|
const [payload, setPayloadState] = React.useState(initialPayload);
|
|
@@ -196,8 +231,10 @@ async function main() {
|
|
|
196
231
|
React.useEffect(() => {
|
|
197
232
|
const stopNavigating = listenNavigation((afterRender) => startNav(async () => {
|
|
198
233
|
try {
|
|
199
|
-
|
|
200
|
-
|
|
234
|
+
// Only the navigation that settled the screen owes a scroll — a superseded one would move the
|
|
235
|
+
// page the navigation that replaced it is about to render.
|
|
236
|
+
if (await fetchRscPayload())
|
|
237
|
+
pendingScroll.current = afterRender;
|
|
201
238
|
}
|
|
202
239
|
catch {
|
|
203
240
|
window.location.reload();
|
|
@@ -214,6 +251,11 @@ async function main() {
|
|
|
214
251
|
}
|
|
215
252
|
setServerCallback(async (id, args) => {
|
|
216
253
|
const temporaryReferences = createTemporaryReferenceSet();
|
|
254
|
+
// The document the action is being called from. Every action response carries a fresh payload for that
|
|
255
|
+
// page, so if a navigation has moved on by the time it arrives the payload describes a page the user has
|
|
256
|
+
// left — the return value is still theirs, but painting it is not. Compared without the fragment, which
|
|
257
|
+
// the server never saw.
|
|
258
|
+
const calledFrom = documentUrl();
|
|
217
259
|
const request = createRscRequest(window.location.href, {
|
|
218
260
|
id,
|
|
219
261
|
body: await encodeReply(args, { temporaryReferences }),
|
|
@@ -231,7 +273,8 @@ async function main() {
|
|
|
231
273
|
push(payload.redirect);
|
|
232
274
|
return undefined;
|
|
233
275
|
}
|
|
234
|
-
|
|
276
|
+
if (documentUrl() === calledFrom)
|
|
277
|
+
React.startTransition(() => setPayload(payload));
|
|
235
278
|
if (payload.notFound)
|
|
236
279
|
return undefined;
|
|
237
280
|
const result = payload.returnValue;
|
|
@@ -357,8 +400,7 @@ function listenNavigation(onNavigation) {
|
|
|
357
400
|
else
|
|
358
401
|
window.scrollTo(0, 0);
|
|
359
402
|
};
|
|
360
|
-
|
|
361
|
-
// What the payload on screen was rendered for. The document part only: the server never sees the fragment.
|
|
403
|
+
// What the payload on screen was rendered for. See {@link documentUrl}.
|
|
362
404
|
let renderedUrl = documentUrl();
|
|
363
405
|
/**
|
|
364
406
|
* A navigation that moves only the fragment leaves the document unchanged, so the payload on screen is
|
|
@@ -408,6 +450,8 @@ function listenNavigation(onNavigation) {
|
|
|
408
450
|
* rsc-update → server component code changed: re-fetch the flight payload, state preserved.
|
|
409
451
|
* hello → sent on (re)connect with the latest build hash; a mismatch means a missed event.
|
|
410
452
|
*/
|
|
453
|
+
// `Promise<unknown>`: the payload fetch reports whether its navigation was superseded, which matters to a
|
|
454
|
+
// click and not to a rebuild — here only settling or rejecting does.
|
|
411
455
|
function initDevRefresh(fetchRscPayload) {
|
|
412
456
|
const hot = import.meta.webpackHot;
|
|
413
457
|
let connectedOnce = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.client.js","sourceRoot":"","sources":["../../src/runtime/entry.client.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,2BAA2B,EAC3B,WAAW,EACX,iBAAiB,GAClB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGpE,sGAAsG;AACtG,6CAA6C;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAyB,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,CAAC;AAOrD,0GAA0G;AAC1G,SAAS,iBAAiB;IACxB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,wFAAwF;IACxF,IAAI,UAAwD,CAAC;IAC7D,MAAM,MAAM,GAAG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} from 'react-dom/client';\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from 'react-server-dom-rspack/client.browser';\nimport { isControlDigest, parseRedirectDigest } from './control.js';\nimport type { DevMessage } from './dev-protocol.js';\nimport type { RscPayload } from './entry.rsc.js';\n// Dev-only: its one caller sits behind `import.meta.webpackHot`, which a production build compiles to\n// `false` — so this module is dropped there.\nimport { walkHotUpdates } from './hot-update.js';\nimport { RouterContext, type NavigationRouter } from './navigation.js';\nimport { createRscRequest } from './request.js';\n\nconst isDev = process.env.NODE_ENV === 'development';\n\ndeclare global {\n /** The array the payload `<script>` tags `flight-inject.ts` emits push their chunks into. */\n var __FLIGHT_DATA: Array<string | Uint8Array> | undefined;\n}\n\n/** The flight payload the document carried, read back out of `__FLIGHT_DATA` — see `flight-inject.ts`. */\nfunction readFlightPayload(): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n // Assigned synchronously by `start`, which `new ReadableStream` runs before it returns.\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start: (c) => void (controller = c),\n });\n const enqueue = (chunk: string | Uint8Array) => controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n\n // Payload scripts interleave with the document: the ones that already ran are in the array, the rest\n // arrive through `push`.\n const data = (self.__FLIGHT_DATA ??= []);\n for (const chunk of data) enqueue(chunk);\n data.push = enqueue as typeof data.push;\n\n // The last payload script lands before parsing finishes, so that is what closes the stream.\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => controller.close(), { once: true });\n } else {\n controller.close();\n }\n return stream;\n}\n\n/** Created at module evaluation, not inside `main()`, so no chunk can be pushed before it is watching. */\nconst flightStream = readFlightPayload();\n\n/** Guarantees somewhere to attach the fatal overlay: the root container is `document`, so a teardown can take `<body>` with it. */\nfunction overlayHost(): HTMLElement {\n if (!document.documentElement) document.appendChild(document.createElement('html'));\n if (!document.body) document.documentElement.appendChild(document.createElement('body'));\n return document.body;\n}\n\n/**\n * Paints the reason for an uncaught render error over the blank page it leaves behind — the full stack in\n * dev, a generic notice and a reload button in production.\n *\n * DOM calls rather than React (the renderer is what just failed), and `textContent` rather than\n * `innerHTML` (an error message is untrusted input).\n */\nfunction showFatal(error: unknown, componentStack?: string | null): void {\n // Queued: React's teardown runs after this callback returns and would remove a node appended inline.\n setTimeout(() => {\n const host = overlayHost();\n host.querySelector('[data-rshono-fatal]')?.remove();\n\n const box = document.createElement('div');\n box.setAttribute('data-rshono-fatal', '');\n box.setAttribute('role', 'alert');\n box.style.cssText =\n 'position:fixed;inset:0;z-index:2147483647;overflow:auto;padding:1.5rem;background:#18181b;color:#f4f4f5;' +\n 'font:14px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:left';\n\n const title = document.createElement('div');\n title.textContent = isDev ? 'Unhandled error' : 'Something went wrong';\n title.style.cssText = 'font-size:1.0625rem;font-weight:700;color:#f87171;margin:0 0 0.75rem';\n box.appendChild(title);\n\n if (isDev) {\n const detail = document.createElement('pre');\n detail.style.cssText = 'margin:0;white-space:pre-wrap;word-break:break-word';\n detail.textContent =\n (error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error)) +\n (componentStack ? `\\n\\nComponent stack:${componentStack}` : '');\n box.appendChild(detail);\n } else {\n const message = document.createElement('p');\n message.textContent = 'This page hit an unexpected error and can’t continue.';\n message.style.cssText = 'margin:0 0 1rem;color:#d4d4d8';\n box.appendChild(message);\n }\n\n const reload = document.createElement('button');\n reload.textContent = 'Reload page';\n reload.style.cssText =\n 'margin-top:1.25rem;padding:0.5rem 1rem;font:inherit;color:#18181b;background:#f4f4f5;border:0;border-radius:4px;cursor:pointer';\n reload.addEventListener('click', () => window.location.reload());\n box.appendChild(reload);\n\n host.appendChild(box);\n }, 0);\n}\n\n/**\n * Asks a URL for its flight payload. Deliberately uncached — a payload can never be staler than the click\n * that wanted it, and the browser's own HTTP cache is what makes a repeat visit cheap.\n */\nfunction requestPayload(href: string): Promise<RscPayload> {\n return createFromFetch<RscPayload>(fetch(createRscRequest(new URL(href, location.href).href)));\n}\n\nasync function main() {\n // The assertion is load-bearing under the compiler that builds this: TypeScript 7 declares `nonce` on\n // HTMLElement, 6 declares it on Element. ESLint runs the older lib — where the narrowing is redundant —\n // so it reports an assertion that `tsc` requires. Believe `typecheck`, not the rule.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const cspMeta = document.querySelector('meta[property=\"csp-nonce\"]') as HTMLMetaElement | null;\n if (cspMeta?.nonce) __webpack_nonce__ = cspMeta.nonce;\n\n // Both are replaced by BrowserRoot's own on mount. The defaults cover the window before hydration, where\n // `setServerCallback` is already registered but there is no root to update — a reload is the honest answer.\n let setPayload: (v: RscPayload) => void = () => {\n window.location.reload();\n };\n // Runs work inside the nav transition so useNavigation().pending stays true across the round-trip.\n let startNav: (run: () => void | Promise<void>) => void = (run) => {\n void run();\n };\n\n const initialPayload = await createFromReadableStream<RscPayload>(flightStream);\n\n function push(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.assign(target.href);\n return;\n }\n window.history.pushState(null, '', target.href);\n }\n\n function replace(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.replace(target.href);\n return;\n }\n window.history.replaceState(null, '', target.href);\n }\n\n // A refresh keeps the URL, so it can't ride the history patch like push/replace and drives the re-fetch itself.\n const refresh = () =>\n startNav(async () => {\n try {\n await fetchRscPayload();\n } catch {\n window.location.reload();\n }\n });\n\n /**\n * Turns a control-signal digest — how `redirect()` / `notFound()` reach the browser — into a real\n * navigation. Returns false for anything else, so callers fall through to their own handling.\n *\n * `hard` forces a full document load, for signals that surfaced *through React*: it unmounts the root on\n * an uncaught error, leaving no live tree to soft-navigate with.\n */\n function handleControlDigest(error: unknown, { hard = false }: { hard?: boolean } = {}): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n if (!isControlDigest(digest)) return false;\n const redirect = parseRedirectDigest(digest);\n if (!redirect) {\n window.location.reload();\n } else if (hard) {\n window.location.assign(new URL(redirect.location, window.location.href).href);\n } else {\n push(redirect.location);\n }\n return true;\n }\n\n async function fetchRscPayload() {\n let payload: RscPayload;\n try {\n payload = await requestPayload(window.location.href);\n } catch (error) {\n if (handleControlDigest(error)) return;\n throw error;\n }\n if (payload.redirect) return push(payload.redirect);\n setPayload(payload);\n }\n\n function BrowserRoot() {\n const [payload, setPayloadState] = React.useState(initialPayload);\n const [pending, startTransition] = React.useTransition();\n // The scroll a fetched navigation still owes, held until its payload is on screen.\n const pendingScroll = React.useRef<(() => void) | null>(null);\n\n React.useEffect(() => {\n setPayload = (v) => setPayloadState(v);\n startNav = (run) => startTransition(run);\n }, [startTransition]);\n\n /**\n * Scrolls where the navigation asked, once React has put its payload in the DOM — a `#hash` target does\n * not exist until the new tree does. A layout effect, so the pre-scroll position is never painted.\n */\n React.useLayoutEffect(() => {\n const scroll = pendingScroll.current;\n pendingScroll.current = null;\n scroll?.();\n }, [payload]);\n\n React.useEffect(() => {\n const stopNavigating = listenNavigation((afterRender) =>\n startNav(async () => {\n try {\n await fetchRscPayload();\n pendingScroll.current = afterRender;\n } catch {\n window.location.reload();\n }\n }),\n );\n const stopUpgradingLinks = listenLinks();\n return () => {\n stopUpgradingLinks();\n stopNavigating();\n };\n }, []);\n\n const router = React.useMemo<NavigationRouter>(() => ({ push, replace, refresh, pending }), [pending]);\n\n return <RouterContext.Provider value={router}>{payload.root}</RouterContext.Provider>;\n }\n\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n const request = createRscRequest(window.location.href, {\n id,\n body: await encodeReply(args, { temporaryReferences }),\n });\n let payload: RscPayload;\n try {\n payload = await createFromFetch<RscPayload>(fetch(request), { temporaryReferences });\n } catch (error) {\n if (handleControlDigest(error)) return undefined;\n throw error;\n }\n if (payload.redirect) {\n push(payload.redirect);\n return undefined;\n }\n React.startTransition(() => setPayload(payload));\n if (payload.notFound) return undefined;\n const result = payload.returnValue!;\n if (!result.ok) throw result.error;\n return result.value;\n });\n\n // A `redirect()` / `notFound()` from a component below the page root reaches us through React: it rides the\n // flight payload as an error, and boundaries re-throw it so it lands here rather than in a fallback.\n //\n // Installing these hooks opts out of React's own defaults, so everything that isn't a control signal has to\n // be put back by hand — `reportError` rather than a bare log, so error-reporting tools still see it.\n hydrateRoot(document, <BrowserRoot />, {\n formState: initialPayload.formState,\n onCaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // A boundary handled it and the tree is intact, so no overlay over the app's own fallback.\n console.error(error, errorInfo.componentStack ?? '');\n },\n onUncaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // Nothing caught it, so React tears the root down — and the root is `document`.\n globalThis.reportError(error);\n showFatal(error, errorInfo.componentStack);\n },\n });\n\n if (import.meta.webpackHot) {\n initDevRefresh(fetchRscPayload);\n }\n}\n\ntype NavigationType = 'push' | 'replace' | 'pop';\n\n/** Runs teardown in reverse and empties the list, so a second call is a no-op. */\nfunction disposeAll(undo: Array<() => void>): void {\n for (const dispose of undo.splice(0).reverse()) dispose();\n}\n\n// An `<a>` we intercept for soft navigation: same-origin, same tab, not a download,\n// and not explicitly opted out with `data-native` (which forces a full browser navigation).\nfunction isRouterLink(link: HTMLAnchorElement): boolean {\n return (\n !!link.href &&\n (!link.target || link.target === '_self') &&\n link.origin === location.origin &&\n !link.hasAttribute('download') &&\n !link.hasAttribute('data-native')\n );\n}\n\n/**\n * Upgrades the app's anchors: a plain left-click becomes a soft navigation. It shares no state with\n * `listenNavigation` — a click only calls `history.pushState`, which is where that picks the navigation up.\n */\nfunction listenLinks(): () => void {\n const undo: Array<() => void> = [];\n\n function onClick(e: MouseEvent) {\n const link = (e.target as Element).closest('a');\n if (\n link &&\n link instanceof HTMLAnchorElement &&\n isRouterLink(link) &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n if (link.hash && link.pathname === location.pathname && link.search === location.search) return;\n e.preventDefault();\n history.pushState(null, '', link.href);\n }\n }\n document.addEventListener('click', onClick);\n undo.push(() => document.removeEventListener('click', onClick));\n\n return () => disposeAll(undo);\n}\n\n/**\n * The element the current `#fragment` names, if it is on the page. A fragment is percent-encoded and an `id`\n * is not, so it is decoded first — and taken literally when a hand-written `%` makes that throw.\n */\nfunction fragmentTarget(): HTMLElement | null {\n const fragment = location.hash.slice(1);\n if (!fragment) return null;\n let id = fragment;\n try {\n id = decodeURIComponent(fragment);\n } catch {\n // Malformed escape — the literal fragment is the better guess at the id than nothing.\n }\n return document.getElementById(id);\n}\n\nfunction listenNavigation(onNavigation: (afterRender: () => void) => void): () => void {\n const undo: Array<() => void> = [];\n\n // Set explicitly as a statement of intent: the browser remembers a traversal's offset, and nothing here\n // tracks one.\n const prevRestoration = window.history.scrollRestoration;\n try {\n window.history.scrollRestoration = 'auto';\n } catch {\n // Not settable in every browser, and only a preference — the navigation still works without it.\n }\n undo.push(() => {\n try {\n window.history.scrollRestoration = prevRestoration;\n } catch {\n // As above: if it could not be set, it cannot be put back either.\n }\n });\n\n /**\n * A push is not a real navigation to the browser, so nothing resets the scroll offset. A `#hash` names\n * where to land instead; `replace` keeps its position, and a traversal is the browser's to restore.\n *\n * `scrollIntoView` is the algorithm a browser's own fragment jump uses, so `scroll-padding-top` still\n * applies. Neither call passes a `behavior`, leaving `scroll-behavior: smooth` the app's to ask for.\n */\n const afterRenderFor = (type: NavigationType) => () => {\n if (type !== 'push') return;\n const target = fragmentTarget();\n if (target) target.scrollIntoView();\n else window.scrollTo(0, 0);\n };\n\n const documentUrl = () => location.pathname + location.search;\n\n // What the payload on screen was rendered for. The document part only: the server never sees the fragment.\n let renderedUrl = documentUrl();\n\n /**\n * A navigation that moves only the fragment leaves the document unchanged, so the payload on screen is\n * already the right one — fetching another would re-render the page out from under the jump.\n * `router.refresh()` is unaffected, and remains the way to ask for fresh data at an unchanged URL.\n */\n const notify = (type: NavigationType) => {\n const afterRender = afterRenderFor(type);\n if (documentUrl() === renderedUrl) {\n afterRender();\n return;\n }\n renderedUrl = documentUrl();\n onNavigation(afterRender);\n };\n\n const onPopState = () => notify('pop');\n window.addEventListener('popstate', onPopState);\n undo.push(() => window.removeEventListener('popstate', onPopState));\n\n // Saved unbound on purpose, and called back with `.call(this, …)` below — patching `history` is the only\n // way to see a navigation the app makes itself, and the receiver is restored at every call site.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldPushState = window.history.pushState;\n window.history.pushState = function (state, unused, url) {\n const res = oldPushState.call(this, state, unused, url as string);\n notify('push');\n return res;\n };\n undo.push(() => {\n window.history.pushState = oldPushState;\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method -- as with `pushState` above.\n const oldReplaceState = window.history.replaceState;\n window.history.replaceState = function (state, unused, url) {\n const res = oldReplaceState.call(this, state, unused, url as string);\n notify('replace');\n return res;\n };\n undo.push(() => {\n window.history.replaceState = oldReplaceState;\n });\n\n return () => disposeAll(undo);\n}\n\n/**\n * Dev-only refresh client, listening to the CLI's SSE endpoint:\n *\n * client-built → hot-apply the waiting updates; anything the page can't be patched up to reloads.\n * rsc-update → server component code changed: re-fetch the flight payload, state preserved.\n * hello → sent on (re)connect with the latest build hash; a mismatch means a missed event.\n */\nfunction initDevRefresh(fetchRscPayload: () => Promise<void>) {\n const hot = import.meta.webpackHot!;\n let connectedOnce = false;\n /** The newest build the dev server has announced — what {@link applyClientUpdate} walks towards. */\n let targetHash: string | undefined;\n\n function reload(reason: string, error?: unknown): void {\n console.warn(`[rshono] ${reason} — reloading`, ...(error === undefined ? [] : [error]));\n window.location.reload();\n }\n\n async function applyClientUpdate(): Promise<void> {\n const giveUp = await walkHotUpdates(\n hot,\n () => __webpack_hash__,\n () => targetHash,\n );\n if (giveUp) reload(giveUp.reason, giveUp.error);\n }\n\n async function handle(message: DevMessage): Promise<void> {\n switch (message.type) {\n case 'hello':\n targetHash = message.hash ?? targetHash;\n if (connectedOnce) {\n await applyClientUpdate();\n await fetchRscPayload().catch(() => window.location.reload());\n }\n connectedOnce = true;\n break;\n case 'client-built':\n targetHash = message.hash;\n await applyClientUpdate();\n break;\n case 'rsc-update':\n console.log('[rshono] server components updated');\n await fetchRscPayload().catch(() => window.location.reload());\n break;\n }\n }\n\n const source = new EventSource('/_rshono/hmr');\n // Chained rather than handled as they arrive: `hot.check` may only run from `idle`, and a burst of saves\n // puts several frames on the wire inside the time one takes. Queueing drops nothing, because `targetHash`\n // is shared — whichever handler runs next walks to the newest build.\n let queue: Promise<void> = Promise.resolve();\n source.onmessage = (event: MessageEvent<string>) => {\n const message = JSON.parse(event.data) as DevMessage;\n queue = queue.then(() => handle(message)).catch((error) => reload('the dev client failed', error));\n };\n}\n\n// A bootstrap failure — a truncated initial payload, most likely — would otherwise be an unhandled\n// rejection: nothing hydrates, nothing is reported, and the page just sits there.\nmain().catch((error) => {\n console.error('[rshono] the client runtime failed to start:', error);\n showFatal(error);\n});\n"]}
|
|
1
|
+
{"version":3,"file":"entry.client.js","sourceRoot":"","sources":["../../src/runtime/entry.client.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,2BAA2B,EAC3B,WAAW,EACX,iBAAiB,GAClB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGpE,sGAAsG;AACtG,6CAA6C;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAyB,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,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CAAC;gBAC1B,MAAM;YACR,KAAK,YAAY;gBACf,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;gBAClD,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBAC9D,MAAM;QACV,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC;IAC/C,yGAAyG;IACzG,0GAA0G;IAC1G,qEAAqE;IACrE,IAAI,KAAK,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7C,MAAM,CAAC,SAAS,GAAG,CAAC,KAA2B,EAAE,EAAE;QACjD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAe,CAAC;QACrD,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC,CAAC;IACrG,CAAC,CAAC;AACJ,CAAC;AAED,mGAAmG;AACnG,kFAAkF;AAClF,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACrE,SAAS,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from 'react-server-dom-rspack/client.browser';\nimport { isControlDigest, parseRedirectDigest } from './control.js';\nimport type { DevMessage } from './dev-protocol.js';\nimport type { RscPayload } from './entry.rsc.js';\n// Dev-only: its one caller sits behind `import.meta.webpackHot`, which a production build compiles to\n// `false` — so this module is dropped there.\nimport { walkHotUpdates } from './hot-update.js';\nimport { RouterContext, type NavigationRouter } from './navigation.js';\nimport { createRscRequest } from './request.js';\n\nconst isDev = process.env.NODE_ENV === 'development';\n\ndeclare global {\n /** The array the payload `<script>` tags `flight-inject.ts` emits push their chunks into. */\n var __FLIGHT_DATA: Array<string | Uint8Array> | undefined;\n}\n\n/** The flight payload the document carried, read back out of `__FLIGHT_DATA` — see `flight-inject.ts`. */\nfunction readFlightPayload(): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n // Assigned synchronously by `start`, which `new ReadableStream` runs before it returns.\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start: (c) => void (controller = c),\n });\n const enqueue = (chunk: string | Uint8Array) => controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n\n // Payload scripts interleave with the document: the ones that already ran are in the array, the rest\n // arrive through `push`.\n const data = (self.__FLIGHT_DATA ??= []);\n for (const chunk of data) enqueue(chunk);\n data.push = enqueue as typeof data.push;\n\n // The last payload script lands before parsing finishes, so that is what closes the stream.\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => controller.close(), { once: true });\n } else {\n controller.close();\n }\n return stream;\n}\n\n/** Created at module evaluation, not inside `main()`, so no chunk can be pushed before it is watching. */\nconst flightStream = readFlightPayload();\n\n/**\n * The part of the location a payload is rendered for — the document, without the fragment, which the server\n * never sees. Two URLs that differ only by `#hash` describe the same payload.\n */\nconst documentUrl = (): string => location.pathname + location.search;\n\n/** Guarantees somewhere to attach the fatal overlay: the root container is `document`, so a teardown can take `<body>` with it. */\nfunction overlayHost(): HTMLElement {\n if (!document.documentElement) document.appendChild(document.createElement('html'));\n if (!document.body) document.documentElement.appendChild(document.createElement('body'));\n return document.body;\n}\n\n/**\n * Paints the reason for an uncaught render error over the blank page it leaves behind — the full stack in\n * dev, a generic notice and a reload button in production.\n *\n * DOM calls rather than React (the renderer is what just failed), and `textContent` rather than\n * `innerHTML` (an error message is untrusted input).\n */\nfunction showFatal(error: unknown, componentStack?: string | null): void {\n // Queued: React's teardown runs after this callback returns and would remove a node appended inline.\n setTimeout(() => {\n const host = overlayHost();\n host.querySelector('[data-rshono-fatal]')?.remove();\n\n const box = document.createElement('div');\n box.setAttribute('data-rshono-fatal', '');\n box.setAttribute('role', 'alert');\n box.style.cssText =\n 'position:fixed;inset:0;z-index:2147483647;overflow:auto;padding:1.5rem;background:#18181b;color:#f4f4f5;' +\n 'font:14px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:left';\n\n const title = document.createElement('div');\n title.textContent = isDev ? 'Unhandled error' : 'Something went wrong';\n title.style.cssText = 'font-size:1.0625rem;font-weight:700;color:#f87171;margin:0 0 0.75rem';\n box.appendChild(title);\n\n if (isDev) {\n const detail = document.createElement('pre');\n detail.style.cssText = 'margin:0;white-space:pre-wrap;word-break:break-word';\n detail.textContent =\n (error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error)) +\n (componentStack ? `\\n\\nComponent stack:${componentStack}` : '');\n box.appendChild(detail);\n } else {\n const message = document.createElement('p');\n message.textContent = 'This page hit an unexpected error and can’t continue.';\n message.style.cssText = 'margin:0 0 1rem;color:#d4d4d8';\n box.appendChild(message);\n }\n\n const reload = document.createElement('button');\n reload.textContent = 'Reload page';\n reload.style.cssText =\n 'margin-top:1.25rem;padding:0.5rem 1rem;font:inherit;color:#18181b;background:#f4f4f5;border:0;border-radius:4px;cursor:pointer';\n reload.addEventListener('click', () => window.location.reload());\n box.appendChild(reload);\n\n host.appendChild(box);\n }, 0);\n}\n\n/**\n * Asks a URL for its flight payload. Deliberately uncached — a payload can never be staler than the click\n * that wanted it, and the browser's own HTTP cache is what makes a repeat visit cheap.\n */\nfunction requestPayload(href: string, signal: AbortSignal): Promise<RscPayload> {\n return createFromFetch<RscPayload>(fetch(createRscRequest(new URL(href, location.href).href, undefined, signal)));\n}\n\nasync function main() {\n // The assertion is load-bearing under the compiler that builds this: TypeScript 7 declares `nonce` on\n // HTMLElement, 6 declares it on Element. ESLint runs the older lib — where the narrowing is redundant —\n // so it reports an assertion that `tsc` requires. Believe `typecheck`, not the rule.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const cspMeta = document.querySelector('meta[property=\"csp-nonce\"]') as HTMLMetaElement | null;\n if (cspMeta?.nonce) __webpack_nonce__ = cspMeta.nonce;\n\n // Both are replaced by BrowserRoot's own on mount. The defaults cover the window before hydration, where\n // `setServerCallback` is already registered but there is no root to update — a reload is the honest answer.\n let setPayload: (v: RscPayload) => void = () => {\n window.location.reload();\n };\n // Runs work inside the nav transition so useNavigation().pending stays true across the round-trip.\n let startNav: (run: () => void | Promise<void>) => void = (run) => {\n void run();\n };\n\n const initialPayload = await createFromReadableStream<RscPayload>(flightStream);\n\n function push(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.assign(target.href);\n return;\n }\n window.history.pushState(null, '', target.href);\n }\n\n function replace(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.replace(target.href);\n return;\n }\n window.history.replaceState(null, '', target.href);\n }\n\n // A refresh keeps the URL, so it can't ride the history patch like push/replace and drives the re-fetch itself.\n const refresh = () =>\n startNav(async () => {\n try {\n await fetchRscPayload();\n } catch {\n window.location.reload();\n }\n });\n\n /**\n * Turns a control-signal digest — how `redirect()` / `notFound()` reach the browser — into a real\n * navigation. Returns false for anything else, so callers fall through to their own handling.\n *\n * `hard` forces a full document load, for signals that surfaced *through React*: it unmounts the root on\n * an uncaught error, leaving no live tree to soft-navigate with.\n */\n function handleControlDigest(error: unknown, { hard = false }: { hard?: boolean } = {}): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n if (!isControlDigest(digest)) return false;\n const redirect = parseRedirectDigest(digest);\n if (!redirect) {\n window.location.reload();\n } else if (hard) {\n window.location.assign(new URL(redirect.location, window.location.href).href);\n } else {\n push(redirect.location);\n }\n return true;\n }\n\n /**\n * The navigation whose payload the screen is allowed to show. React runs async transitions concurrently, so\n * two overlapping navigations are two live fetches with no ordering between them — without this, a slow\n * first response landing after a fast second one renders the page the user already left while the address\n * bar shows the one they asked for.\n */\n let currentNavigation = 0;\n /** The in-flight navigation's fetch, so a newer one can stop paying for it. */\n let navigationFetch: AbortController | null = null;\n\n /**\n * Fetches the payload for the current URL and applies it, unless a newer navigation started meanwhile.\n *\n * @returns `true` when this navigation is the one that settled the screen, `false` when it was superseded.\n * The distinction is what keeps a stale response from scrolling a page it is no longer rendering — and\n * why being superseded resolves rather than throws: both callers answer a rejection with a full reload,\n * so surfacing the abort would turn every fast second click into one.\n */\n async function fetchRscPayload(): Promise<boolean> {\n const navigation = ++currentNavigation;\n navigationFetch?.abort();\n const controller = (navigationFetch = new AbortController());\n const superseded = () => navigation !== currentNavigation;\n\n let payload: RscPayload;\n try {\n payload = await requestPayload(window.location.href, controller.signal);\n } catch (error) {\n // Checked before the error is read: an abort is this navigation being replaced, and the one that\n // replaced it owns the outcome.\n if (superseded()) return false;\n if (handleControlDigest(error)) return true;\n throw error;\n }\n if (superseded()) return false;\n if (payload.redirect) {\n push(payload.redirect);\n return true;\n }\n setPayload(payload);\n return true;\n }\n\n function BrowserRoot() {\n const [payload, setPayloadState] = React.useState(initialPayload);\n const [pending, startTransition] = React.useTransition();\n // The scroll a fetched navigation still owes, held until its payload is on screen.\n const pendingScroll = React.useRef<(() => void) | null>(null);\n\n React.useEffect(() => {\n setPayload = (v) => setPayloadState(v);\n startNav = (run) => startTransition(run);\n }, [startTransition]);\n\n /**\n * Scrolls where the navigation asked, once React has put its payload in the DOM — a `#hash` target does\n * not exist until the new tree does. A layout effect, so the pre-scroll position is never painted.\n */\n React.useLayoutEffect(() => {\n const scroll = pendingScroll.current;\n pendingScroll.current = null;\n scroll?.();\n }, [payload]);\n\n React.useEffect(() => {\n const stopNavigating = listenNavigation((afterRender) =>\n startNav(async () => {\n try {\n // Only the navigation that settled the screen owes a scroll — a superseded one would move the\n // page the navigation that replaced it is about to render.\n if (await fetchRscPayload()) pendingScroll.current = afterRender;\n } catch {\n window.location.reload();\n }\n }),\n );\n const stopUpgradingLinks = listenLinks();\n return () => {\n stopUpgradingLinks();\n stopNavigating();\n };\n }, []);\n\n const router = React.useMemo<NavigationRouter>(() => ({ push, replace, refresh, pending }), [pending]);\n\n return <RouterContext.Provider value={router}>{payload.root}</RouterContext.Provider>;\n }\n\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n // The document the action is being called from. Every action response carries a fresh payload for that\n // page, so if a navigation has moved on by the time it arrives the payload describes a page the user has\n // left — the return value is still theirs, but painting it is not. Compared without the fragment, which\n // the server never saw.\n const calledFrom = documentUrl();\n const request = createRscRequest(window.location.href, {\n id,\n body: await encodeReply(args, { temporaryReferences }),\n });\n let payload: RscPayload;\n try {\n payload = await createFromFetch<RscPayload>(fetch(request), { temporaryReferences });\n } catch (error) {\n if (handleControlDigest(error)) return undefined;\n throw error;\n }\n if (payload.redirect) {\n push(payload.redirect);\n return undefined;\n }\n if (documentUrl() === calledFrom) React.startTransition(() => setPayload(payload));\n if (payload.notFound) return undefined;\n const result = payload.returnValue!;\n if (!result.ok) throw result.error;\n return result.value;\n });\n\n // A `redirect()` / `notFound()` from a component below the page root reaches us through React: it rides the\n // flight payload as an error, and boundaries re-throw it so it lands here rather than in a fallback.\n //\n // Installing these hooks opts out of React's own defaults, so everything that isn't a control signal has to\n // be put back by hand — `reportError` rather than a bare log, so error-reporting tools still see it.\n hydrateRoot(document, <BrowserRoot />, {\n formState: initialPayload.formState,\n onCaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // A boundary handled it and the tree is intact, so no overlay over the app's own fallback.\n console.error(error, errorInfo.componentStack ?? '');\n },\n onUncaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // Nothing caught it, so React tears the root down — and the root is `document`.\n globalThis.reportError(error);\n showFatal(error, errorInfo.componentStack);\n },\n });\n\n if (import.meta.webpackHot) {\n initDevRefresh(fetchRscPayload);\n }\n}\n\ntype NavigationType = 'push' | 'replace' | 'pop';\n\n/** Runs teardown in reverse and empties the list, so a second call is a no-op. */\nfunction disposeAll(undo: Array<() => void>): void {\n for (const dispose of undo.splice(0).reverse()) dispose();\n}\n\n// An `<a>` we intercept for soft navigation: same-origin, same tab, not a download,\n// and not explicitly opted out with `data-native` (which forces a full browser navigation).\nfunction isRouterLink(link: HTMLAnchorElement): boolean {\n return (\n !!link.href &&\n (!link.target || link.target === '_self') &&\n link.origin === location.origin &&\n !link.hasAttribute('download') &&\n !link.hasAttribute('data-native')\n );\n}\n\n/**\n * Upgrades the app's anchors: a plain left-click becomes a soft navigation. It shares no state with\n * `listenNavigation` — a click only calls `history.pushState`, which is where that picks the navigation up.\n */\nfunction listenLinks(): () => void {\n const undo: Array<() => void> = [];\n\n function onClick(e: MouseEvent) {\n const link = (e.target as Element).closest('a');\n if (\n link &&\n link instanceof HTMLAnchorElement &&\n isRouterLink(link) &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n if (link.hash && link.pathname === location.pathname && link.search === location.search) return;\n e.preventDefault();\n history.pushState(null, '', link.href);\n }\n }\n document.addEventListener('click', onClick);\n undo.push(() => document.removeEventListener('click', onClick));\n\n return () => disposeAll(undo);\n}\n\n/**\n * The element the current `#fragment` names, if it is on the page. A fragment is percent-encoded and an `id`\n * is not, so it is decoded first — and taken literally when a hand-written `%` makes that throw.\n */\nfunction fragmentTarget(): HTMLElement | null {\n const fragment = location.hash.slice(1);\n if (!fragment) return null;\n let id = fragment;\n try {\n id = decodeURIComponent(fragment);\n } catch {\n // Malformed escape — the literal fragment is the better guess at the id than nothing.\n }\n return document.getElementById(id);\n}\n\nfunction listenNavigation(onNavigation: (afterRender: () => void) => void): () => void {\n const undo: Array<() => void> = [];\n\n // Set explicitly as a statement of intent: the browser remembers a traversal's offset, and nothing here\n // tracks one.\n const prevRestoration = window.history.scrollRestoration;\n try {\n window.history.scrollRestoration = 'auto';\n } catch {\n // Not settable in every browser, and only a preference — the navigation still works without it.\n }\n undo.push(() => {\n try {\n window.history.scrollRestoration = prevRestoration;\n } catch {\n // As above: if it could not be set, it cannot be put back either.\n }\n });\n\n /**\n * A push is not a real navigation to the browser, so nothing resets the scroll offset. A `#hash` names\n * where to land instead; `replace` keeps its position, and a traversal is the browser's to restore.\n *\n * `scrollIntoView` is the algorithm a browser's own fragment jump uses, so `scroll-padding-top` still\n * applies. Neither call passes a `behavior`, leaving `scroll-behavior: smooth` the app's to ask for.\n */\n const afterRenderFor = (type: NavigationType) => () => {\n if (type !== 'push') return;\n const target = fragmentTarget();\n if (target) target.scrollIntoView();\n else window.scrollTo(0, 0);\n };\n\n // What the payload on screen was rendered for. See {@link documentUrl}.\n let renderedUrl = documentUrl();\n\n /**\n * A navigation that moves only the fragment leaves the document unchanged, so the payload on screen is\n * already the right one — fetching another would re-render the page out from under the jump.\n * `router.refresh()` is unaffected, and remains the way to ask for fresh data at an unchanged URL.\n */\n const notify = (type: NavigationType) => {\n const afterRender = afterRenderFor(type);\n if (documentUrl() === renderedUrl) {\n afterRender();\n return;\n }\n renderedUrl = documentUrl();\n onNavigation(afterRender);\n };\n\n const onPopState = () => notify('pop');\n window.addEventListener('popstate', onPopState);\n undo.push(() => window.removeEventListener('popstate', onPopState));\n\n // Saved unbound on purpose, and called back with `.call(this, …)` below — patching `history` is the only\n // way to see a navigation the app makes itself, and the receiver is restored at every call site.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldPushState = window.history.pushState;\n window.history.pushState = function (state, unused, url) {\n const res = oldPushState.call(this, state, unused, url as string);\n notify('push');\n return res;\n };\n undo.push(() => {\n window.history.pushState = oldPushState;\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method -- as with `pushState` above.\n const oldReplaceState = window.history.replaceState;\n window.history.replaceState = function (state, unused, url) {\n const res = oldReplaceState.call(this, state, unused, url as string);\n notify('replace');\n return res;\n };\n undo.push(() => {\n window.history.replaceState = oldReplaceState;\n });\n\n return () => disposeAll(undo);\n}\n\n/**\n * Dev-only refresh client, listening to the CLI's SSE endpoint:\n *\n * client-built → hot-apply the waiting updates; anything the page can't be patched up to reloads.\n * rsc-update → server component code changed: re-fetch the flight payload, state preserved.\n * hello → sent on (re)connect with the latest build hash; a mismatch means a missed event.\n */\n// `Promise<unknown>`: the payload fetch reports whether its navigation was superseded, which matters to a\n// click and not to a rebuild — here only settling or rejecting does.\nfunction initDevRefresh(fetchRscPayload: () => Promise<unknown>) {\n const hot = import.meta.webpackHot!;\n let connectedOnce = false;\n /** The newest build the dev server has announced — what {@link applyClientUpdate} walks towards. */\n let targetHash: string | undefined;\n\n function reload(reason: string, error?: unknown): void {\n console.warn(`[rshono] ${reason} — reloading`, ...(error === undefined ? [] : [error]));\n window.location.reload();\n }\n\n async function applyClientUpdate(): Promise<void> {\n const giveUp = await walkHotUpdates(\n hot,\n () => __webpack_hash__,\n () => targetHash,\n );\n if (giveUp) reload(giveUp.reason, giveUp.error);\n }\n\n async function handle(message: DevMessage): Promise<void> {\n switch (message.type) {\n case 'hello':\n targetHash = message.hash ?? targetHash;\n if (connectedOnce) {\n await applyClientUpdate();\n await fetchRscPayload().catch(() => window.location.reload());\n }\n connectedOnce = true;\n break;\n case 'client-built':\n targetHash = message.hash;\n await applyClientUpdate();\n break;\n case 'rsc-update':\n console.log('[rshono] server components updated');\n await fetchRscPayload().catch(() => window.location.reload());\n break;\n }\n }\n\n const source = new EventSource('/_rshono/hmr');\n // Chained rather than handled as they arrive: `hot.check` may only run from `idle`, and a burst of saves\n // puts several frames on the wire inside the time one takes. Queueing drops nothing, because `targetHash`\n // is shared — whichever handler runs next walks to the newest build.\n let queue: Promise<void> = Promise.resolve();\n source.onmessage = (event: MessageEvent<string>) => {\n const message = JSON.parse(event.data) as DevMessage;\n queue = queue.then(() => handle(message)).catch((error) => reload('the dev client failed', error));\n };\n}\n\n// A bootstrap failure — a truncated initial payload, most likely — would otherwise be an unhandled\n// rejection: nothing hydrates, nothing is reported, and the page just sits there.\nmain().catch((error) => {\n console.error('[rshono] the client runtime failed to start:', error);\n showFatal(error);\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry.rsc.d.ts","sourceRoot":"","sources":["../../src/runtime/entry.rsc.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAsBvD,OAAO,EAA0F,KAAK,KAAK,EAAoB,MAAM,cAAc,CAAC;AAwBpJ,eAAO,MAAM,MAAM,EAAE,SAAS,KAAK,EAAuB,CAAC;AAE3D,kGAAkG;AAClG,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAExF,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC;IACtB,WAAW,CAAC,EAAE,YAAY,CAAC;IAC3B,SAAS,CAAC,EAAE,cAAc,CAAC;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;
|
|
1
|
+
{"version":3,"file":"entry.rsc.d.ts","sourceRoot":"","sources":["../../src/runtime/entry.rsc.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAsBvD,OAA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