@barqjs/start 0.0.0-stage → 0.2.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +791 -2
- package/dist/client-BHyIiYxt.js +1527 -0
- package/dist/client-BHyIiYxt.js.map +1 -0
- package/dist/client-DHCV7yvQ.d.ts +440 -0
- package/dist/client-DHCV7yvQ.d.ts.map +1 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +4 -0
- package/dist/env-qA8EyOr1.d.ts +49 -0
- package/dist/env-qA8EyOr1.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +44 -0
- package/dist/env.js.map +1 -0
- package/dist/index-Bm_-MTj6.d.ts +915 -0
- package/dist/index-Bm_-MTj6.d.ts.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +6 -0
- package/dist/middleware-BdVlE8qm.d.ts +576 -0
- package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +282 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +98 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +58 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +26 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +135 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +223 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-BV3xKmLa.js +1148 -0
- package/dist/server-BV3xKmLa.js.map +1 -0
- package/dist/server.d.ts +142 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-ChnB_xug.js +1140 -0
- package/dist/src-ChnB_xug.js.map +1 -0
- package/dist/static-fn-DgjNArBe.js +123 -0
- package/dist/static-fn-DgjNArBe.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +672 -0
- package/src/context.ts +666 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +97 -0
- package/src/frames-client.ts +1216 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +714 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +182 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +990 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +139 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-BHyIiYxt.js","names":[],"sources":["../src/fn-error.ts","../src/stubs.ts","../src/frames.ts","../src/frames-client.ts","../src/start-instance.ts","../src/live-client.ts","../src/client.ts"],"sourcesContent":["/**\n * How a server function's failure reaches its caller in the browser. Its own\n * module, so every module that answers a call can raise it and none of them\n * has to import the stub to do so.\n */\n\n/** What a handler threw, as a development server tells its caller. */\nexport interface ServerFnThrown {\n readonly name: string;\n readonly message: string;\n /** Mapped to the source files by the development server. */\n readonly stack?: string;\n}\n\n/** One thing wrong with a call's input, and the path to the field it is about. */\nexport interface ServerFnIssue {\n readonly message: string;\n readonly path?: readonly (string | number)[];\n}\n\n/** What a failed call's JSON body may carry. */\nexport interface FailedAnswer {\n readonly message?: string;\n readonly issues?: readonly ServerFnIssue[];\n readonly thrown?: ServerFnThrown;\n}\n\n/**\n * A server function answered with a failure.\n *\n * THE MESSAGE IS NOT THE HANDLER'S, and that is deliberate rather than\n * unfinished. `server.ts` refuses to put a handler's error text on the wire\n * because it can name a table, a column or a filesystem path, and none of that\n * is the caller's business — TanStack serialises the whole error object to the\n * client instead. What a caller legitimately needs is the STATUS, so it is here\n * as a field rather than something to parse back out of a string.\n */\nexport class ServerFnError extends Error {\n readonly status: number;\n /**\n * What was wrong with the input, for a 400 the validator refused: one entry\n * per issue, with the path to the field it is about. Sent in every build,\n * because it describes the caller's own input.\n */\n readonly issues?: readonly ServerFnIssue[];\n /**\n * What the handler threw: its name, message and source-mapped stack. Only a\n * development server sends it; in production this is `undefined`, so handle\n * a failure by its `status` rather than by this.\n */\n readonly thrown?: ServerFnThrown;\n /**\n * The answer itself, unread.\n *\n * The server's own refusals land here: a 400 for input, a 403 for an origin,\n * a 404, a 405, a 413. A `Response` a middleware or a handler THREW is not\n * wrapped at all; the call rejects with it. A handler's own failure has\n * nothing here worth reading: the server answers those with one fixed line,\n * for the reason above.\n */\n readonly response?: Response;\n constructor(id: string, status: number, response?: Response, answer?: FailedAnswer) {\n super(failureMessage(id, status, answer));\n this.name = \"ServerFnError\";\n this.status = status;\n this.response = response;\n if (answer?.issues !== undefined) this.issues = answer.issues;\n if (answer?.thrown !== undefined) this.thrown = answer.thrown;\n }\n}\n\nfunction failureMessage(id: string, status: number, answer: FailedAnswer | undefined): string {\n const issues = answer?.issues;\n if (issues !== undefined && issues.length > 0) {\n const listed = issues\n .map((issue) =>\n issue.path === undefined ? issue.message : `\\`${issue.path.join(\".\")}\\`: ${issue.message}`,\n )\n .join(\"; \");\n return (\n `The server function \\`${id}\\` refused its input (${status}): ${listed}. ` +\n \"`error.issues` holds each issue with the path to its field.\"\n );\n }\n const thrown = answer?.thrown;\n if (thrown !== undefined) {\n return (\n `The server function \\`${id}\\` threw \\`${thrown.name}: ${thrown.message}\\` and answered ${status}. ` +\n \"The server's stack is in `error.thrown.stack` and in the development overlay. A production \" +\n \"server sends only the status, so handle a failure by `error.status`.\"\n );\n }\n return (\n `The server function \\`${id}\\` answered ${status}. A handler's own error text is never sent to the browser, so read it in the server's log. ` +\n \"`error.response` holds the server's answer.\"\n );\n}\n","/**\n * The stubs a page has made, and how `live` calls one: a module of its own so\n * the frames client finds a stub by id without importing the stub's module.\n */\n\n/** What the registry holds: a callable stub that knows its id. */\nexport type Stub = ((options?: unknown) => Promise<unknown>) & {\n readonly meta: { readonly id: string };\n};\n\n/** A call at the live address: where the last connection left off, and how to end this one. */\nexport interface LiveRequest {\n readonly lastEventId: string | null;\n readonly signal: AbortSignal;\n}\n\n/** How `live` calls a stub at the live address, its client middleware around the fetch. */\nexport const LIVE_CALL: unique symbol = Symbol.for(\"barq.server-fn.live\");\n\n/**\n * Every stub this page has made, by id: what a frame the page carries asks for\n * its connection through when it was called through `live` on the server.\n */\nconst STUBS = new Map<string, Stub>();\n\nexport function registerStub(id: string, stub: Stub): void {\n STUBS.set(id, stub);\n}\n\nexport function clientStub(id: string): Stub | undefined {\n return STUBS.get(id);\n}\n","/**\n * Frames: a region of server-rendered markup the browser can ask for again and\n * apply in place, Solid 2.0's partial rendering.\n *\n * A frame is what a server function returns when its handler returns a\n * component. The component runs on the server only; what crosses is its\n * markup. The props it is rendered with are SLOTS, positions it marks and the\n * browser fills: `props.children`, and a call such as\n * `props.comment({ cid })`, whose arguments cross as data and whose own\n * children cross as a nested region of server markup.\n *\n * This module is the wire both halves agree on, and nothing else.\n *\n * THE WIRE. A frame is its markup:\n *\n * ```html\n * <barq-frame data-frame=\"<address>\"><script type=\"application/barq-frame\">\n * { \"v\": 1, \"slots\": [...], \"head\": [...] }\n * </script> ...region... <!--s:0--> ...a slot's content... <!--/s:0--> ...</barq-frame>\n * ```\n *\n * The page carries it inline where a route rendered it, and a server-function\n * response carries the same bytes as its body under `x-barq-rpc: frame`. The\n * payload holds what the browser needs to fill the slots and nothing the\n * markup already says, so no piece of content arrives twice.\n */\n\nimport type { Child, Incoming, JSXElement } from \"@barqjs/core\";\nimport type { HeadTag } from \"@barqjs/web\";\n\n/**\n * A slot on a server component's props: a call the browser answers with its\n * own content. What the call is given crosses as data, and its `children` as a\n * region of server markup. `$key` names the occurrence, so its content follows\n * it across updates rather than its position.\n */\nexport type Slot<P extends object = {}> = (\n props: Incoming<P & { readonly $key?: string | number; readonly children?: Child }>,\n) => JSXElement;\n\n/**\n * A slot the server component reads as data: called once per data context,\n * `const like = props.like({ cid })`, and each property placed whole at a\n * position of the server's own markup, an attribute, a class name or style\n * property in object form, a handler, a ref or a text child. The page's fill\n * takes the call's arguments and returns the object those positions read; the\n * server never has its values to compute with.\n */\nexport type BindingSlot<\n A extends object = {},\n B extends object = Record<string, unknown>,\n> = keyof A extends never\n ? (args?: { readonly $key?: string | number }) => Readonly<B>\n : (args: A & { readonly $key?: string | number }) => Readonly<B>;\n\n/** The brand on a frame, on either side, carrying where it lives. */\nexport const FRAME: unique symbol = Symbol.for(\"barq.frame\") as never;\n\n/** How a frame is named across the wire: its server function and its address. */\nexport interface FrameRef {\n readonly id: string;\n readonly address: string;\n}\n\n/** Whether a value is a frame: a server function's component result, on either side. */\nexport function isFrame(value: unknown): boolean {\n return (\n typeof value === \"function\" &&\n (value as unknown as Record<symbol, unknown>)[FRAME] !== undefined\n );\n}\n\n/**\n * How a server function's component result becomes a frame, installed by\n * `@barqjs/start/server`: on the global, because a server bundle and the host\n * serving it each carry a copy of this module, and the copy that defines a\n * server function is not always the one that imported the server half.\n */\nconst MAKE = Symbol.for(\"barq.frames.make\");\n\ntype MakeFrame = (id: string, data: unknown, component: (props: never) => unknown) => unknown;\n\nexport function installFrames(make: MakeFrame): void {\n (globalThis as { [MAKE]?: MakeFrame })[MAKE] = make;\n}\n\n/** The handler's result, a frame when it is a component and the server half is here. */\nexport function asFrame(id: string, data: unknown, result: unknown): unknown {\n const make = (globalThis as { [MAKE]?: MakeFrame })[MAKE];\n if (make === undefined || typeof result !== \"function\" || isFrame(result)) return result;\n return make(id, data, result as (props: never) => unknown);\n}\n\n/** The element a frame's markup stands in. `display: contents`, so it takes no box. */\nexport const FRAME_TAG = \"barq-frame\";\n\n/** The element a nested region of server markup stands in, inside a slot's content. */\nexport const REGION_TAG = \"barq-region\";\n\n/** The `type` of the script that carries a frame's payload. Not JavaScript, so never run. */\nexport const PAYLOAD_TYPE = \"application/barq-frame\";\n\n/** The `x-barq-rpc` value a frame response carries. */\nexport const RPC_FRAME = \"frame\";\n\n/**\n * The `x-barq-rpc` value of a mutation's answer that carries the regions it\n * changed beside its value: single flight, one round trip for both.\n */\nexport const RPC_FLIGHT = \"flight\";\n\n/**\n * The request header a page sends with a mutation: the frames it has mounted,\n * as `[{ id, args }]`, so the answer can carry the ones the mutation changed.\n * Bounded, as a header is: a page with more mounted frames names the first ones.\n */\nexport const FRAMES_HEADER = \"x-barq-frames\";\nexport const FRAMES_BUDGET = 32;\n\n/** The `type` of the script a single-flight answer carries its value in. */\nexport const FLIGHT_TYPE = \"application/barq-flight\";\n\n/** Dispatched on `document` once a frame update has been applied to the page. */\nexport const FRAME_APPLIED_EVENT = \"barq:frame-applied\";\n\n/** The wire format's version: a browser reading a newer one fetches the page whole. */\nexport const FRAME_VERSION = 1;\n\n/**\n * One slot the server component marked: where it stands, by the index in its\n * markers, and what the browser needs to fill it.\n */\nexport interface SlotRecord {\n /** The index in the slot's markers, `<!--s:N-->` and `<!--/s:N-->`. */\n readonly at: number;\n /** The prop the component read: `children`, or the name it called. */\n readonly name: string;\n /**\n * The occurrence's identity across updates: `$key` when the call named one,\n * and its name and position among the calls of that name otherwise.\n */\n readonly key: string;\n /** The call's arguments, wire-encoded, its `children` aside. */\n readonly args?: unknown;\n /**\n * The call's `children`, as server markup: the nested region. Absent when\n * the page already carries it, inside the slot's content.\n */\n readonly region?: string;\n /** Whether the call passed `children` at all. */\n readonly hasRegion?: boolean;\n /**\n * The call was read as data, a binding slot: it has no range, and its\n * properties fill the positions marked with its index.\n */\n readonly bind?: boolean;\n}\n\n/** What a frame's script carries. */\nexport interface FramePayload {\n readonly v: number;\n /**\n * What the call was given, wire-encoded: what the page sends to ask for the\n * region again, live or after a mutation. It is the call's own input, which\n * the page could have sent itself.\n */\n readonly args?: unknown;\n /** Called through `live`: the page connects and keeps the region current. */\n readonly live?: boolean;\n readonly slots: readonly SlotRecord[];\n /** What the region declared for the head, and the assets it needs. */\n readonly head: readonly HeadTag[];\n}\n\nexport function slotOpen(at: number): string {\n return `s:${at}`;\n}\n\nexport function slotClose(at: number): string {\n return `/s:${at}`;\n}\n\n/** The marker index a comment's data names, or `-1` when it is not a slot's opening marker. */\nexport function slotIndex(data: string): number {\n return data.startsWith(\"s:\") ? Number(data.slice(2)) : -1;\n}\n\n/** The marker index a comment's data names, or `-1` when it is not a slot's closing marker. */\nexport function slotEnd(data: string): number {\n return data.startsWith(\"/s:\") ? Number(data.slice(3)) : -1;\n}\n\n/**\n * A string of 32-bit FNV-1a, in base 36: short enough to be an attribute,\n * stable across processes, which a frame's address has to be.\n */\nfunction digest(text: string): string {\n let hash = 0x811c9dc5;\n for (let at = 0; at < text.length; at++) {\n hash ^= text.charCodeAt(at);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(36);\n}\n\n/**\n * Where a frame lives: the server function and what it was called with. One\n * address is one region, so asking for it again updates that region rather\n * than mounting a second one, and an answer for other arguments is another.\n */\nexport function frameAddress(id: string, wireArgs: unknown): string {\n return `${id}#${digest(JSON.stringify(wireArgs ?? null))}`;\n}\n\n/** The payload as the text of its script: `<` escaped, so no string in it can end the element. */\nexport function payloadText(payload: FramePayload): string {\n return JSON.stringify(payload).replaceAll(\"<\", \"\\\\u003c\");\n}\n\n/** The opening of a frame's markup, the payload's script included. */\nexport function frameOpen(address: string, payload: FramePayload): string {\n const attribute = address\n .replaceAll(\"&\", \"&\")\n .replaceAll('\"', \""\")\n .replaceAll(\"<\", \"<\");\n return (\n `<${FRAME_TAG} data-frame=\"${attribute}\" style=\"display:contents\">` +\n `<script type=\"${PAYLOAD_TYPE}\">${payloadText(payload)}</script>`\n );\n}\n\nexport const FRAME_CLOSE = `</${FRAME_TAG}>`;\n\nexport function regionMarkup(key: string, html: string): string {\n const attribute = key.replaceAll(\"&\", \"&\").replaceAll('\"', \""\").replaceAll(\"<\", \"<\");\n return `<${REGION_TAG} data-region=\"${attribute}\" style=\"display:contents\">${html}</${REGION_TAG}>`;\n}\n\n/**\n * A binding slot's markers, as `@barqjs/server` writes them: an attribute\n * `_b-<position>` on each element it fills, valued `<at>:<key>[=<member>]`\n * entries separated by commas, and a text child between `<!--_b:<at>:<key>-->`\n * and `<!--/_b-->`. The position is the attribute's name, `on-<event>` or\n * `ref`; a member is a class name or style property in object form, or\n * `capture` on a handler.\n */\nexport const BIND_ATTRIBUTE = \"_b-\";\nexport const BIND_EVENT = \"on-\";\nexport const BIND_TEXT = \"_b:\";\nexport const BIND_TEXT_END = \"/_b\";\n\nexport interface BindEntry {\n readonly at: number;\n readonly key: string;\n readonly member?: string;\n}\n\nfunction bindEntry(text: string): BindEntry | null {\n const colon = text.indexOf(\":\");\n if (colon < 1) return null;\n const at = Number(text.slice(0, colon));\n if (!Number.isInteger(at)) return null;\n const equals = text.indexOf(\"=\", colon);\n const key = decodeURIComponent(\n equals === -1 ? text.slice(colon + 1) : text.slice(colon + 1, equals),\n );\n return equals === -1\n ? { at, key }\n : { at, key, member: decodeURIComponent(text.slice(equals + 1)) };\n}\n\n/** The entries of a marker attribute's value. */\nexport function bindEntries(value: string): BindEntry[] {\n const out: BindEntry[] = [];\n for (const text of value.split(\",\")) {\n const entry = bindEntry(text);\n if (entry !== null) out.push(entry);\n }\n return out;\n}\n\n/** The entry a text position's opening comment names, or `null` when it is not one. */\nexport function bindTextEntry(data: string): BindEntry | null {\n return data.startsWith(BIND_TEXT) ? bindEntry(data.slice(BIND_TEXT.length)) : null;\n}\n","/**\n * The browser half of frames: the component a server function's frame answer\n * becomes, and the update that applies a new answer to every place it is\n * mounted without building any of the page again.\n *\n * One component per address. Asking for a frame again hands back the SAME\n * component, so a `dynamic` over it does not remount: the new markup is\n * morphed into the region where it stands. Server nodes are patched in place,\n * and a slot's content, which the browser owns, is kept, its arguments\n * updated, and moved only when the server moved it.\n */\n\nimport {\n type HeadTag,\n bindEvent,\n classToString,\n delegate,\n element,\n insert,\n isHydrating,\n onHydrationEnd,\n ref as bindRef,\n setClass,\n setProp,\n setStyle,\n useHead,\n} from \"@barqjs/web\";\nimport {\n type Owner,\n block,\n createRenderEffect,\n createRoot,\n createSignal,\n getOwner,\n onCleanup,\n runWithOwner,\n untrack,\n} from \"@barqjs/core\";\nimport { withoutClaim } from \"@barqjs/core/internal\";\nimport { type Range, withRange } from \"@barqjs/web/internal\";\nimport { type AnySerializationAdapter, decodeWire } from \"@barqjs/server/codec\";\n\nimport { ServerFnError } from \"./fn-error.ts\";\nimport { LIVE_CALL, type LiveRequest, type Stub, clientStub } from \"./stubs.ts\";\nimport {\n BIND_ATTRIBUTE,\n BIND_EVENT,\n BIND_TEXT_END,\n type BindEntry,\n FRAME,\n FRAME_APPLIED_EVENT,\n FRAME_TAG,\n FLIGHT_TYPE,\n FRAMES_BUDGET,\n FRAME_VERSION,\n type FramePayload,\n type FrameRef,\n PAYLOAD_TYPE,\n REGION_TAG,\n type SlotRecord,\n bindEntries,\n bindTextEntry,\n isFrame,\n slotClose,\n slotEnd,\n slotIndex,\n slotOpen,\n} from \"./frames.ts\";\n\n/** What a frame renders as: a component taking the slots' content as props. */\nexport type FrameComponent = ((props: Record<string, unknown>) => Node) & {\n readonly [FRAME]: FrameRef;\n};\n\n/** One slot's content, owned by the browser. */\ninterface Occurrence {\n readonly key: string;\n readonly name: string;\n readonly start: Comment;\n readonly end: Comment;\n readonly region: Element | null;\n readonly setArgs: (args: Record<string, unknown>) => void;\n readonly dispose: () => void;\n}\n\n/**\n * One binding slot occurrence: the page's fill, run once, and the positions of\n * the server's markup its properties fill, by the node that carries each and\n * the position's spelling.\n */\ninterface Binding {\n readonly name: string;\n readonly owner: Owner | null;\n readonly values: Record<string, unknown> | null;\n readonly setArgs: (args: Record<string, unknown>) => void;\n readonly dispose: () => void;\n readonly positions: Map<Node, Map<string, () => void>>;\n}\n\n/** One place a frame is mounted. */\ninterface Mount {\n readonly host: Element;\n /** The page is being claimed over this mount's server markup, slots included. */\n claiming: boolean;\n readonly owner: Owner | null;\n readonly props: Record<string, unknown>;\n readonly occurrences: Map<Comment, Occurrence>;\n /** The binding slot occurrences, by key. */\n bindings: Map<string, Binding>;\n}\n\ninterface FrameState {\n readonly ref: FrameRef;\n payload: FramePayload | null;\n /** The region's markup as the last answer carried it, for a mount that has none on the page. */\n markup: string | null;\n readonly mounts: Set<Mount>;\n readonly head: () => readonly HeadTag[];\n readonly setHead: (head: readonly HeadTag[]) => void;\n readonly component: FrameComponent;\n /** The live connection the page opened for a frame it was served, while one is open. */\n connection: { readonly stop: () => void } | null;\n}\n\nconst FRAMES = new Map<string, FrameState>();\n\n/**\n * Keep a frame the page was served through `live` current: the connection a\n * `live` call in the browser would have opened, through the same stub and so\n * its client middleware, opened once the page has been claimed and closed\n * when the last place the frame is mounted goes.\n */\nfunction connect(state: FrameState): void {\n if (state.connection !== null || state.payload?.live !== true) return;\n const stub = clientStub(state.ref.id) as Parameters<typeof liveIterable>[0] | undefined;\n if (stub === undefined) return;\n const options = {\n data: state.payload.args === undefined ? undefined : decodeWire(state.payload.args),\n };\n const iterator = liveIterable(stub, options)[Symbol.asyncIterator]();\n const connection = { stop: (): void => void iterator.return?.() };\n state.connection = connection;\n void (async () => {\n try {\n for (;;) if ((await iterator.next()).done === true) return;\n } catch (error) {\n console.error(\n `[barq] The live frame of ${JSON.stringify(state.ref.id)} could not stay connected, so it shows what it last received. The error:`,\n error,\n );\n } finally {\n if (state.connection === connection) state.connection = null;\n }\n })();\n}\n\nfunction stateFor(ref: FrameRef): FrameState {\n const known = FRAMES.get(ref.address);\n if (known !== undefined) return known;\n const [head, setHead] = createSignal<readonly HeadTag[]>([], { ownedWrite: true });\n const state: FrameState = {\n ref,\n payload: null,\n markup: null,\n mounts: new Set(),\n head,\n setHead,\n component: null as never,\n connection: null,\n };\n const component = (props: Record<string, unknown>): Node => mount(state, props);\n (state as { component: FrameComponent }).component = Object.assign(component, { [FRAME]: ref });\n FRAMES.set(ref.address, state);\n return state;\n}\n\n/**\n * How a frame named in the page's seed becomes the component for the region\n * the page already carries. The client entry installs it beside the\n * application's own adapters, before the seed is read.\n */\nexport const frameAdapter: AnySerializationAdapter = {\n key: \"barq.frame\",\n test: isFrame,\n toSerializable: (frame: FrameComponent): FrameRef => ({\n id: frame[FRAME].id,\n address: frame[FRAME].address,\n }),\n fromSerializable: (ref: FrameRef): FrameComponent => stateFor(ref).component,\n};\n\nfunction payloadOf(host: Element): FramePayload | null {\n const script = host.firstElementChild;\n if (script === null || script.localName !== \"script\") return null;\n if (script.getAttribute(\"type\") !== PAYLOAD_TYPE) return null;\n const text = script.textContent ?? \"\";\n return text === \"\" ? null : (JSON.parse(text) as FramePayload);\n}\n\n/** The frame's own script, which the morph leaves to `setPayload`. */\nfunction isPayload(node: Node | null): node is Element {\n return (\n node !== null &&\n node.nodeType === 1 &&\n (node as Element).localName === \"script\" &&\n (node as Element).getAttribute(\"type\") === PAYLOAD_TYPE\n );\n}\n\nfunction setPayload(host: Element, payload: FramePayload): void {\n const script = host.firstElementChild;\n if (script !== null && isPayload(script)) script.textContent = JSON.stringify(payload);\n}\n\nfunction recordAt(payload: FramePayload, at: number): SlotRecord | undefined {\n return payload.slots.find((record) => record.at === at);\n}\n\n/** The comment that closes the slot `start` opens, among its siblings. */\nfunction closeOf(start: Comment): Comment | null {\n const at = slotIndex(start.data);\n for (let node = start.nextSibling; node !== null; node = node.nextSibling) {\n if (node.nodeType === 8 && slotEnd((node as Comment).data) === at) return node as Comment;\n }\n return null;\n}\n\nfunction between(start: Node, end: Node): Node[] {\n const out: Node[] = [];\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n out.push(node);\n }\n return out;\n}\n\n/** Every slot opening in `root` that no occurrence owns yet, in document order. */\nfunction unfilled(root: Element, owned: Map<Comment, Occurrence>): Comment | null {\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n const comment = node as Comment;\n if (slotIndex(comment.data) !== -1 && !owned.has(comment)) return comment;\n }\n return null;\n}\n\nfunction regionElement(key: string, markup: string): Element {\n const region = document.createElement(REGION_TAG);\n region.setAttribute(\"data-region\", key);\n region.setAttribute(\"style\", \"display:contents\");\n region.innerHTML = markup;\n return region;\n}\n\n/**\n * Fill one slot: the page's `children` where the server placed them, or the\n * page's function for a named slot called with the occurrence's arguments.\n *\n * While the page is being claimed, the server's content for the slot is\n * CLAIMED: the fill runs over a cursor on the slot's range, as the content of\n * any other hole does, and takes the nodes the server wrote for it. Otherwise\n * the slot is empty and the fill builds into it. A nested region the server\n * wrote is handed to the fill as its children either way.\n */\nfunction fill(site: Mount, start: Comment, record: SlotRecord): Occurrence | null {\n const end = closeOf(start);\n if (end === null) return null;\n const parent = end.parentNode;\n if (parent === null) return null;\n const served = between(start, end);\n const claiming = site.claiming && served.length > 0;\n let region: Element | null = null;\n if (record.hasRegion === true) {\n for (const node of served) {\n const found =\n node.nodeType === 1 && (node as Element).localName === REGION_TAG\n ? (node as Element)\n : node.nodeType === 1\n ? (node as Element).querySelector(REGION_TAG)\n : null;\n if (found !== null) {\n region = found;\n break;\n }\n }\n if (!claiming) region?.remove();\n region ??= regionElement(String(record.at), record.region ?? \"\");\n }\n if (!claiming) for (const node of served) node.parentNode?.removeChild(node);\n const [args, setArgs] = createSignal<Record<string, unknown>>(\n record.args === undefined ? {} : decodeWire(record.args),\n { ownedWrite: true },\n );\n const given = site.props[record.name];\n const content = (): unknown => {\n if (record.name === \"children\") return given;\n // A fill that takes nothing reaches the props as the Cell it is, so reading\n // the prop is calling it.\n const fn = typeof given === \"function\" ? untrack(given as () => unknown) : given;\n if (typeof fn !== \"function\") return fn ?? null;\n const props: Record<string, unknown> = {};\n for (const key of Object.keys(untrack(args))) props[key] = (): unknown => args()[key];\n if (region !== null) {\n const placed = region;\n props.children = block(() => placed);\n }\n return untrack(() => (fn as (props: Record<string, unknown>) => unknown)(props));\n };\n const range: Range = { open: start, close: end, parent, nodes: served };\n const dispose = claiming\n ? runWithOwner(site.owner, () =>\n createRoot((release) => {\n withRange(range, () => {\n const value = content();\n // A Block is called with the scope it builds under, as `insert` calls one.\n return typeof value === \"function\"\n ? (value as (scope: unknown) => unknown)(getOwner())\n : value;\n });\n return release;\n }),\n )\n : withoutClaim(() =>\n runWithOwner(site.owner, () =>\n createRoot((release) => {\n insert(parent, content() as never, end);\n return release;\n }),\n ),\n );\n return { key: record.key, name: record.name, start, end, region, setArgs, dispose };\n}\n\n/** Fill every slot in the mount that has no content yet, outermost first. */\nfunction fillAll(site: Mount, payload: FramePayload): void {\n for (;;) {\n const start = unfilled(site.host, site.occurrences);\n if (start === null) return;\n const record = recordAt(payload, slotIndex(start.data));\n const occurrence = record === undefined ? null : fill(site, start, record);\n // A marker with no record, or no close, is left as it is rather than filled.\n site.occurrences.set(start, occurrence ?? DEAD);\n }\n}\n\nconst DEAD: Occurrence = {\n key: \"\",\n name: \"\",\n start: null as never,\n end: null as never,\n region: null,\n setArgs: () => {},\n dispose: () => {},\n};\n\nfunction mount(state: FrameState, props: Record<string, unknown>): Node {\n const owner = getOwner();\n // The server's element when the page is being claimed: its region stays\n // exactly as it is, and only the slots are filled.\n const host = element(FRAME_TAG, {});\n const adopted = host.getAttribute(\"data-frame\") === state.ref.address && payloadOf(host) !== null;\n if (!adopted) {\n withoutClaim(() => {\n host.setAttribute(\"data-frame\", state.ref.address);\n host.setAttribute(\"style\", \"display:contents\");\n host.innerHTML = `<script type=\"${PAYLOAD_TYPE}\"></script>${state.markup ?? markupOnPage(state) ?? \"\"}`;\n if (state.payload !== null) setPayload(host, state.payload);\n });\n }\n state.payload ??= payloadOf(host);\n const payload = state.payload ?? { v: FRAME_VERSION, slots: [], head: [] };\n if (untrack(state.head).length === 0 && payload.head.length > 0) state.setHead(payload.head);\n const placed: Mount = {\n host,\n owner,\n props,\n occurrences: new Map(),\n bindings: new Map(),\n claiming: adopted && isHydrating(),\n };\n fillAll(placed, payload);\n bindAll(placed, payload);\n placed.claiming = false;\n state.mounts.add(placed);\n useHead(() => state.head());\n if (adopted) onHydrationEnd(() => connect(state));\n onCleanup(() => {\n state.mounts.delete(placed);\n for (const occurrence of placed.occurrences.values()) occurrence.dispose();\n for (const binding of placed.bindings.values()) binding.dispose();\n if (state.mounts.size === 0) state.connection?.stop();\n });\n return host;\n}\n\n/**\n * A frame the page carries but this mount was not claimed over: one that\n * rendered on the server and is mounted again after the page started, from a\n * seed that named it. Its markup is taken from the page.\n */\nfunction markupOnPage(state: FrameState): string | null {\n for (const candidate of document.querySelectorAll(FRAME_TAG)) {\n if (candidate.getAttribute(\"data-frame\") !== state.ref.address) continue;\n state.payload ??= payloadOf(candidate);\n const copy = candidate.cloneNode(true) as Element;\n copy.firstElementChild?.remove();\n for (const comment of commentsIn(copy)) {\n const at = slotIndex(comment.data);\n if (at === -1) continue;\n const end = closeOf(comment);\n if (end !== null)\n for (const node of between(comment, end)) node.parentNode?.removeChild(node);\n }\n return copy.innerHTML;\n }\n return null;\n}\n\n/** Every comment in `root`, collected before the caller changes the tree around them. */\nfunction commentsIn(root: Node): Comment[] {\n const walker = (root.ownerDocument ?? document).createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n const out: Comment[] = [];\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n out.push(node as Comment);\n }\n return out;\n}\n\n// ── binding slots ─────────────────────────────────────────────────────────\n\n/** The page's fill for a binding slot, run once: the object whose properties fill its positions. */\nfunction bindOccurrence(site: Mount, record: SlotRecord): Binding {\n const [args, setArgs] = createSignal<Record<string, unknown>>(\n record.args === undefined ? {} : decodeWire(record.args),\n { ownedWrite: true },\n );\n const given = site.props[record.name];\n return runWithOwner(site.owner, () =>\n createRoot((dispose): Binding => {\n const props: Record<string, unknown> = {};\n for (const key of Object.keys(untrack(args))) props[key] = (): unknown => args()[key];\n // A fill that takes nothing reaches the props as the Cell it is, so\n // reading the prop is calling it.\n const result = withoutClaim(() =>\n untrack(() => {\n const fn = typeof given === \"function\" ? (given as () => unknown)() : given;\n return typeof fn === \"function\"\n ? (fn as (props: Record<string, unknown>) => unknown)(props)\n : fn;\n }),\n );\n let values: Record<string, unknown> | null = null;\n if (\n typeof result === \"object\" &&\n result !== null &&\n !Array.isArray(result) &&\n !(result instanceof Node)\n ) {\n values = result as Record<string, unknown>;\n } else if (given !== undefined) {\n console.error(\n `[barq] The page's \\`${record.name}\\` fill returned ${result === null ? \"null\" : Array.isArray(result) ? \"an array\" : typeof result} where the server component reads it as data. ` +\n \"A binding slot's fill returns a plain object whose properties fill the positions the server marked, so the server's values stay in place.\",\n );\n }\n const binding: Binding = {\n name: record.name,\n owner: getOwner(),\n values,\n setArgs,\n positions: new Map(),\n dispose: () => {\n for (const at of binding.positions.values()) for (const release of at.values()) release();\n binding.positions.clear();\n dispose();\n },\n };\n return binding;\n }),\n );\n}\n\ninterface Found {\n readonly node: Node;\n readonly position: string;\n readonly entry: BindEntry;\n}\n\n/** Every position marked in `root`, a nested frame's aside, in document order. */\nfunction positionsIn(root: Element): Found[] {\n const out: Found[] = [];\n const walker = root.ownerDocument.createTreeWalker(\n root,\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT,\n {\n acceptNode: (node) =>\n node !== root && node.nodeType === 1 && (node as Element).localName === FRAME_TAG\n ? NodeFilter.FILTER_REJECT\n : NodeFilter.FILTER_ACCEPT,\n },\n );\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n if (node.nodeType === 8) {\n const entry = bindTextEntry((node as Comment).data);\n if (entry !== null) out.push({ node, position: \"\", entry });\n continue;\n }\n const element = node as Element;\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(BIND_ATTRIBUTE)) continue;\n const position = name.slice(BIND_ATTRIBUTE.length);\n for (const entry of bindEntries(element.getAttribute(name) ?? \"\")) {\n out.push({ node, position, entry });\n }\n }\n }\n return out;\n}\n\n/**\n * Bring the binding slot occurrences up to date with a payload: a new one's\n * fill runs, a kept one's arguments move and its fill is not run again, and\n * each position in the markup is bound once, a position the morph replaced or\n * dropped released.\n */\nfunction bindAll(site: Mount, payload: FramePayload): void {\n const byAt = new Map<number, Binding>();\n const next = new Map<string, Binding>();\n for (const record of payload.slots) {\n if (record.bind !== true) continue;\n let binding = site.bindings.get(record.key);\n if (binding !== undefined && binding.name === record.name) {\n if (record.args !== undefined) binding.setArgs(decodeWire(record.args));\n } else {\n binding = bindOccurrence(site, record);\n }\n next.set(record.key, binding);\n byAt.set(record.at, binding);\n }\n for (const [key, binding] of site.bindings) if (next.get(key) !== binding) binding.dispose();\n site.bindings = next;\n if (next.size === 0) return;\n\n const seen = new Map<Binding, Map<Node, Set<string>>>();\n for (const found of positionsIn(site.host)) {\n const binding = byAt.get(found.entry.at);\n if (binding === undefined || binding.values === null) continue;\n const id = `${found.position}|${found.entry.key}|${found.entry.member ?? \"\"}`;\n let nodes = seen.get(binding);\n if (nodes === undefined) seen.set(binding, (nodes = new Map<Node, Set<string>>()));\n let ids = nodes.get(found.node);\n if (ids === undefined) nodes.set(found.node, (ids = new Set()));\n ids.add(id);\n let at = binding.positions.get(found.node);\n if (at === undefined) binding.positions.set(found.node, (at = new Map<string, () => void>()));\n if (at.has(id)) continue;\n const claiming = site.claiming;\n const values = binding.values;\n at.set(\n id,\n runWithOwner(binding.owner, () =>\n createRoot((release) => {\n bindPosition(found, values, claiming);\n return release;\n }),\n ),\n );\n }\n for (const binding of next.values()) {\n const nodes = seen.get(binding);\n for (const [node, at] of binding.positions) {\n const ids = nodes?.get(node);\n for (const [id, release] of at) {\n if (ids?.has(id) === true) continue;\n release();\n at.delete(id);\n }\n if (at.size === 0) binding.positions.delete(node);\n }\n }\n}\n\nfunction textOf(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : typeof value === \"number\" || typeof value === \"bigint\"\n ? String(value)\n : \"\";\n}\n\n/**\n * A detached element for the style a claimed position already shows: what\n * `setStyle` would have applied, without writing to the page's element.\n */\nlet scratch: HTMLElement | null = null;\n\n/**\n * Fill one position from the fill's object. A value position follows the\n * property, a handler and a ref are read once, as the page's own JSX reads\n * them. While the page is claimed the server already wrote each value, so the\n * first run writes nothing.\n */\nfunction bindPosition(found: Found, values: Record<string, unknown>, claiming: boolean): void {\n const { node, position, entry } = found;\n const read = (): unknown => values[entry.key];\n if (position === \"\") {\n const start = node as Comment;\n let text: Text;\n if (start.nextSibling !== null && start.nextSibling.nodeType === 3) {\n text = start.nextSibling as Text;\n } else {\n text = document.createTextNode(\"\");\n start.parentNode?.insertBefore(text, start.nextSibling);\n }\n createRenderEffect(\n () => textOf(read()),\n (value) => {\n if (text.data !== value) text.data = value;\n },\n );\n return;\n }\n const element = node as Element;\n if (position === \"ref\") {\n bindRef(element, untrack(read));\n return;\n }\n if (position.startsWith(BIND_EVENT)) {\n const type = position.slice(BIND_EVENT.length);\n const capture = entry.member === \"capture\";\n bindEvent(element, type, untrack(read), capture);\n // A delegated handler is the element's own expando, which nothing else\n // takes back when the position is released.\n if (!capture) onCleanup(() => delegate(element, type, undefined));\n return;\n }\n if (position === \"class\" && entry.member !== undefined) {\n const name = entry.member;\n createRenderEffect(\n () => Boolean(read()),\n (on) => {\n if (element.classList.contains(name) !== on) element.classList.toggle(name, on);\n },\n );\n return;\n }\n // What the channel last applied, which `setStyle` and `setClass` diff against.\n let applied: unknown;\n let first = claiming;\n if (position === \"style\") {\n const member = entry.member;\n createRenderEffect(\n () => (member === undefined ? read() : { [member]: read() }),\n (value) => {\n if (first) {\n first = false;\n scratch ??= document.createElement(\"div\");\n scratch.removeAttribute(\"style\");\n applied = setStyle(scratch, \"style\", value);\n return;\n }\n applied = setStyle(element, \"style\", value, applied);\n },\n );\n return;\n }\n if (position === \"class\") {\n createRenderEffect(read, (value) => {\n if (first) {\n first = false;\n applied = classToString(value);\n return;\n }\n applied = setClass(element, \"class\", value, applied);\n });\n return;\n }\n createRenderEffect(read, (value) => {\n if (first) {\n first = false;\n return;\n }\n setProp(element, position, value);\n });\n}\n\n// ── the morph ─────────────────────────────────────────────────────────────\n\ninterface MorphContext {\n readonly mount: Mount;\n readonly payload: FramePayload;\n /** The occurrences still to place, by key. */\n readonly keep: Map<string, Occurrence>;\n readonly used: Set<Occurrence>;\n}\n\nfunction sameNode(current: Node, next: Node): boolean {\n if (current.nodeType !== next.nodeType) return false;\n if (current.nodeType !== 1) return true;\n const a = current as Element;\n const b = next as Element;\n return a.localName === b.localName && a.getAttribute(\"id\") === b.getAttribute(\"id\");\n}\n\n/**\n * The positions of an element a binding slot fills, by its markers: whole\n * attributes, and the class names and style properties it fills in object form.\n */\nfunction ownedBy(element: Element): {\n whole: Set<string>;\n classes: Set<string>;\n styles: Set<string>;\n} {\n const owned = { whole: new Set<string>(), classes: new Set<string>(), styles: new Set<string>() };\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(BIND_ATTRIBUTE)) continue;\n const position = name.slice(BIND_ATTRIBUTE.length);\n if (position === \"ref\" || position.startsWith(BIND_EVENT)) continue;\n for (const entry of bindEntries(element.getAttribute(name) ?? \"\")) {\n if (entry.member === undefined) owned.whole.add(position);\n else if (position === \"class\") owned.classes.add(entry.member);\n else if (position === \"style\") owned.styles.add(entry.member);\n }\n }\n return owned;\n}\n\n/**\n * The server's attributes, written over the element's, except where the page\n * fills a position: a whole attribute it fills is left as it stands, and the\n * class names and style properties it fills keep their current state inside\n * the server's new class and style.\n */\nfunction patchAttributes(current: Element, next: Element): void {\n const owned = ownedBy(next);\n const classes = owned.classes.size > 0;\n const styles = owned.styles.size > 0;\n for (const name of current.getAttributeNames()) {\n if (owned.whole.has(name) || (name === \"class\" && classes) || (name === \"style\" && styles)) {\n continue;\n }\n if (!next.hasAttribute(name)) current.removeAttribute(name);\n }\n for (const name of next.getAttributeNames()) {\n if (owned.whole.has(name) || (name === \"class\" && classes) || (name === \"style\" && styles)) {\n continue;\n }\n const value = next.getAttribute(name) ?? \"\";\n if (current.getAttribute(name) !== value) current.setAttribute(name, value);\n }\n if (classes) {\n const tokens = new Set((next.getAttribute(\"class\") ?? \"\").split(/\\s+/).filter(Boolean));\n for (const name of owned.classes) {\n if (current.classList.contains(name)) tokens.add(name);\n else tokens.delete(name);\n }\n const value = [...tokens].join(\" \");\n if ((current.getAttribute(\"class\") ?? \"\") !== value) current.setAttribute(\"class\", value);\n }\n if (styles) {\n const style = (current as HTMLElement).style;\n const kept = new Map<string, string>();\n for (const property of owned.styles) {\n const css = cssProperty(property);\n kept.set(css, style.getPropertyValue(css));\n }\n const value = next.getAttribute(\"style\");\n if (current.getAttribute(\"style\") !== value) {\n if (value === null) current.removeAttribute(\"style\");\n else current.setAttribute(\"style\", value);\n for (const [css, text] of kept) {\n if (text === \"\") style.removeProperty(css);\n else style.setProperty(css, text);\n }\n }\n }\n}\n\n/** A style object's key as the declaration's name, as `setStyle` writes it. */\nfunction cssProperty(property: string): string {\n return property.startsWith(\"--\")\n ? property\n : property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\nfunction isTextEnd(node: Node | null): boolean {\n return node !== null && node.nodeType === 8 && (node as Comment).data === BIND_TEXT_END;\n}\n\nfunction occurrenceAt(context: MorphContext, node: Node | null): Occurrence | null {\n if (node === null || node.nodeType !== 8) return null;\n const found = context.mount.occurrences.get(node as Comment);\n return found === undefined || found === DEAD ? null : found;\n}\n\n/** Move an occurrence's whole range, markers and content, to stand before `before`. */\nfunction place(occurrence: Occurrence, parent: Node, before: Node | null): void {\n const nodes = [occurrence.start, ...between(occurrence.start, occurrence.end), occurrence.end];\n for (const node of nodes) parent.insertBefore(node, before);\n}\n\nfunction morphChildren(current: Node, next: Node, context: MorphContext): void {\n let cursor: Node | null = current.firstChild;\n if (isPayload(cursor)) cursor = cursor.nextSibling;\n const incoming = [...next.childNodes];\n for (let at = 0; at < incoming.length; at++) {\n const node = incoming[at];\n // An occurrence standing here that the server no longer puts here is\n // stepped over: it is moved to where it now belongs, or removed after.\n for (let standing = occurrenceAt(context, cursor); standing !== null;) {\n cursor = standing.end.nextSibling;\n standing = occurrenceAt(context, cursor);\n }\n const opening = node.nodeType === 8 ? slotIndex((node as Comment).data) : -1;\n if (opening !== -1) {\n let close = at + 1;\n while (close < incoming.length) {\n const candidate = incoming[close];\n if (candidate.nodeType === 8 && slotEnd((candidate as Comment).data) === opening) break;\n close++;\n }\n at = close;\n const record = recordAt(context.payload, opening);\n const kept = record === undefined ? undefined : context.keep.get(record.key);\n if (kept !== undefined && kept.name === record!.name) {\n context.keep.delete(kept.key);\n context.used.add(kept);\n if (kept.start.nextSibling !== cursor || kept.start.parentNode !== current) {\n place(kept, current, cursor);\n }\n kept.start.data = slotOpen(opening);\n kept.end.data = slotClose(opening);\n continue;\n }\n current.insertBefore(document.createComment(slotOpen(opening)), cursor);\n current.insertBefore(document.createComment(slotClose(opening)), cursor);\n continue;\n }\n // A text position the page fills keeps the page's text: the server's\n // pair has nothing between, and the morph steps over both.\n if (\n node.nodeType === 8 &&\n bindTextEntry((node as Comment).data) !== null &&\n cursor !== null &&\n cursor.nodeType === 8 &&\n (cursor as Comment).data === (node as Comment).data\n ) {\n while (at + 1 < incoming.length && !isTextEnd(incoming[at])) at++;\n let end: Node | null = cursor.nextSibling;\n while (end !== null && !isTextEnd(end)) end = end.nextSibling;\n cursor = end === null ? null : end.nextSibling;\n continue;\n }\n if (cursor !== null && sameNode(cursor, node)) {\n if (cursor.nodeType === 1) {\n patchAttributes(cursor as Element, node as Element);\n morphChildren(cursor, node, context);\n } else if (cursor.nodeValue !== node.nodeValue) {\n cursor.nodeValue = node.nodeValue;\n }\n cursor = cursor.nextSibling;\n continue;\n }\n current.insertBefore(document.importNode(node, true), cursor);\n }\n // What is left is what the server no longer sends. An occurrence among it is\n // kept in the tree for now: it may still be placed elsewhere.\n while (cursor !== null) {\n const standing = occurrenceAt(context, cursor);\n if (standing !== null) {\n cursor = standing.end.nextSibling;\n continue;\n }\n const gone = cursor;\n cursor = cursor.nextSibling;\n current.removeChild(gone);\n }\n}\n\n/** Apply a new answer to one mount: morph the region, then bring the occurrences up to date. */\nfunction update(site: Mount, payload: FramePayload, markup: string): void {\n const next = document.createElement(\"template\");\n next.innerHTML = markup;\n const keep = new Map<string, Occurrence>();\n for (const occurrence of site.occurrences.values()) {\n if (occurrence !== DEAD) keep.set(occurrence.key, occurrence);\n }\n const context: MorphContext = { mount: site, payload, keep, used: new Set() };\n withoutClaim(() => {\n morphChildren(site.host, next.content, context);\n setPayload(site.host, payload);\n });\n const occurrences = new Map<Comment, Occurrence>();\n for (const occurrence of context.used) {\n occurrences.set(occurrence.start, occurrence);\n const record = recordAt(payload, slotIndex(occurrence.start.data));\n if (record === undefined) continue;\n if (record.args !== undefined) occurrence.setArgs(decodeWire(record.args));\n if (occurrence.region !== null && record.region !== undefined) {\n const region = document.createElement(\"template\");\n region.innerHTML = record.region;\n withoutClaim(() => morphChildren(occurrence.region!, region.content, context));\n for (const nested of context.used) occurrences.set(nested.start, nested);\n }\n }\n for (const occurrence of site.occurrences.values()) {\n if (occurrence === DEAD || context.used.has(occurrence)) continue;\n occurrence.dispose();\n for (const node of [\n occurrence.start,\n ...between(occurrence.start, occurrence.end),\n occurrence.end,\n ]) {\n node.parentNode?.removeChild(node);\n }\n }\n site.occurrences.clear();\n for (const [start, occurrence] of occurrences) site.occurrences.set(start, occurrence);\n fillAll(site, payload);\n bindAll(site, payload);\n}\n\n// ── assets ────────────────────────────────────────────────────────────────\n\n/**\n * The region's stylesheets, loaded before it is shown: a region revealed\n * before its styles is the flash a server render exists to prevent. Each is\n * the element `useHead` takes over when the frame mounts.\n */\nasync function loadStylesheets(head: readonly HeadTag[]): Promise<void> {\n const loading: Promise<void>[] = [];\n for (const tag of head) {\n const props = tag.props ?? {};\n if (tag.tag !== \"link\" || props.rel !== \"stylesheet\" || typeof props.href !== \"string\")\n continue;\n const key = `link:stylesheet:${props.href}`;\n let present = false;\n for (const candidate of document.head.querySelectorAll(\"[data-bh]\")) {\n if (candidate.getAttribute(\"data-bh\") === key) present = true;\n }\n if (present) continue;\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = props.href;\n link.setAttribute(\"data-bh\", key);\n loading.push(\n new Promise<void>((resolve) => {\n link.addEventListener(\"load\", () => resolve(), { once: true });\n link.addEventListener(\"error\", () => resolve(), { once: true });\n }),\n );\n document.head.appendChild(link);\n }\n await Promise.all(loading);\n}\n\n// ── the wire ──────────────────────────────────────────────────────────────\n\n/**\n * Read a frame answer and apply it: the component for its address, the same\n * one every time, with every place it is mounted morphed to the new markup\n * once the region's stylesheets have loaded.\n */\nexport async function applyFrameResponse(response: Response): Promise<FrameComponent> {\n const template = document.createElement(\"template\");\n template.innerHTML = await response.text();\n return applyFrameMarkup(template.content.firstElementChild);\n}\n\n/** A frame's markup as text, a live event's, applied as a frame answer is. */\nexport function applyFrameText(markup: string): Promise<FrameComponent> {\n const template = document.createElement(\"template\");\n template.innerHTML = markup;\n return applyFrameMarkup(template.content.firstElementChild);\n}\n\n/** One frame's markup, applied to every place its address is mounted. */\nasync function applyFrameMarkup(host: Element | null): Promise<FrameComponent> {\n const address = host?.getAttribute(\"data-frame\") ?? null;\n const payload = host === null ? null : payloadOf(host);\n if (host === null || address === null || payload === null) {\n throw new Error(\n \"[barq] A server function answered with a frame whose markup has no `barq-frame` element and payload, so there is nothing to apply. \" +\n \"The server and this page were built from different versions: reload the page.\",\n );\n }\n if (payload.v !== FRAME_VERSION) {\n throw new Error(\n `[barq] A server function answered with frame version ${payload.v}, and this page reads version ${FRAME_VERSION}. ` +\n \"The server was deployed after this page loaded: reload the page.\",\n );\n }\n host.firstElementChild?.remove();\n const markup = host.innerHTML;\n const id = address.slice(0, address.lastIndexOf(\"#\"));\n const state = stateFor({ id, address });\n await loadStylesheets(payload.head);\n state.payload = payload;\n state.markup = markup;\n state.setHead(payload.head);\n for (const placed of state.mounts) update(placed, payload, markup);\n document.dispatchEvent(new CustomEvent(FRAME_APPLIED_EVENT, { detail: { address } }));\n return state.component;\n}\n\n/**\n * What a mutation sends so its answer can carry the regions it changed: every\n * mounted frame's function and arguments, up to the budget, or `null` with\n * none mounted.\n */\nexport function mountedFramesHeader(): string | null {\n const out: { id: string; args: unknown }[] = [];\n for (const state of FRAMES.values()) {\n if (state.mounts.size === 0 || state.payload === null) continue;\n out.push({ id: state.ref.id, args: state.payload.args });\n if (out.length === FRAMES_BUDGET) break;\n }\n return out.length === 0 ? null : JSON.stringify(out);\n}\n\n/**\n * A mutation's single-flight answer: each region it carries applied where it\n * is mounted, then the value, which is what the caller is handed.\n */\nexport async function applyFlight(response: Response): Promise<unknown> {\n const template = document.createElement(\"template\");\n template.innerHTML = await response.text();\n const script = template.content.firstElementChild;\n if (\n script === null ||\n script.localName !== \"script\" ||\n script.getAttribute(\"type\") !== FLIGHT_TYPE\n ) {\n throw new Error(\n \"[barq] A server function answered with a single flight whose value script is missing, so there is no value to hand the caller. \" +\n \"The server and this page were built from different versions: reload the page.\",\n );\n }\n const value = decodeWire(JSON.parse(script.textContent ?? \"null\"));\n for (const host of template.content.children) {\n if (host.localName === FRAME_TAG) await applyFrameMarkup(host);\n }\n return value;\n}\n\n/** Forget every frame, for a test that renders more than one page. */\nexport function resetFrames(): void {\n FRAMES.clear();\n}\n\n// ── live ──────────────────────────────────────────────────────────────────\n//\n// `live`'s loop, here because a frame the page was served through `live`\n// connects through it as well as a `live` call does.\n\n/** What the loop says about its connection. */\nexport type LiveStatus = \"connected\" | \"reconnecting\" | \"closed\";\n\nexport interface LiveIterable<T> extends AsyncIterable<T> {\n /** Told `\"connected\"` per connection, `\"reconnecting\"` with the error per death, `\"closed\"` at the end. */\n onstatus?: (status: LiveStatus, error?: unknown) => void;\n}\n\ninterface ServerEvent {\n readonly event: string;\n readonly id: string | null;\n readonly data: string;\n}\n\n/** The events of a `text/event-stream` body, as the spec frames them. */\nasync function* eventsOf(body: ReadableStream<Uint8Array>): AsyncGenerator<ServerEvent> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n let event = \"message\";\n let id: string | null = null;\n let data: string[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n pending += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let end = pending.search(/\\r\\n|\\r|\\n/);\n while (end !== -1) {\n const line = pending.slice(0, end);\n pending = pending.slice(end + (pending.startsWith(\"\\r\\n\", end) ? 2 : 1));\n if (line === \"\") {\n if (data.length > 0 || event !== \"message\") yield { event, id, data: data.join(\"\\n\") };\n event = \"message\";\n data = [];\n } else if (!line.startsWith(\":\")) {\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n const text = colon === -1 ? \"\" : line.slice(colon + 1).replace(/^ /, \"\");\n if (field === \"data\") data.push(text);\n else if (field === \"event\") event = text;\n else if (field === \"id\") id = text;\n }\n end = pending.search(/\\r\\n|\\r|\\n/);\n }\n if (done) return;\n }\n } finally {\n void reader.cancel().catch(() => {});\n }\n}\n\n/** Statuses that say \"ask again\" even though they refuse this time. */\nconst RETRY = new Set([408, 425, 429]);\n\n/** How long to wait before the next connection, the nth failure in a row. */\nfunction pause(failures: number, signal: AbortSignal): Promise<void> {\n const ms = Math.min(30_000, 250 * 2 ** failures);\n return new Promise<void>((resolve) => {\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n globalThis.removeEventListener?.(\"online\", done);\n signal.removeEventListener(\"abort\", done);\n resolve();\n }\n globalThis.addEventListener?.(\"online\", done, { once: true });\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nexport type LiveStub = Stub & {\n readonly [LIVE_CALL]: (options: unknown, live: LiveRequest) => Promise<Response>;\n};\n\n/** The reconnecting iteration of one live call. */\nexport function liveIterable(stub: LiveStub, options: unknown): LiveIterable<unknown> {\n const iterable: LiveIterable<unknown> = {\n [Symbol.asyncIterator]: (): AsyncIterator<unknown> => {\n const controller = new AbortController();\n const running = loop(stub, options, iterable, controller);\n return {\n next: () => running.next(),\n // The connection is ended here, not when the generator gets round to\n // it: one waiting on a body that sends nothing would never get there.\n return: (value?: unknown) => {\n controller.abort();\n return running.return(value);\n },\n };\n },\n };\n return iterable;\n}\n\nasync function* loop(\n stub: LiveStub,\n options: unknown,\n told: LiveIterable<unknown>,\n controller: AbortController,\n): AsyncGenerator {\n let lastEventId: string | null = null;\n let failures = 0;\n let connected = false;\n try {\n for (;;) {\n let response: Response;\n try {\n response = await stub[LIVE_CALL](options, { lastEventId, signal: controller.signal });\n } catch (error) {\n if (controller.signal.aborted) return;\n if (!connected) throw error;\n told.onstatus?.(\"reconnecting\", error);\n await pause(failures++, controller.signal);\n continue;\n }\n if (!response.ok || response.body === null) {\n const retries = RETRY.has(response.status) || response.headers.has(\"retry-after\");\n const error = new ServerFnError(stub.meta.id, response.status, response);\n if (!connected || (!retries && response.status >= 400 && response.status < 500))\n throw error;\n told.onstatus?.(\"reconnecting\", error);\n await pause(failures++, controller.signal);\n continue;\n }\n connected = true;\n failures = 0;\n told.onstatus?.(\"connected\");\n let yielded: unknown = undefined;\n let complete = false;\n let died: unknown = new Error(\n `[barq] The live connection of ${JSON.stringify(stub.meta.id)} ended before it was complete.`,\n );\n try {\n for await (const event of eventsOf(response.body)) {\n if (event.event === \"complete\") {\n complete = true;\n break;\n }\n if (event.id !== null) lastEventId = event.id;\n const data = JSON.parse(event.data) as unknown;\n if (event.event === \"frame\") {\n const component = await applyFrameText(data as string);\n if (component !== yielded) {\n yielded = component;\n yield component;\n }\n continue;\n }\n yield decodeWire(data);\n }\n } catch (error) {\n died = error;\n }\n if (complete || controller.signal.aborted) return;\n told.onstatus?.(\"reconnecting\", died);\n await pause(failures++, controller.signal);\n }\n } finally {\n controller.abort();\n told.onstatus?.(\"closed\");\n }\n}\n","/**\n * The application-wide middleware, declared once.\n *\n * TanStack Start's `createStart`, written in a project's `src/start.ts`:\n *\n * ```ts\n * export const startInstance = createStart(() => ({\n * requestMiddleware: [logging],\n * functionMiddleware: [requireSession],\n * }));\n * ```\n *\n * Its own module, importing nothing that reaches `node:async_hooks`, because\n * the client stub reads it: a global function middleware's client half runs in\n * the browser around every call.\n */\n\nimport { type AnySerializationAdapter, registerSerializationAdapters } from \"@barqjs/server/codec\";\n\nimport type { ChainContribution, Empty, Middleware } from \"./middleware.ts\";\n\nexport interface StartOptions {\n /** Runs for every request the server answers: a page, a route handler, a server function. */\n readonly requestMiddleware?: readonly Middleware[];\n /** Runs for every server function, ahead of the function's own chain. */\n readonly functionMiddleware?: readonly Middleware[];\n /**\n * How a type only the application knows crosses the wire, in a server\n * function's input and result and in the page's seed. Installed when the\n * options are first read, which both sides do before they encode anything.\n */\n readonly serializationAdapters?: readonly AnySerializationAdapter[];\n /**\n * What a route that says nothing about `ssr` does, for every route: `true`,\n * `false` (rendered in the browser alone) or `\"data-only\"` (loaders run on\n * the server, the component in the browser). Wins over the router's own\n * `defaultSsr`, as TanStack's does.\n */\n readonly defaultSsr?: boolean | \"data-only\";\n readonly serverFns?: {\n /**\n * The `fetch` every call goes out through, in place of the global one. A\n * client middleware's `next({ fetch })` and the call's own `fetch` win\n * over it.\n */\n readonly fetch?: typeof fetch;\n };\n}\n\nexport interface StartInstance<Options extends StartOptions = StartOptions> {\n getOptions(): Options;\n}\n\ndeclare const UNREGISTERED: unique symbol;\n\n/**\n * Where an application tells the types about its `src/start.ts`:\n *\n * ```ts\n * declare module \"@barqjs/start\" {\n * interface Register {\n * start: typeof startInstance;\n * }\n * }\n * ```\n *\n * With that, what the global middleware passes to `next({ context })` is typed\n * in every server function's `context` and in `getGlobalStartContext()`.\n * Without it they are untyped, never wrong. The member below exists so the\n * interface is not the empty object type before anything augments it.\n */\nexport interface Register {\n readonly [UNREGISTERED]?: never;\n}\n\ntype RegisteredInstance = Register extends { readonly start: infer Instance }\n ? Instance\n : StartInstance;\n\n/** What an instance's request middleware adds, for the whole request. */\nexport type RequestContextOf<Instance> =\n Instance extends StartInstance<infer Options>\n ? ChainContribution<NonNullable<Options[\"requestMiddleware\"]>>[\"context\"]\n : Empty;\n\n/** What an instance's middleware hands every server function: request, then function. */\nexport type FunctionContextOf<Instance> =\n Instance extends StartInstance<infer Options>\n ? RequestContextOf<Instance> &\n ChainContribution<NonNullable<Options[\"functionMiddleware\"]>>[\"context\"]\n : Empty;\n\n/** What the registered global request middleware adds, for the whole request. */\nexport type GlobalRequestContext = RequestContextOf<RegisteredInstance>;\n\n/** What every server function's `context` starts from. */\nexport type GlobalFunctionContext = FunctionContextOf<RegisteredInstance>;\n\n/**\n * One instance for the process, whichever copy of this module asks.\n *\n * It is configuration, fixed once the application has loaded, so it has none\n * of the hazards an ambient request would: nothing a visitor does changes it.\n * On the global registry for the reason the server-function registry is: a\n * build compiles this module into its server bundle, and a host serving that\n * bundle through its own `serveBarq` has imported a second copy.\n */\nconst REGISTERED = ((globalThis as Record<symbol, unknown>)[Symbol.for(\"barq.start.instance\")] ??= {\n instance: null,\n}) as { instance: StartInstance | null };\n\nconst NONE: StartOptions = Object.freeze({});\n\n/**\n * Declare the application's global middleware.\n *\n * The function is called once, the first time anything asks, so a middleware\n * module that imports this one back is fully evaluated by then.\n */\nexport function createStart<const Options extends StartOptions>(\n options: () => Options,\n): StartInstance<Options> {\n let resolved: Options | undefined;\n const instance: StartInstance<Options> = {\n getOptions: () => {\n if (resolved === undefined) {\n resolved = options();\n if (resolved.serializationAdapters !== undefined) {\n registerSerializationAdapters(resolved.serializationAdapters);\n }\n }\n return resolved;\n },\n };\n REGISTERED.instance = instance;\n return instance;\n}\n\n/** What the application declared, or nothing. */\nexport function startOptions(): StartOptions {\n return REGISTERED.instance?.getOptions() ?? NONE;\n}\n\n/** Test seam. Not for application use. */\nexport function clearStart(): void {\n REGISTERED.instance = null;\n}\n","/**\n * `live`: a server function's answer as a standing one, kept current for as\n * long as the caller reads it, Solid 2.0's declaration.\n *\n * In the browser, calling a live function returns an async iterable that\n * survives its connection. Each connection is a call at the live address,\n * read as server-sent events: a value per event, or, for a frame, the region\n * applied where it is mounted, the same component yielded once per connection\n * so a `dynamic` over it never remounts. A body that ends without saying it\n * is complete is a death, and the loop calls again, after a pause that grows\n * with each failure in a row and resets on a healthy connection, naming the\n * last event it applied. A failure on the first connection rejects as a call\n * would, and so does a refusal the server will repeat.\n *\n * On the server, in process, there is no connection: the call is the call,\n * and a frame it answers with is marked so the page connects once claimed.\n */\n\nimport type { ServerFn } from \"./client.ts\";\nimport { type LiveIterable, type LiveStub, liveIterable } from \"./frames-client.ts\";\nimport { FRAME } from \"./frames.ts\";\n\nexport type { LiveIterable, LiveStatus } from \"./frames-client.ts\";\n\n/** Whether a server function is the server half, which runs in this process. */\nfunction inProcess(fn: unknown): boolean {\n return typeof fn === \"function\" && \"built\" in fn;\n}\n\n/**\n * Declare a server function's answer a standing one. In the browser, calling\n * the result returns an iterable that stays connected; on the server it is the\n * call itself, a frame it answers with marked for the page to connect.\n */\nexport function live<In, Out>(\n fn: ServerFn<In, Out, never>,\n): (...args: Parameters<ServerFn<In, Out, never>>) => LiveIterable<Awaited<Out>> {\n if (inProcess(fn)) {\n return ((...args: unknown[]) =>\n (fn as unknown as (...given: unknown[]) => Promise<unknown>)(...args).then((answer) => {\n const frame =\n typeof answer === \"function\"\n ? (answer as unknown as Record<symbol, { live?: boolean }>)[FRAME]\n : undefined;\n if (frame !== undefined) frame.live = true;\n return answer;\n })) as never;\n }\n return ((options?: unknown) => liveIterable(fn as unknown as LiveStub, options)) as never;\n}\n","/**\n * The client half of a server function, and NOTHING the server half needs.\n *\n * Its own module because of what importing it costs. The compiler replaces a\n * server-function module's contents with `export const x = clientRpc(\"<id>\")`,\n * and that stub used to import from `@barqjs/start` — whose index re-exports\n * `context.ts`, which is `node:async_hooks`. Every client bundle that reached\n * one server function therefore pulled the request-context machinery, the\n * middleware runner, the validators and the error classes, and Vite printed\n * \"node:async_hooks has been externalized for browser compatibility\" on every\n * build.\n *\n * That was survivable while a route module was `lazy()`, because the cost sat\n * in that route's own chunk. It stopped being survivable when `routeTree.gen.ts`\n * started importing route modules STATICALLY: measured on\n * `packages/kitchen-sink`, 25.7 kB of it moved into the set every page\n * preloads, for an application with two server functions on one route.\n *\n * So the stub imports from here. `index.ts` re-exports every name below, so an\n * application still writes `import { createServerFn } from \"@barqjs/start\"` and\n * nothing about the authoring surface changes.\n */\n\nimport { decodeWire, encodeWire } from \"@barqjs/server/codec\";\nimport {\n type FailedAnswer,\n type ServerFnIssue,\n type ServerFnThrown,\n ServerFnError,\n} from \"./fn-error.ts\";\nimport { applyFlight, applyFrameResponse, mountedFramesHeader } from \"./frames-client.ts\";\nimport { LIVE_CALL, type LiveRequest, registerStub } from \"./stubs.ts\";\nimport { FRAMES_HEADER, RPC_FLIGHT, RPC_FRAME } from \"./frames.ts\";\nimport {\n type Middleware,\n NOT_FOUND,\n REDIRECT,\n flattenMiddleware,\n runMiddleware,\n} from \"./middleware.ts\";\nimport { startOptions } from \"./start-instance.ts\";\n\nexport { STATIC_PREFIX, staticFunctionMiddleware, staticUrl } from \"./static-fn.ts\";\nexport { NOT_FOUND, REDIRECT } from \"./middleware.ts\";\nexport { ServerFnError, type ServerFnIssue, type ServerFnThrown } from \"./fn-error.ts\";\nexport { LIVE_CALL, type LiveRequest, clientStub } from \"./stubs.ts\";\nexport { type FrameComponent, applyFrameResponse, frameAdapter } from \"./frames-client.ts\";\nexport { type LiveIterable, type LiveStatus, live } from \"./live-client.ts\";\nexport { type BindingSlot, FRAME_APPLIED_EVENT, type Slot, isFrame } from \"./frames.ts\";\n\nexport const SERVER_FN: unique symbol = Symbol.for(\"barq.server-fn\");\n\n/** Where mounted server functions answer. */\nexport const RPC_PREFIX = \"/_barq/fn/\";\n\n/**\n * What distinguishes an RPC call from a form submission: the URL, not a header.\n *\n * `/_barq/fn/<id>` is what `<form action={fn}>` writes, takes `FormData`, and\n * answers with a redirect a browser can follow with JS disabled.\n * `/_barq/fn/<id>.data` is the JSON channel and answers with a value.\n *\n * React Router's `.data` suffix, and the reason is its reason: a header decides\n * the response shape invisibly, and a form cannot set one. RedwoodSDK shows the\n * failure — it emits the right hidden fields for a no-JS submit and never reads\n * them, so the form posts, returns 200, and nothing happens.\n */\nexport const DATA_SUFFIX = \".data\";\n\n/**\n * `/_barq/fn/<id>.live` is the live address: the data address's answer, framed\n * as server-sent events for as long as it stands. Its own URL, because a cache\n * keys on the URL and not on a header nothing tells it to vary by.\n */\nexport const LIVE_SUFFIX = \".live\";\n\n/**\n * How the data channel says \"the answer is an instruction, not a value\".\n *\n * A HEADER rather than a body sniff, so a caller that does not care never\n * parses the body to find out, and so a handler returning a plain object that\n * happens to have a `to` field is never mistaken for a redirect.\n */\nexport const RPC_CONTROL = \"x-barq-rpc\";\n\n/**\n * The {@link RPC_CONTROL} value for a `Response` the handler returned.\n *\n * The response IS the result then, and its body is whatever the handler wrote,\n * so the stub hands it back whole rather than reading it as a wire value. No\n * body rides under this one, which is why it is not an {@link RpcControl} kind.\n */\nexport const RPC_RESPONSE = \"response\";\n\n/**\n * The {@link RPC_CONTROL} value for a `Response` a handler, a validator or a\n * middleware THREW: the call rejects with that response itself, as TanStack's\n * does. Its body and status are what the author wrote for the caller.\n */\nexport const RPC_THROWN = \"thrown\";\n\n/**\n * The {@link RPC_CONTROL} value for an answer that arrives over time.\n *\n * The body is then one JSON line for each value the function yielded, each\n * holding a wire-encoded value, and the stub hands the caller an async iterable\n * of them. A line that says the function failed ends it with a\n * {@link ServerFnError}.\n */\nexport const RPC_STREAM = \"stream\";\n\n/** One line of a streamed answer: a value, the chain's `sendContext`, or a failure. */\nexport type RpcStreamLine =\n | { readonly v: unknown }\n | { readonly c: unknown }\n | { readonly e: 1; readonly t?: ServerFnThrown };\n\n/** The body of a 400 for refused input. */\nexport interface ServerFnInputAnswer {\n readonly error: \"invalid input\";\n readonly message: string;\n readonly issues: readonly ServerFnIssue[];\n}\n\n/**\n * What a caller is handed for a handler's result.\n *\n * A function that returns a `ReadableStream` or an async iterable answers over\n * time, and both arrive as an async iterable of the values, in the browser and\n * in process alike.\n */\nexport type Streamed<Out> =\n Out extends ReadableStream<infer Value>\n ? AsyncIterableIterator<Value>\n : Out extends AsyncIterable<infer Value>\n ? AsyncIterableIterator<Value>\n : Out;\n\n/**\n * Present when a middleware's `sendContext` rides back with the result.\n *\n * A HEADER flagging a different body shape, which is what `RPC_CONTROL` already\n * does and for the same reason: an ordinary call — every call, in almost every\n * application — must not pay a second parse or a wrapper object to carry\n * something it does not have. With the flag the body is `{ result, context }`;\n * without it the body IS the result, byte for byte as before.\n */\nexport const RPC_CONTEXT = \"x-barq-ctx\";\n\n/** The body shape {@link RPC_CONTEXT} announces. */\nexport interface RpcEnvelope {\n readonly result: unknown;\n readonly context: unknown;\n}\n\n/**\n * What rides in the body under {@link RPC_CONTROL}.\n *\n * `options` and `data` are wire-encoded, so a `Date` in a redirect's search or\n * in a not-found's data arrives as one. Each is absent when the thrown value\n * carried none, which leaves the body the two fields it otherwise is.\n */\nexport type RpcControl =\n | {\n readonly kind: \"redirect\";\n readonly to: string;\n readonly status: number;\n readonly options?: unknown;\n }\n | {\n readonly kind: \"not-found\";\n readonly message: string;\n readonly data?: unknown;\n readonly routeId?: string;\n };\n\n/**\n * A redirect that arrived over the wire, rebuilt on the client.\n *\n * NOT `@barqjs/router`'s `Redirect` — this package cannot construct that one.\n * It carries the same brand, so `isRedirect` from the router accepts it and the\n * router navigates on it exactly as it would on a redirect a loader threw. That\n * interchangeability is the whole reason those predicates are brand checks\n * rather than `instanceof`.\n */\nexport class RpcRedirect extends Error {\n readonly [REDIRECT] = true as const;\n readonly to: string;\n readonly status: number;\n readonly statusCode: number;\n /**\n * The navigation an options-form redirect described: `to`, `params`,\n * `search`, `hash`, `replace`, `reloadDocument`, `href`. The router goes\n * there in place of `to` when it is present.\n */\n readonly options?: Record<string, unknown>;\n constructor(to: string, status: number, options?: Record<string, unknown>) {\n super(`redirect to ${to}`);\n this.name = \"Redirect\";\n this.to = to;\n this.status = status;\n this.statusCode = status;\n this.options = options;\n }\n}\n\n/** The `notFound()` counterpart, branded for the same reason. */\nexport class RpcNotFound extends Error {\n readonly [NOT_FOUND] = true as const;\n readonly isNotFound = true as const;\n /** What `notFound({ data })` carried, for the `notFoundComponent` that renders this. */\n readonly data?: unknown;\n /** The route whose `notFoundComponent` answers, when the thrower named one. */\n readonly routeId?: string;\n constructor(message: string, data?: unknown, routeId?: string) {\n super(message);\n this.name = \"NotFound\";\n this.data = data;\n this.routeId = routeId;\n }\n}\n\n/** The JSON a failed call answered with, read from a copy so `error.response` stays unread. */\nasync function failedAnswer(response: Response): Promise<FailedAnswer | undefined> {\n if (!(response.headers.get(\"content-type\") ?? \"\").includes(\"application/json\")) return undefined;\n try {\n return (await response.clone().json()) as FailedAnswer;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The HTTP methods a server function answers. `GET` is the default, for a read\n * the browser and a CDN may cache; see {@link RPC_CALLER} for what keeps a link\n * from reaching one. `POST` is for a write and is the only one a form can reach.\n */\nexport type ServerFnMethod = \"GET\" | \"POST\";\n\nexport interface ServerFnMeta {\n /** Stable across edits and deploys: the module path and the export name. */\n id: string;\n /** Absent for `POST`, which is every function that did not ask for `GET`. */\n readonly method?: ServerFnMethod;\n}\n\n/**\n * The request header every GET call the stub makes carries, and is refused\n * without.\n *\n * A link, an `<img>`, a prefetch and a navigation cannot set a header; only\n * script can, and a cross-origin script that sets one is preflighted and\n * refused by the origin check. So a `GET` server function stays out of reach\n * of everything that is not this application's own code, which is the reason\n * `GET` was once refused outright: a mutation reachable by navigation is a\n * one-click CSRF carrying `SameSite=Lax` cookies.\n */\nexport const RPC_CALLER = \"x-barq-fn\";\n\n/** Where a GET call's payload rides, since a GET has no body. */\nexport const PAYLOAD_PARAM = \"payload\";\n\n/**\n * How a server function is CALLED: `fn({ data })`, and `fn()` when it takes\n * none.\n *\n * TanStack's convention, and worth matching for a reason beyond fidelity: a\n * named field leaves room for the options that\n * come after it without ever changing the call shape again, and it removes the\n * `adminStats(undefined)` the bare form forced on every no-argument call.\n */\n/**\n * What a call may carry beside its `data`. TanStack's three, under their names.\n */\nexport interface ServerFnCallOptions {\n /**\n * Aborts the call. In the browser the fetch is cancelled, and the server sees\n * its request go away, which is what the handler's own `signal` follows.\n */\n readonly signal?: AbortSignal;\n /**\n * Sent with the request. A name set here wins over the same name from a\n * client middleware's `next({ headers })`, since the call is the more\n * specific of the two.\n */\n readonly headers?: HeadersInit;\n /** Used in place of the global `fetch`, for this call alone. */\n readonly fetch?: typeof fetch;\n}\n\nexport type ServerFnArgs<In, Method extends ServerFnMethod = \"POST\"> = [undefined] extends [In]\n ? // The argument is OPTIONAL exactly when `undefined` is an acceptable input,\n // which covers both cases that want it: no validator at all (`In` is\n // `undefined`), and `.validator(\"unchecked\")`, whose `In` is `unknown` and\n // which therefore admits `undefined` too. Asking `[In] extends [undefined]`\n // instead got the first and not the second, so every `unchecked` function\n // that takes nothing still had to be called with an argument.\n //\n // An optional ELEMENT, not a `void` one: a rest tuple with a `void` member\n // does not make the parameter optional, and `fn()` stayed \"Expected 1\n // arguments, but got 0\" until it was written this way.\n [options?: ({ readonly data?: In } & ServerFnCallOptions) | FormFor<Method>]\n : [options: ({ readonly data: In } & ServerFnCallOptions) | FormFor<Method>];\n\n/** A form is a body, so only a `POST` function takes one. */\ntype FormFor<Method extends ServerFnMethod> = Method extends \"POST\" ? FormData : never;\n\n/**\n * A server function, from either side.\n *\n * A bare `FormData` is accepted BESIDE the options object, and only there. It is\n * what `<form action={fn}>` hands the function on the enhanced path, and a\n * `FormData` can never be mistaken for an options object — so the no-JS\n * submission and the JS one reach the handler identically, which is the whole\n * point of that path. TanStack has no counterpart to match here.\n */\nexport type ServerFn<In, Out, Method extends ServerFnMethod = \"POST\"> = ((\n ...args: ServerFnArgs<In, Method>\n) => Promise<Out>) & {\n readonly [SERVER_FN]: true;\n readonly meta: ServerFnMeta;\n /** TanStack's name for `meta`: the id this function is mounted at. */\n readonly serverFnMeta: ServerFnMeta;\n /** The method this function answers. */\n readonly method: ServerFnMethod;\n /**\n * Where a form posts to reach this function: what `<form action={fn}>`\n * writes. Empty for a function that is not mounted, which has no endpoint.\n */\n readonly url: string;\n};\n\n/**\n * Any server function, whatever it takes and returns.\n *\n * `never` in, because the input sits in a parameter: a function that takes a\n * string does not accept `unknown`, and every function accepts `never`. The\n * method is `never` for the same reason: it decides whether a form is a\n * parameter.\n */\nexport type AnyServerFn = ServerFn<never, unknown, never>;\n\n/** The form endpoint of a mounted id, or nothing for a function with none. */\nexport function urlOf(id: string): string {\n return id === \"\" ? \"\" : RPC_PREFIX + encodeURIComponent(id);\n}\n\n/** The `data` out of a call, whichever of the two shapes it arrived in. */\nexport function dataOf(options: unknown): unknown {\n if (options instanceof FormData) return options;\n if (options === undefined || options === null) return undefined;\n return (options as { data?: unknown }).data;\n}\n\n/** What a call asked for beside its `data`. A bare `FormData` asks for nothing. */\nexport function callOptionsOf(options: unknown): ServerFnCallOptions | undefined {\n if (options instanceof FormData || options === undefined || options === null) return undefined;\n return options;\n}\n\n/**\n * The client half. The compiler emits this in a module compiled for the client,\n * with the id, the chain, and nothing else — no handler body, no validator, no\n * imports the body needed.\n *\n * `chain` is the middlewares the function declared, and it is here so a\n * `.client()` half can run around the fetch. Only the CLIENT halves survive the\n * compile: `createMiddleware(...).server(fn)` has its `server` argument deleted\n * in the client build, so a middleware may hold both without the server body —\n * or the database import it needed — reaching the browser.\n */\nexport function clientRpc<In, Out, Method extends ServerFnMethod = \"POST\">(\n id: string,\n declaredChain: readonly ChainStep[] = [],\n declared?: { readonly method?: Method },\n): ServerFn<In, Out, Method> {\n const method: ServerFnMethod = declared?.method ?? \"POST\";\n const chain = inlineServerFns(declaredChain);\n // With the application's global function middleware ahead of the function's\n // own, read when first needed for the reason `serverRpc` gives.\n let composed: { from: readonly Middleware[] | undefined; chain: readonly Middleware[] } | null =\n null;\n const composition = (): readonly Middleware[] => {\n const global = startOptions().functionMiddleware;\n if (composed === null || composed.from !== global) {\n composed = { from: global, chain: flattenMiddleware([...(global ?? []), ...chain]) };\n }\n return composed.chain;\n };\n\n /**\n * The fetch, as the INNERMOST step of the chain.\n *\n * A client middleware therefore wraps the request the way a server one wraps\n * the handler: it can read what it is about to send, add to `sendContext`,\n * and see the result on the way back. TanStack reaches the same arrangement\n * by appending the server function itself to the chain as a middleware.\n */\n const send = async (\n input: unknown,\n sendContext: Record<string, unknown>,\n /**\n * THIS call's context, which is where the server chain's answer is merged.\n * Absent on the path with no chain, where nothing could read it.\n */\n context?: Record<string, unknown>,\n asked?: ServerFnCallOptions,\n /** What the client halves passed to `next({ headers })`. */\n chainHeaders?: Headers,\n /** What the client halves passed to `next({ fetch })`, the last one winning. */\n chainFetch?: typeof fetch,\n /** A call at the live address, whose answer is handed back whole for `live`'s loop to read. */\n live?: LiveRequest,\n ): Promise<Out> => {\n // FormData goes as FormData. Routing it through the value codec would hand\n // the handler a plain OBJECT here and a real `FormData` on the no-JS path —\n // the same function seeing two input types depending on whether JS ran,\n // which is the divergence progressive enhancement exists to avoid. It also\n // keeps files, which no value codec in this class carries.\n const form = input instanceof FormData;\n if (form && method === \"GET\") {\n throw new TypeError(\n `[barq] The server function \\`${id}\\` answers GET, and a GET has no body to carry a form. ` +\n 'Declare it `createServerFn({ method: \"POST\" })` to accept a `FormData`.',\n );\n }\n // Otherwise seroval's JSON channel, so an argument carries a Date, a Map or\n // a cycle the same way a hydration seed does — and reconstructs through\n // `fromJSON`, which evaluates nothing.\n //\n // `context` is what the CLIENT halves asked to send. It is absent from the\n // payload when they asked for nothing, so an application with no client\n // middleware sends exactly the bytes it sent before.\n const payload = form\n ? undefined\n : JSON.stringify(\n Object.keys(sendContext).length === 0\n ? { input: encodeWire(input) }\n : { input: encodeWire(input), context: encodeWire(sendContext) },\n );\n // No content-type for the form case: the browser sets the multipart\n // boundary, and setting it by hand produces a body nothing can parse. None\n // for a GET either, which has no body to describe.\n let headers: HeadersInit | undefined = method === \"GET\" ? CALLER : form ? undefined : JSON_BODY;\n // A mutation names the frames the page has mounted, so its answer can\n // carry the ones it changed.\n const mountedFrames = method === \"POST\" && live === undefined ? mountedFramesHeader() : null;\n if (mountedFrames !== null) {\n const withFrames = new Headers(headers);\n withFrames.set(FRAMES_HEADER, mountedFrames);\n headers = withFrames;\n }\n if (chainHeaders !== undefined || asked?.headers !== undefined) {\n const merged = new Headers(chainHeaders);\n if (mountedFrames !== null) merged.set(FRAMES_HEADER, mountedFrames);\n if (asked?.headers !== undefined) {\n for (const [name, value] of new Headers(asked.headers)) merged.set(name, value);\n }\n // Ours either way: the body is what this function encoded, whatever a\n // caller or a middleware believes it is sending.\n if (form || method === \"GET\") merged.delete(\"content-type\");\n else merged.set(\"content-type\", \"application/json\");\n if (method === \"GET\") merged.set(RPC_CALLER, \"1\");\n headers = merged;\n }\n if (live !== undefined) {\n const withPosition = new Headers(headers);\n if (live.lastEventId !== null) withPosition.set(\"last-event-id\", live.lastEventId);\n headers = withPosition;\n }\n const endpoint =\n RPC_PREFIX + encodeURIComponent(id) + (live === undefined ? DATA_SUFFIX : LIVE_SUFFIX);\n const response = await (asked?.fetch ?? chainFetch ?? startOptions().serverFns?.fetch ?? fetch)(\n method === \"GET\"\n ? `${endpoint}?${PAYLOAD_PARAM}=${encodeURIComponent(payload ?? \"\")}`\n : endpoint,\n {\n method,\n headers,\n signal: live?.signal ?? asked?.signal,\n body: method === \"GET\" ? undefined : form ? input : payload,\n credentials: \"same-origin\",\n // `manual` so a handler that answers with its OWN 3xx — a real\n // `new Response(null, { status: 302 })`, not a `throw redirect(...)` —\n // is handed back as a response rather than silently followed. The\n // default `follow` would fetch the target and hand the CALLER that\n // page's body, which is how TanStack's fetcher turns a redirecting\n // server function into an opaque HTML string.\n redirect: \"manual\",\n },\n );\n // A control answer is an INSTRUCTION rather than a value, and it is read\n // off the header so an ordinary result never pays a second body parse.\n // A BROWSER hides a redirect it was told not to follow: status 0 and no\n // headers, so nothing below can recognise it. It is still the handler's\n // answer, and the status check would report it as a failure with no status.\n if (response.type === \"opaqueredirect\") return response as Out;\n if (live !== undefined) return response as Out;\n const control = response.headers.get(RPC_CONTROL);\n // Before the status check: a response the handler returned is its answer\n // whatever status it chose.\n if (control === RPC_RESPONSE) return response as Out;\n if (control === RPC_THROWN) throw response;\n if (control === RPC_STREAM) return received(response, id, context) as Out;\n if (control === RPC_FRAME) return (await applyFrameResponse(response)) as Out;\n if (control === RPC_FLIGHT) {\n const flown = await applyFlight(response);\n if (response.headers.get(RPC_CONTEXT) === null) return flown as Out;\n const envelope = flown as RpcEnvelope;\n if (context !== undefined) Object.assign(context, envelope.context);\n return envelope.result as Out;\n }\n if (control !== null) throw fromControl((await response.json()) as RpcControl);\n if (!response.ok) {\n throw new ServerFnError(id, response.status, response, await failedAnswer(response));\n }\n if (response.headers.get(RPC_CONTEXT) === null) return decodeWire<Out>(await response.json());\n const envelope = decodeWire<RpcEnvelope>(await response.json());\n // What the SERVER's chain sent back, merged into the same object the client\n // halves have been writing. A client middleware reads it on the way out\n // through the `context` it was handed, which is that object.\n if (context !== undefined) Object.assign(context, envelope.context);\n return envelope.result as Out;\n };\n\n const call = async (options?: unknown, live?: LiveRequest): Promise<Out> => {\n const input = dataOf(options);\n // NO CHAIN, NO RUNNER. Every application without a client middleware takes\n // this line, and it is the line the compiler emitted before any of this\n // existed — one fetch, no closures built, no objects allocated.\n const asked = callOptionsOf(options);\n const flattened = composition();\n if (flattened.length === 0)\n return send(input, EMPTY_CONTEXT, undefined, asked, undefined, undefined, live);\n\n const context: Record<string, unknown> = {};\n const sendContext: Record<string, unknown> = {};\n const headers = new Headers();\n const chosen: { current: typeof fetch | undefined } = { current: undefined };\n return (await runMiddleware(flattened, \"client\", {\n data: input,\n meta: { id },\n method,\n signal: asked?.signal ?? new AbortController().signal,\n context,\n sendContext,\n headers,\n fetch: chosen,\n run: (data) => send(data, sendContext, context, asked, headers, chosen.current, live),\n })) as Out;\n };\n\n const meta: ServerFnMeta = method === \"GET\" ? { id, method } : { id };\n const stub = Object.assign((options?: unknown) => call(options), {\n [SERVER_FN]: true as const,\n [SERVER_FN_CHAIN]: chain,\n [LIVE_CALL]: (options: unknown, live: LiveRequest): Promise<Response> =>\n call(options, live) as Promise<Response>,\n meta,\n serverFnMeta: meta,\n method,\n url: urlOf(id),\n });\n registerStub(id, stub);\n return stub;\n}\n\n/**\n * A streamed answer, as the values it carries.\n *\n * Read a line at a time, so a value is handed over when its line has arrived\n * rather than when the answer is complete. Leaving the loop early cancels the\n * body, which is what tells the server to stop producing.\n */\nasync function* received(\n response: Response,\n id: string,\n context: Record<string, unknown> | undefined,\n): AsyncIterableIterator<unknown> {\n const body = response.body;\n if (body === null) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read();\n pending += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let end = pending.indexOf(\"\\n\");\n while (end !== -1) {\n const line = JSON.parse(pending.slice(0, end)) as RpcStreamLine;\n pending = pending.slice(end + 1);\n if (\"e\" in line) throw new ServerFnError(id, 500, undefined, { thrown: line.t });\n if (\"c\" in line) {\n if (context !== undefined) Object.assign(context, decodeWire(line.c));\n } else yield decodeWire(line.v);\n end = pending.indexOf(\"\\n\");\n }\n if (done) return;\n }\n } finally {\n void reader.cancel().catch(() => {});\n }\n}\n\n/** One object for every JSON call, which only ever reads it. */\nconst JSON_BODY = { \"content-type\": \"application/json\" };\n\n/** What a GET call carries in place of a body's type. */\nconst CALLER = { [RPC_CALLER]: \"1\" };\n\n/** Shared, because the no-middleware path never writes to it. */\nconst EMPTY_CONTEXT: Record<string, unknown> = {};\n\n/**\n * Rebuild the throwable a control answer describes.\n *\n * An UNKNOWN kind is an error rather than a pass-through: it means the server is\n * newer than the client and is describing something this build cannot act on,\n * and returning it as a value would let a navigation instruction be rendered as\n * data.\n */\nfunction fromControl(control: RpcControl): Error {\n if (control.kind === \"redirect\") {\n return new RpcRedirect(\n control.to,\n control.status,\n control.options === undefined ? undefined : decodeWire(control.options),\n );\n }\n if (control.kind === \"not-found\") {\n return new RpcNotFound(\n control.message,\n control.data === undefined ? undefined : decodeWire(control.data),\n control.routeId,\n );\n }\n return new Error(\n `[barq] server function answered with an unrecognised ${RPC_CONTROL} kind ` +\n `${JSON.stringify((control as { kind: string }).kind)}; the server is newer than this client bundle.`,\n );\n}\n\n/** Where a server function keeps the middleware it declared, for another to inline. */\nexport const SERVER_FN_CHAIN: unique symbol = Symbol.for(\"barq.server-fn-chain\");\n\n/** What `.middleware([...])` takes: a middleware, or a server function whose chain it inlines. */\nexport type ChainStep = Middleware | AnyServerFn;\n\n/**\n * A chain with each server function in it replaced by the middleware that\n * function declared, which is TanStack's rule: listing a function lists its\n * guards, never its handler.\n */\nexport function inlineServerFns(chain: readonly ChainStep[]): readonly Middleware[] {\n return chain.flatMap((step): readonly Middleware[] =>\n isServerFn(step) ? chainOf(step) : [step as Middleware],\n );\n}\n\nfunction chainOf(fn: AnyServerFn | ServerFn<unknown, unknown>): readonly Middleware[] {\n return (\n (fn as unknown as Record<symbol, readonly Middleware[] | undefined>)[SERVER_FN_CHAIN] ?? []\n );\n}\n\n/** Whether a value is a server function, by brand rather than by shape. */\nexport function isServerFn(value: unknown): value is ServerFn<unknown, unknown> {\n return (\n typeof value === \"function\" && (value as unknown as Record<symbol, unknown>)[SERVER_FN] === true\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqCA,IAAa,gBAAb,cAAmC,MAAM;CACvC;;;;;;CAMA;;;;;;CAMA;;;;;;;;;;CAUA;CACA,YAAY,IAAY,QAAgB,UAAqB,QAAuB;EAClF,MAAM,eAAe,IAAI,QAAQ,MAAM,CAAC;EACxC,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,IAAI,QAAQ,WAAW,KAAA,GAAW,KAAK,SAAS,OAAO;EACvD,IAAI,QAAQ,WAAW,KAAA,GAAW,KAAK,SAAS,OAAO;CACzD;AACF;AAEA,SAAS,eAAe,IAAY,QAAgB,QAA0C;CAC5F,MAAM,SAAS,QAAQ;CACvB,IAAI,WAAW,KAAA,KAAa,OAAO,SAAS,GAM1C,OACE,yBAAyB,GAAG,wBAAwB,OAAO,KAN9C,OACZ,KAAK,UACJ,MAAM,SAAS,KAAA,IAAY,MAAM,UAAU,KAAK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