@barqjs/start 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
@@ -0,0 +1,1554 @@
1
+ import { decodeWire, encodeWire, registerSerializationAdapters } from "@barqjs/server/codec";
2
+ import { bindEvent, classToString, delegate, element, insert, isHydrating, onHydrationEnd, ref, setClass, setProp, setStyle, useHead } from "@barqjs/web";
3
+ import { block, createRenderEffect, createRoot, createSignal, getOwner, onCleanup, runWithOwner, untrack } from "@barqjs/core";
4
+ import { withoutClaim } from "@barqjs/core/internal";
5
+ import { withRange } from "@barqjs/web/internal";
6
+ import { NOT_FOUND, REDIRECT, flattenMiddleware, runMiddleware } from "./middleware.js";
7
+ // src/fn-error.ts
8
+ /**
9
+ * The label on an answer from a deployment that does not know the call: an
10
+ * unknown id (a tab holding the previous build's ids across a deploy, or a
11
+ * removed function), or a call from another build. A CDN 404 and a skew 404
12
+ * look alike without it.
13
+ */
14
+ const UNKNOWN_HEADER = "x-barq-fn-unknown";
15
+ /**
16
+ * A server function answered with a failure.
17
+ *
18
+ * THE MESSAGE IS NOT THE HANDLER'S, and that is deliberate rather than
19
+ * unfinished. `server.ts` refuses to put a handler's error text on the wire
20
+ * because it can name a table, a column or a filesystem path, and none of that
21
+ * is the caller's business — TanStack serialises the whole error object to the
22
+ * client instead. What a caller legitimately needs is the STATUS, so it is here
23
+ * as a field rather than something to parse back out of a string.
24
+ */
25
+ var ServerFnError = class extends Error {
26
+ status;
27
+ /**
28
+ * What was wrong with the input, for a 400 the validator refused: one entry
29
+ * per issue, with the path to the field it is about. Sent in every build,
30
+ * because it describes the caller's own input.
31
+ */
32
+ issues;
33
+ /**
34
+ * What the handler threw: its name, message and source-mapped stack. Only a
35
+ * development server sends it; in production this is `undefined`, so handle
36
+ * a failure by its `status` rather than by this.
37
+ */
38
+ thrown;
39
+ /**
40
+ * The answer itself, unread.
41
+ *
42
+ * The server's own refusals land here: a 400 for input, a 403 for an origin,
43
+ * a 404, a 405, a 413. A `Response` a middleware or a handler THREW is not
44
+ * wrapped at all; the call rejects with it. A handler's own failure has
45
+ * nothing here worth reading: the server answers those with one fixed line,
46
+ * for the reason above.
47
+ */
48
+ response;
49
+ /**
50
+ * The deployment that answered does not know this call: the page came from
51
+ * another build, or the function was removed. Retrying cannot help; reloading
52
+ * the document onto the current build can.
53
+ */
54
+ unknownFunction;
55
+ constructor(id, status, response, answer) {
56
+ const unknown = (response?.headers.get("x-barq-fn-unknown") ?? null) !== null;
57
+ super(unknown ? skewMessage(id, status) : failureMessage(id, status, answer));
58
+ this.name = "ServerFnError";
59
+ this.status = status;
60
+ this.response = response;
61
+ if (unknown) this.unknownFunction = true;
62
+ if (answer?.issues !== void 0) this.issues = answer.issues;
63
+ if (answer?.thrown !== void 0) this.thrown = answer.thrown;
64
+ }
65
+ };
66
+ function skewMessage(id, status) {
67
+ return `The server function \`${id}\` is not part of the deployment that answered (${status}): this page came from another build, or the function was removed. Reload the page to run the current build; \`error.unknownFunction\` is set for exactly this case.`;
68
+ }
69
+ function failureMessage(id, status, answer) {
70
+ const issues = answer?.issues;
71
+ if (issues !== void 0 && issues.length > 0) return `The server function \`${id}\` refused its input (${status}): ${issues.map((issue) => issue.path === void 0 ? issue.message : `\`${issue.path.join(".")}\`: ${issue.message}`).join("; ")}. \`error.issues\` holds each issue with the path to its field.`;
72
+ const thrown = answer?.thrown;
73
+ if (thrown !== void 0) return `The server function \`${id}\` threw \`${thrown.name}: ${thrown.message}\` and answered ${status}. The server's stack is in \`error.thrown.stack\` and in the development overlay. A production server sends only the status, so handle a failure by \`error.status\`.`;
74
+ return `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. \`error.response\` holds the server's answer.`;
75
+ }
76
+ // src/stubs.ts
77
+ /** How `live` calls a stub at the live address, its client middleware around the fetch. */
78
+ const LIVE_CALL = Symbol.for("barq.server-fn.live");
79
+ /**
80
+ * Every stub this page has made, by id: what a frame the page carries asks for
81
+ * its connection through when it was called through `live` on the server.
82
+ */
83
+ const STUBS = /* @__PURE__ */ new Map();
84
+ function registerStub(id, stub) {
85
+ STUBS.set(id, stub);
86
+ }
87
+ function clientStub(id) {
88
+ return STUBS.get(id);
89
+ }
90
+ // src/frames.ts
91
+ /** The brand on a frame, on either side, carrying where it lives. */
92
+ const FRAME = Symbol.for("barq.frame");
93
+ /** Whether a value is a frame: a server function's component result, on either side. */
94
+ function isFrame(value) {
95
+ return typeof value === "function" && value[FRAME] !== void 0;
96
+ }
97
+ /**
98
+ * How a server function's component result becomes a frame, installed by
99
+ * `@barqjs/start/server`: on the global, because a server bundle and the host
100
+ * serving it each carry a copy of this module, and the copy that defines a
101
+ * server function is not always the one that imported the server half.
102
+ */
103
+ const MAKE = Symbol.for("barq.frames.make");
104
+ function installFrames(make) {
105
+ globalThis[MAKE] = make;
106
+ }
107
+ /** The handler's result, a frame when it is a component and the server half is here. */
108
+ function asFrame(id, data, result) {
109
+ const make = globalThis[MAKE];
110
+ if (make === void 0 || typeof result !== "function" || isFrame(result)) return result;
111
+ return make(id, data, result);
112
+ }
113
+ /** The element a frame's markup stands in. `display: contents`, so it takes no box. */
114
+ const FRAME_TAG = "barq-frame";
115
+ /** The element a nested region of server markup stands in, inside a slot's content. */
116
+ const REGION_TAG = "barq-region";
117
+ /** The `type` of the script that carries a frame's payload. Not JavaScript, so never run. */
118
+ const PAYLOAD_TYPE = "application/barq-frame";
119
+ /** The `x-barq-rpc` value a frame response carries. */
120
+ const RPC_FRAME = "frame";
121
+ /**
122
+ * The `x-barq-rpc` value of a mutation's answer that carries the regions it
123
+ * changed beside its value: single flight, one round trip for both.
124
+ */
125
+ const RPC_FLIGHT = "flight";
126
+ /**
127
+ * The request header a page sends with a mutation: the frames it has mounted,
128
+ * as `[{ id, args }]`, so the answer can carry the ones the mutation changed.
129
+ * Bounded, as a header is: a page with more mounted frames names the first ones.
130
+ */
131
+ const FRAMES_HEADER = "x-barq-frames";
132
+ /** The `type` of the script a single-flight answer carries its value in. */
133
+ const FLIGHT_TYPE = "application/barq-flight";
134
+ /** Dispatched on `document` once a frame update has been applied to the page. */
135
+ const FRAME_APPLIED_EVENT = "barq:frame-applied";
136
+ function slotOpen(at) {
137
+ return `s:${at}`;
138
+ }
139
+ function slotClose(at) {
140
+ return `/s:${at}`;
141
+ }
142
+ /** The marker index a comment's data names, or `-1` when it is not a slot's opening marker. */
143
+ function slotIndex(data) {
144
+ return data.startsWith("s:") ? Number(data.slice(2)) : -1;
145
+ }
146
+ /** The marker index a comment's data names, or `-1` when it is not a slot's closing marker. */
147
+ function slotEnd(data) {
148
+ return data.startsWith("/s:") ? Number(data.slice(3)) : -1;
149
+ }
150
+ /**
151
+ * A string of 32-bit FNV-1a, in base 36: short enough to be an attribute,
152
+ * stable across processes, which a frame's address has to be.
153
+ */
154
+ function digest(text) {
155
+ let hash = 0x811c9dc5;
156
+ for (let at = 0; at < text.length; at++) {
157
+ hash ^= text.charCodeAt(at);
158
+ hash = Math.imul(hash, 16777619);
159
+ }
160
+ return (hash >>> 0).toString(36);
161
+ }
162
+ /**
163
+ * Where a frame lives: the server function and what it was called with. One
164
+ * address is one region, so asking for it again updates that region rather
165
+ * than mounting a second one, and an answer for other arguments is another.
166
+ */
167
+ function frameAddress(id, wireArgs) {
168
+ return `${id}#${digest(JSON.stringify(wireArgs ?? null))}`;
169
+ }
170
+ /** The payload as the text of its script: `<` escaped, so no string in it can end the element. */
171
+ function payloadText(payload) {
172
+ return JSON.stringify(payload).replaceAll("<", "\\u003c");
173
+ }
174
+ /** The opening of a frame's markup, the payload's script included. */
175
+ function frameOpen(address, payload) {
176
+ const attribute = address.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
177
+ return `<${FRAME_TAG} data-frame="${attribute}" style="display:contents"><script type="${PAYLOAD_TYPE}">${payloadText(payload)}<\/script>`;
178
+ }
179
+ const FRAME_CLOSE = `</${FRAME_TAG}>`;
180
+ function regionMarkup(key, html) {
181
+ const attribute = key.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
182
+ return `<${REGION_TAG} data-region="${attribute}" style="display:contents">${html}</${REGION_TAG}>`;
183
+ }
184
+ function bindEntry(text) {
185
+ const colon = text.indexOf(":");
186
+ if (colon < 1) return null;
187
+ const at = Number(text.slice(0, colon));
188
+ if (!Number.isInteger(at)) return null;
189
+ const equals = text.indexOf("=", colon);
190
+ const key = decodeURIComponent(equals === -1 ? text.slice(colon + 1) : text.slice(colon + 1, equals));
191
+ return equals === -1 ? {
192
+ at,
193
+ key
194
+ } : {
195
+ at,
196
+ key,
197
+ member: decodeURIComponent(text.slice(equals + 1))
198
+ };
199
+ }
200
+ /** The entries of a marker attribute's value. */
201
+ function bindEntries(value) {
202
+ const out = [];
203
+ for (const text of value.split(",")) {
204
+ const entry = bindEntry(text);
205
+ if (entry !== null) out.push(entry);
206
+ }
207
+ return out;
208
+ }
209
+ /** The entry a text position's opening comment names, or `null` when it is not one. */
210
+ function bindTextEntry(data) {
211
+ return data.startsWith("_b:") ? bindEntry(data.slice(3)) : null;
212
+ }
213
+ // src/frames-client.ts
214
+ /**
215
+ * The browser half of frames: the component a server function's frame answer
216
+ * becomes, and the update that applies a new answer to every place it is
217
+ * mounted without building any of the page again.
218
+ *
219
+ * One component per address. Asking for a frame again hands back the SAME
220
+ * component, so a `dynamic` over it does not remount: the new markup is
221
+ * morphed into the region where it stands. Server nodes are patched in place,
222
+ * and a slot's content, which the browser owns, is kept, its arguments
223
+ * updated, and moved only when the server moved it.
224
+ */
225
+ const FRAMES = /* @__PURE__ */ new Map();
226
+ /**
227
+ * Keep a frame the page was served through `live` current: the connection a
228
+ * `live` call in the browser would have opened, through the same stub and so
229
+ * its client middleware, opened once the page has been claimed and closed
230
+ * when the last place the frame is mounted goes.
231
+ */
232
+ function connect(state) {
233
+ if (state.connection !== null || state.payload?.live !== true) return;
234
+ const stub = clientStub(state.ref.id);
235
+ if (stub === void 0) return;
236
+ const iterator = liveIterable(stub, { data: state.payload.args === void 0 ? void 0 : decodeWire(state.payload.args) })[Symbol.asyncIterator]();
237
+ const connection = { stop: () => void iterator.return?.() };
238
+ state.connection = connection;
239
+ (async () => {
240
+ try {
241
+ for (;;) if ((await iterator.next()).done === true) return;
242
+ } catch (error) {
243
+ console.error(`[barq] The live frame of ${JSON.stringify(state.ref.id)} could not stay connected, so it shows what it last received. The error:`, error);
244
+ } finally {
245
+ if (state.connection === connection) state.connection = null;
246
+ }
247
+ })();
248
+ }
249
+ function stateFor(ref) {
250
+ const known = FRAMES.get(ref.address);
251
+ if (known !== void 0) return known;
252
+ const [head, setHead] = createSignal([], { ownedWrite: true });
253
+ const state = {
254
+ ref,
255
+ payload: null,
256
+ markup: null,
257
+ mounts: /* @__PURE__ */ new Set(),
258
+ head,
259
+ setHead,
260
+ component: null,
261
+ connection: null
262
+ };
263
+ const component = (props) => mount(state, props);
264
+ state.component = Object.assign(component, { [FRAME]: ref });
265
+ FRAMES.set(ref.address, state);
266
+ return state;
267
+ }
268
+ /**
269
+ * How a frame named in the page's seed becomes the component for the region
270
+ * the page already carries. The client entry installs it beside the
271
+ * application's own adapters, before the seed is read.
272
+ */
273
+ const frameAdapter = {
274
+ key: "barq.frame",
275
+ test: isFrame,
276
+ toSerializable: (frame) => ({
277
+ id: frame[FRAME].id,
278
+ address: frame[FRAME].address
279
+ }),
280
+ fromSerializable: (ref) => stateFor(ref).component
281
+ };
282
+ function payloadOf(host) {
283
+ const script = host.firstElementChild;
284
+ if (script === null || script.localName !== "script") return null;
285
+ if (script.getAttribute("type") !== "application/barq-frame") return null;
286
+ const text = script.textContent ?? "";
287
+ return text === "" ? null : JSON.parse(text);
288
+ }
289
+ /** The frame's own script, which the morph leaves to `setPayload`. */
290
+ function isPayload(node) {
291
+ return node !== null && node.nodeType === 1 && node.localName === "script" && node.getAttribute("type") === "application/barq-frame";
292
+ }
293
+ function setPayload(host, payload) {
294
+ const script = host.firstElementChild;
295
+ if (script !== null && isPayload(script)) script.textContent = JSON.stringify(payload);
296
+ }
297
+ function recordAt(payload, at) {
298
+ return payload.slots.find((record) => record.at === at);
299
+ }
300
+ /** The comment that closes the slot `start` opens, among its siblings. */
301
+ function closeOf(start) {
302
+ const at = slotIndex(start.data);
303
+ for (let node = start.nextSibling; node !== null; node = node.nextSibling) if (node.nodeType === 8 && slotEnd(node.data) === at) return node;
304
+ return null;
305
+ }
306
+ function between(start, end) {
307
+ const out = [];
308
+ for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) out.push(node);
309
+ return out;
310
+ }
311
+ /** Every slot opening in `root` that no occurrence owns yet, in document order. */
312
+ function unfilled(root, owned) {
313
+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
314
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
315
+ const comment = node;
316
+ if (slotIndex(comment.data) !== -1 && !owned.has(comment)) return comment;
317
+ }
318
+ return null;
319
+ }
320
+ function regionElement(key, markup) {
321
+ const region = document.createElement(REGION_TAG);
322
+ region.setAttribute("data-region", key);
323
+ region.setAttribute("style", "display:contents");
324
+ region.innerHTML = markup;
325
+ return region;
326
+ }
327
+ /**
328
+ * Fill one slot: the page's `children` where the server placed them, or the
329
+ * page's function for a named slot called with the occurrence's arguments.
330
+ *
331
+ * While the page is being claimed, the server's content for the slot is
332
+ * CLAIMED: the fill runs over a cursor on the slot's range, as the content of
333
+ * any other hole does, and takes the nodes the server wrote for it. Otherwise
334
+ * the slot is empty and the fill builds into it. A nested region the server
335
+ * wrote is handed to the fill as its children either way.
336
+ */
337
+ function fill(site, start, record) {
338
+ const end = closeOf(start);
339
+ if (end === null) return null;
340
+ const parent = end.parentNode;
341
+ if (parent === null) return null;
342
+ const served = between(start, end);
343
+ const claiming = site.claiming && served.length > 0;
344
+ let region = null;
345
+ if (record.hasRegion === true) {
346
+ for (const node of served) {
347
+ const found = node.nodeType === 1 && node.localName === "barq-region" ? node : node.nodeType === 1 ? node.querySelector(REGION_TAG) : null;
348
+ if (found !== null) {
349
+ region = found;
350
+ break;
351
+ }
352
+ }
353
+ if (!claiming) region?.remove();
354
+ region ??= regionElement(String(record.at), record.region ?? "");
355
+ }
356
+ if (!claiming) for (const node of served) node.parentNode?.removeChild(node);
357
+ const [args, setArgs] = createSignal(record.args === void 0 ? {} : decodeWire(record.args), { ownedWrite: true });
358
+ const given = site.props[record.name];
359
+ const content = () => {
360
+ if (record.name === "children") return given;
361
+ const fn = typeof given === "function" ? untrack(given) : given;
362
+ if (typeof fn !== "function") return fn ?? null;
363
+ const props = {};
364
+ for (const key of Object.keys(untrack(args))) props[key] = () => args()[key];
365
+ if (region !== null) {
366
+ const placed = region;
367
+ props.children = block(() => placed);
368
+ }
369
+ return untrack(() => fn(props));
370
+ };
371
+ const range = {
372
+ open: start,
373
+ close: end,
374
+ parent,
375
+ nodes: served
376
+ };
377
+ const dispose = claiming ? runWithOwner(site.owner, () => createRoot((release) => {
378
+ withRange(range, () => {
379
+ const value = content();
380
+ return typeof value === "function" ? value(getOwner()) : value;
381
+ });
382
+ return release;
383
+ })) : withoutClaim(() => runWithOwner(site.owner, () => createRoot((release) => {
384
+ insert(parent, content(), end);
385
+ return release;
386
+ })));
387
+ return {
388
+ key: record.key,
389
+ name: record.name,
390
+ start,
391
+ end,
392
+ region,
393
+ setArgs,
394
+ dispose
395
+ };
396
+ }
397
+ /** Fill every slot in the mount that has no content yet, outermost first. */
398
+ function fillAll(site, payload) {
399
+ for (;;) {
400
+ const start = unfilled(site.host, site.occurrences);
401
+ if (start === null) return;
402
+ const record = recordAt(payload, slotIndex(start.data));
403
+ const occurrence = record === void 0 ? null : fill(site, start, record);
404
+ site.occurrences.set(start, occurrence ?? DEAD);
405
+ }
406
+ }
407
+ const DEAD = {
408
+ key: "",
409
+ name: "",
410
+ start: null,
411
+ end: null,
412
+ region: null,
413
+ setArgs: () => {},
414
+ dispose: () => {}
415
+ };
416
+ function mount(state, props) {
417
+ const owner = getOwner();
418
+ const host = element(FRAME_TAG, {});
419
+ const adopted = host.getAttribute("data-frame") === state.ref.address && payloadOf(host) !== null;
420
+ if (!adopted) withoutClaim(() => {
421
+ host.setAttribute("data-frame", state.ref.address);
422
+ host.setAttribute("style", "display:contents");
423
+ host.innerHTML = `<script type="${PAYLOAD_TYPE}"><\/script>${state.markup ?? markupOnPage(state) ?? ""}`;
424
+ if (state.payload !== null) setPayload(host, state.payload);
425
+ });
426
+ state.payload ??= payloadOf(host);
427
+ const payload = state.payload ?? {
428
+ v: 1,
429
+ slots: [],
430
+ head: []
431
+ };
432
+ if (untrack(state.head).length === 0 && payload.head.length > 0) state.setHead(payload.head);
433
+ const placed = {
434
+ host,
435
+ owner,
436
+ props,
437
+ occurrences: /* @__PURE__ */ new Map(),
438
+ bindings: /* @__PURE__ */ new Map(),
439
+ claiming: adopted && isHydrating()
440
+ };
441
+ fillAll(placed, payload);
442
+ bindAll(placed, payload);
443
+ placed.claiming = false;
444
+ state.mounts.add(placed);
445
+ useHead(() => state.head());
446
+ if (adopted) onHydrationEnd(() => connect(state));
447
+ onCleanup(() => {
448
+ state.mounts.delete(placed);
449
+ for (const occurrence of placed.occurrences.values()) occurrence.dispose();
450
+ for (const binding of placed.bindings.values()) binding.dispose();
451
+ if (state.mounts.size === 0) state.connection?.stop();
452
+ });
453
+ return host;
454
+ }
455
+ /**
456
+ * A frame the page carries but this mount was not claimed over: one that
457
+ * rendered on the server and is mounted again after the page started, from a
458
+ * seed that named it. Its markup is taken from the page.
459
+ */
460
+ function markupOnPage(state) {
461
+ for (const candidate of document.querySelectorAll(FRAME_TAG)) {
462
+ if (candidate.getAttribute("data-frame") !== state.ref.address) continue;
463
+ state.payload ??= payloadOf(candidate);
464
+ const copy = candidate.cloneNode(true);
465
+ copy.firstElementChild?.remove();
466
+ for (const comment of commentsIn(copy)) {
467
+ if (slotIndex(comment.data) === -1) continue;
468
+ const end = closeOf(comment);
469
+ if (end !== null) for (const node of between(comment, end)) node.parentNode?.removeChild(node);
470
+ }
471
+ return copy.innerHTML;
472
+ }
473
+ return null;
474
+ }
475
+ /** Every comment in `root`, collected before the caller changes the tree around them. */
476
+ function commentsIn(root) {
477
+ const walker = (root.ownerDocument ?? document).createTreeWalker(root, NodeFilter.SHOW_COMMENT);
478
+ const out = [];
479
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) out.push(node);
480
+ return out;
481
+ }
482
+ /** The page's fill for a binding slot, run once: the object whose properties fill its positions. */
483
+ function bindOccurrence(site, record) {
484
+ const [args, setArgs] = createSignal(record.args === void 0 ? {} : decodeWire(record.args), { ownedWrite: true });
485
+ const given = site.props[record.name];
486
+ return runWithOwner(site.owner, () => createRoot((dispose) => {
487
+ const props = {};
488
+ for (const key of Object.keys(untrack(args))) props[key] = () => args()[key];
489
+ const result = withoutClaim(() => untrack(() => {
490
+ const fn = typeof given === "function" ? given() : given;
491
+ return typeof fn === "function" ? fn(props) : fn;
492
+ }));
493
+ let values = null;
494
+ if (typeof result === "object" && result !== null && !Array.isArray(result) && !(result instanceof Node)) values = result;
495
+ else if (given !== void 0) console.error(`[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. 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.`);
496
+ const binding = {
497
+ name: record.name,
498
+ owner: getOwner(),
499
+ values,
500
+ setArgs,
501
+ positions: /* @__PURE__ */ new Map(),
502
+ dispose: () => {
503
+ for (const at of binding.positions.values()) for (const release of at.values()) release();
504
+ binding.positions.clear();
505
+ dispose();
506
+ }
507
+ };
508
+ return binding;
509
+ }));
510
+ }
511
+ /** Every position marked in `root`, a nested frame's aside, in document order. */
512
+ function positionsIn(root) {
513
+ const out = [];
514
+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT, { acceptNode: (node) => node !== root && node.nodeType === 1 && node.localName === "barq-frame" ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT });
515
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
516
+ if (node.nodeType === 8) {
517
+ const entry = bindTextEntry(node.data);
518
+ if (entry !== null) out.push({
519
+ node,
520
+ position: "",
521
+ entry
522
+ });
523
+ continue;
524
+ }
525
+ const element = node;
526
+ for (const name of element.getAttributeNames()) {
527
+ if (!name.startsWith("_b-")) continue;
528
+ const position = name.slice(3);
529
+ for (const entry of bindEntries(element.getAttribute(name) ?? "")) out.push({
530
+ node,
531
+ position,
532
+ entry
533
+ });
534
+ }
535
+ }
536
+ return out;
537
+ }
538
+ /**
539
+ * Bring the binding slot occurrences up to date with a payload: a new one's
540
+ * fill runs, a kept one's arguments move and its fill is not run again, and
541
+ * each position in the markup is bound once, a position the morph replaced or
542
+ * dropped released.
543
+ */
544
+ function bindAll(site, payload) {
545
+ const byAt = /* @__PURE__ */ new Map();
546
+ const next = /* @__PURE__ */ new Map();
547
+ for (const record of payload.slots) {
548
+ if (record.bind !== true) continue;
549
+ let binding = site.bindings.get(record.key);
550
+ if (binding !== void 0 && binding.name === record.name) {
551
+ if (record.args !== void 0) binding.setArgs(decodeWire(record.args));
552
+ } else binding = bindOccurrence(site, record);
553
+ next.set(record.key, binding);
554
+ byAt.set(record.at, binding);
555
+ }
556
+ for (const [key, binding] of site.bindings) if (next.get(key) !== binding) binding.dispose();
557
+ site.bindings = next;
558
+ if (next.size === 0) return;
559
+ const seen = /* @__PURE__ */ new Map();
560
+ for (const found of positionsIn(site.host)) {
561
+ const binding = byAt.get(found.entry.at);
562
+ if (binding === void 0 || binding.values === null) continue;
563
+ const id = `${found.position}|${found.entry.key}|${found.entry.member ?? ""}`;
564
+ let nodes = seen.get(binding);
565
+ if (nodes === void 0) seen.set(binding, nodes = /* @__PURE__ */ new Map());
566
+ let ids = nodes.get(found.node);
567
+ if (ids === void 0) nodes.set(found.node, ids = /* @__PURE__ */ new Set());
568
+ ids.add(id);
569
+ let at = binding.positions.get(found.node);
570
+ if (at === void 0) binding.positions.set(found.node, at = /* @__PURE__ */ new Map());
571
+ if (at.has(id)) continue;
572
+ const claiming = site.claiming;
573
+ const values = binding.values;
574
+ at.set(id, runWithOwner(binding.owner, () => createRoot((release) => {
575
+ bindPosition(found, values, claiming);
576
+ return release;
577
+ })));
578
+ }
579
+ for (const binding of next.values()) {
580
+ const nodes = seen.get(binding);
581
+ for (const [node, at] of binding.positions) {
582
+ const ids = nodes?.get(node);
583
+ for (const [id, release] of at) {
584
+ if (ids?.has(id) === true) continue;
585
+ release();
586
+ at.delete(id);
587
+ }
588
+ if (at.size === 0) binding.positions.delete(node);
589
+ }
590
+ }
591
+ }
592
+ function textOf(value) {
593
+ return typeof value === "string" ? value : typeof value === "number" || typeof value === "bigint" ? String(value) : "";
594
+ }
595
+ /**
596
+ * A detached element for the style a claimed position already shows: what
597
+ * `setStyle` would have applied, without writing to the page's element.
598
+ */
599
+ let scratch = null;
600
+ /**
601
+ * Fill one position from the fill's object. A value position follows the
602
+ * property, a handler and a ref are read once, as the page's own JSX reads
603
+ * them. While the page is claimed the server already wrote each value, so the
604
+ * first run writes nothing.
605
+ */
606
+ function bindPosition(found, values, claiming) {
607
+ const { node, position, entry } = found;
608
+ const read = () => values[entry.key];
609
+ if (position === "") {
610
+ const start = node;
611
+ let text;
612
+ if (start.nextSibling !== null && start.nextSibling.nodeType === 3) text = start.nextSibling;
613
+ else {
614
+ text = document.createTextNode("");
615
+ start.parentNode?.insertBefore(text, start.nextSibling);
616
+ }
617
+ createRenderEffect(() => textOf(read()), (value) => {
618
+ if (text.data !== value) text.data = value;
619
+ });
620
+ return;
621
+ }
622
+ const element = node;
623
+ if (position === "ref") {
624
+ ref(element, untrack(read));
625
+ return;
626
+ }
627
+ if (position.startsWith("on-")) {
628
+ const type = position.slice(3);
629
+ const capture = entry.member === "capture";
630
+ bindEvent(element, type, untrack(read), capture);
631
+ if (!capture) onCleanup(() => delegate(element, type, void 0));
632
+ return;
633
+ }
634
+ if (position === "class" && entry.member !== void 0) {
635
+ const name = entry.member;
636
+ createRenderEffect(() => Boolean(read()), (on) => {
637
+ if (element.classList.contains(name) !== on) element.classList.toggle(name, on);
638
+ });
639
+ return;
640
+ }
641
+ let applied;
642
+ let first = claiming;
643
+ if (position === "style") {
644
+ const member = entry.member;
645
+ createRenderEffect(() => member === void 0 ? read() : { [member]: read() }, (value) => {
646
+ if (first) {
647
+ first = false;
648
+ scratch ??= document.createElement("div");
649
+ scratch.removeAttribute("style");
650
+ applied = setStyle(scratch, "style", value);
651
+ return;
652
+ }
653
+ applied = setStyle(element, "style", value, applied);
654
+ });
655
+ return;
656
+ }
657
+ if (position === "class") {
658
+ createRenderEffect(read, (value) => {
659
+ if (first) {
660
+ first = false;
661
+ applied = classToString(value);
662
+ return;
663
+ }
664
+ applied = setClass(element, "class", value, applied);
665
+ });
666
+ return;
667
+ }
668
+ createRenderEffect(read, (value) => {
669
+ if (first) {
670
+ first = false;
671
+ return;
672
+ }
673
+ setProp(element, position, value);
674
+ });
675
+ }
676
+ function sameNode(current, next) {
677
+ if (current.nodeType !== next.nodeType) return false;
678
+ if (current.nodeType !== 1) return true;
679
+ const a = current;
680
+ const b = next;
681
+ return a.localName === b.localName && a.getAttribute("id") === b.getAttribute("id");
682
+ }
683
+ /**
684
+ * The positions of an element a binding slot fills, by its markers: whole
685
+ * attributes, and the class names and style properties it fills in object form.
686
+ */
687
+ function ownedBy(element) {
688
+ const owned = {
689
+ whole: /* @__PURE__ */ new Set(),
690
+ classes: /* @__PURE__ */ new Set(),
691
+ styles: /* @__PURE__ */ new Set()
692
+ };
693
+ for (const name of element.getAttributeNames()) {
694
+ if (!name.startsWith("_b-")) continue;
695
+ const position = name.slice(3);
696
+ if (position === "ref" || position.startsWith("on-")) continue;
697
+ for (const entry of bindEntries(element.getAttribute(name) ?? "")) if (entry.member === void 0) owned.whole.add(position);
698
+ else if (position === "class") owned.classes.add(entry.member);
699
+ else if (position === "style") owned.styles.add(entry.member);
700
+ }
701
+ return owned;
702
+ }
703
+ /**
704
+ * The server's attributes, written over the element's, except where the page
705
+ * fills a position: a whole attribute it fills is left as it stands, and the
706
+ * class names and style properties it fills keep their current state inside
707
+ * the server's new class and style.
708
+ */
709
+ function patchAttributes(current, next) {
710
+ const owned = ownedBy(next);
711
+ const classes = owned.classes.size > 0;
712
+ const styles = owned.styles.size > 0;
713
+ for (const name of current.getAttributeNames()) {
714
+ if (owned.whole.has(name) || name === "class" && classes || name === "style" && styles) continue;
715
+ if (!next.hasAttribute(name)) current.removeAttribute(name);
716
+ }
717
+ for (const name of next.getAttributeNames()) {
718
+ if (owned.whole.has(name) || name === "class" && classes || name === "style" && styles) continue;
719
+ const value = next.getAttribute(name) ?? "";
720
+ if (current.getAttribute(name) !== value) current.setAttribute(name, value);
721
+ }
722
+ if (classes) {
723
+ const tokens = new Set((next.getAttribute("class") ?? "").split(/\s+/).filter(Boolean));
724
+ for (const name of owned.classes) if (current.classList.contains(name)) tokens.add(name);
725
+ else tokens.delete(name);
726
+ const value = [...tokens].join(" ");
727
+ if ((current.getAttribute("class") ?? "") !== value) current.setAttribute("class", value);
728
+ }
729
+ if (styles) {
730
+ const style = current.style;
731
+ const kept = /* @__PURE__ */ new Map();
732
+ for (const property of owned.styles) {
733
+ const css = cssProperty(property);
734
+ kept.set(css, style.getPropertyValue(css));
735
+ }
736
+ const value = next.getAttribute("style");
737
+ if (current.getAttribute("style") !== value) {
738
+ if (value === null) current.removeAttribute("style");
739
+ else current.setAttribute("style", value);
740
+ for (const [css, text] of kept) if (text === "") style.removeProperty(css);
741
+ else style.setProperty(css, text);
742
+ }
743
+ }
744
+ }
745
+ /** A style object's key as the declaration's name, as `setStyle` writes it. */
746
+ function cssProperty(property) {
747
+ return property.startsWith("--") ? property : property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
748
+ }
749
+ function isTextEnd(node) {
750
+ return node !== null && node.nodeType === 8 && node.data === "/_b";
751
+ }
752
+ function occurrenceAt(context, node) {
753
+ if (node === null || node.nodeType !== 8) return null;
754
+ const found = context.mount.occurrences.get(node);
755
+ return found === void 0 || found === DEAD ? null : found;
756
+ }
757
+ /** Move an occurrence's whole range, markers and content, to stand before `before`. */
758
+ function place(occurrence, parent, before) {
759
+ const nodes = [
760
+ occurrence.start,
761
+ ...between(occurrence.start, occurrence.end),
762
+ occurrence.end
763
+ ];
764
+ for (const node of nodes) parent.insertBefore(node, before);
765
+ }
766
+ function morphChildren(current, next, context) {
767
+ let cursor = current.firstChild;
768
+ if (isPayload(cursor)) cursor = cursor.nextSibling;
769
+ const incoming = [...next.childNodes];
770
+ for (let at = 0; at < incoming.length; at++) {
771
+ const node = incoming[at];
772
+ for (let standing = occurrenceAt(context, cursor); standing !== null;) {
773
+ cursor = standing.end.nextSibling;
774
+ standing = occurrenceAt(context, cursor);
775
+ }
776
+ const opening = node.nodeType === 8 ? slotIndex(node.data) : -1;
777
+ if (opening !== -1) {
778
+ let close = at + 1;
779
+ while (close < incoming.length) {
780
+ const candidate = incoming[close];
781
+ if (candidate.nodeType === 8 && slotEnd(candidate.data) === opening) break;
782
+ close++;
783
+ }
784
+ at = close;
785
+ const record = recordAt(context.payload, opening);
786
+ const kept = record === void 0 ? void 0 : context.keep.get(record.key);
787
+ if (kept !== void 0 && kept.name === record.name) {
788
+ context.keep.delete(kept.key);
789
+ context.used.add(kept);
790
+ if (kept.start.nextSibling !== cursor || kept.start.parentNode !== current) place(kept, current, cursor);
791
+ kept.start.data = slotOpen(opening);
792
+ kept.end.data = slotClose(opening);
793
+ continue;
794
+ }
795
+ current.insertBefore(document.createComment(slotOpen(opening)), cursor);
796
+ current.insertBefore(document.createComment(slotClose(opening)), cursor);
797
+ continue;
798
+ }
799
+ if (node.nodeType === 8 && bindTextEntry(node.data) !== null && cursor !== null && cursor.nodeType === 8 && cursor.data === node.data) {
800
+ while (at + 1 < incoming.length && !isTextEnd(incoming[at])) at++;
801
+ let end = cursor.nextSibling;
802
+ while (end !== null && !isTextEnd(end)) end = end.nextSibling;
803
+ cursor = end === null ? null : end.nextSibling;
804
+ continue;
805
+ }
806
+ if (cursor !== null && sameNode(cursor, node)) {
807
+ if (cursor.nodeType === 1) {
808
+ patchAttributes(cursor, node);
809
+ morphChildren(cursor, node, context);
810
+ } else if (cursor.nodeValue !== node.nodeValue) cursor.nodeValue = node.nodeValue;
811
+ cursor = cursor.nextSibling;
812
+ continue;
813
+ }
814
+ current.insertBefore(document.importNode(node, true), cursor);
815
+ }
816
+ while (cursor !== null) {
817
+ const standing = occurrenceAt(context, cursor);
818
+ if (standing !== null) {
819
+ cursor = standing.end.nextSibling;
820
+ continue;
821
+ }
822
+ const gone = cursor;
823
+ cursor = cursor.nextSibling;
824
+ current.removeChild(gone);
825
+ }
826
+ }
827
+ /** Apply a new answer to one mount: morph the region, then bring the occurrences up to date. */
828
+ function update(site, payload, markup) {
829
+ const next = document.createElement("template");
830
+ next.innerHTML = markup;
831
+ const keep = /* @__PURE__ */ new Map();
832
+ for (const occurrence of site.occurrences.values()) if (occurrence !== DEAD) keep.set(occurrence.key, occurrence);
833
+ const context = {
834
+ mount: site,
835
+ payload,
836
+ keep,
837
+ used: /* @__PURE__ */ new Set()
838
+ };
839
+ withoutClaim(() => {
840
+ morphChildren(site.host, next.content, context);
841
+ setPayload(site.host, payload);
842
+ });
843
+ const occurrences = /* @__PURE__ */ new Map();
844
+ for (const occurrence of context.used) {
845
+ occurrences.set(occurrence.start, occurrence);
846
+ const record = recordAt(payload, slotIndex(occurrence.start.data));
847
+ if (record === void 0) continue;
848
+ if (record.args !== void 0) occurrence.setArgs(decodeWire(record.args));
849
+ if (occurrence.region !== null && record.region !== void 0) {
850
+ const region = document.createElement("template");
851
+ region.innerHTML = record.region;
852
+ withoutClaim(() => morphChildren(occurrence.region, region.content, context));
853
+ for (const nested of context.used) occurrences.set(nested.start, nested);
854
+ }
855
+ }
856
+ for (const occurrence of site.occurrences.values()) {
857
+ if (occurrence === DEAD || context.used.has(occurrence)) continue;
858
+ occurrence.dispose();
859
+ for (const node of [
860
+ occurrence.start,
861
+ ...between(occurrence.start, occurrence.end),
862
+ occurrence.end
863
+ ]) node.parentNode?.removeChild(node);
864
+ }
865
+ site.occurrences.clear();
866
+ for (const [start, occurrence] of occurrences) site.occurrences.set(start, occurrence);
867
+ fillAll(site, payload);
868
+ bindAll(site, payload);
869
+ }
870
+ /**
871
+ * The region's stylesheets, loaded before it is shown: a region revealed
872
+ * before its styles is the flash a server render exists to prevent. Each is
873
+ * the element `useHead` takes over when the frame mounts.
874
+ */
875
+ async function loadStylesheets(head) {
876
+ const loading = [];
877
+ for (const tag of head) {
878
+ const props = tag.props ?? {};
879
+ if (tag.tag !== "link" || props.rel !== "stylesheet" || typeof props.href !== "string") continue;
880
+ const key = `link:stylesheet:${props.href}`;
881
+ let present = false;
882
+ for (const candidate of document.head.querySelectorAll("[data-bh]")) if (candidate.getAttribute("data-bh") === key) present = true;
883
+ if (present) continue;
884
+ const link = document.createElement("link");
885
+ link.rel = "stylesheet";
886
+ link.href = props.href;
887
+ link.setAttribute("data-bh", key);
888
+ loading.push(new Promise((resolve) => {
889
+ link.addEventListener("load", () => resolve(), { once: true });
890
+ link.addEventListener("error", () => resolve(), { once: true });
891
+ }));
892
+ const atoms = document.head.querySelector("link[rel=\"stylesheet\"][data-barq-atoms]");
893
+ if (atoms === null) document.head.appendChild(link);
894
+ else atoms.before(link);
895
+ }
896
+ await Promise.all(loading);
897
+ }
898
+ /**
899
+ * Read a frame answer and apply it: the component for its address, the same
900
+ * one every time, with every place it is mounted morphed to the new markup
901
+ * once the region's stylesheets have loaded.
902
+ */
903
+ async function applyFrameResponse(response) {
904
+ const template = document.createElement("template");
905
+ template.innerHTML = await response.text();
906
+ return applyFrameMarkup(template.content.firstElementChild);
907
+ }
908
+ /** A frame's markup as text, a live event's, applied as a frame answer is. */
909
+ function applyFrameText(markup) {
910
+ const template = document.createElement("template");
911
+ template.innerHTML = markup;
912
+ return applyFrameMarkup(template.content.firstElementChild);
913
+ }
914
+ /** One frame's markup, applied to every place its address is mounted. */
915
+ async function applyFrameMarkup(host) {
916
+ const address = host?.getAttribute("data-frame") ?? null;
917
+ const payload = host === null ? null : payloadOf(host);
918
+ if (host === null || address === null || payload === null) throw new Error("[barq] A server function answered with a frame whose markup has no `barq-frame` element and payload, so there is nothing to apply. The server and this page were built from different versions: reload the page.");
919
+ if (payload.v !== 1) throw new Error(`[barq] A server function answered with frame version ${payload.v}, and this page reads version 1. The server was deployed after this page loaded: reload the page.`);
920
+ host.firstElementChild?.remove();
921
+ const markup = host.innerHTML;
922
+ const state = stateFor({
923
+ id: address.slice(0, address.lastIndexOf("#")),
924
+ address
925
+ });
926
+ await loadStylesheets(payload.head);
927
+ state.payload = payload;
928
+ state.markup = markup;
929
+ state.setHead(payload.head);
930
+ for (const placed of state.mounts) update(placed, payload, markup);
931
+ document.dispatchEvent(new CustomEvent(FRAME_APPLIED_EVENT, { detail: { address } }));
932
+ return state.component;
933
+ }
934
+ /**
935
+ * What a mutation sends so its answer can carry the regions it changed: every
936
+ * mounted frame's function and arguments, up to the budget, or `null` with
937
+ * none mounted.
938
+ */
939
+ function mountedFramesHeader() {
940
+ const out = [];
941
+ for (const state of FRAMES.values()) {
942
+ if (state.mounts.size === 0 || state.payload === null) continue;
943
+ out.push({
944
+ id: state.ref.id,
945
+ args: state.payload.args
946
+ });
947
+ if (out.length === 32) break;
948
+ }
949
+ return out.length === 0 ? null : JSON.stringify(out);
950
+ }
951
+ /**
952
+ * A mutation's single-flight answer: each region it carries applied where it
953
+ * is mounted, then the value, which is what the caller is handed.
954
+ */
955
+ async function applyFlight(response) {
956
+ const template = document.createElement("template");
957
+ template.innerHTML = await response.text();
958
+ const script = template.content.firstElementChild;
959
+ if (script === null || script.localName !== "script" || script.getAttribute("type") !== "application/barq-flight") throw new Error("[barq] A server function answered with a single flight whose value script is missing, so there is no value to hand the caller. The server and this page were built from different versions: reload the page.");
960
+ const value = decodeWire(JSON.parse(script.textContent ?? "null"));
961
+ for (const host of template.content.children) if (host.localName === "barq-frame") await applyFrameMarkup(host);
962
+ return value;
963
+ }
964
+ /** The events of a `text/event-stream` body, as the spec frames them. */
965
+ async function* eventsOf(body) {
966
+ const reader = body.getReader();
967
+ const decoder = new TextDecoder();
968
+ let pending = "";
969
+ let event = "message";
970
+ let id = null;
971
+ let data = [];
972
+ try {
973
+ for (;;) {
974
+ const { done, value } = await reader.read();
975
+ pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
976
+ let end = pending.search(/\r\n|\r|\n/);
977
+ while (end !== -1) {
978
+ const line = pending.slice(0, end);
979
+ pending = pending.slice(end + (pending.startsWith("\r\n", end) ? 2 : 1));
980
+ if (line === "") {
981
+ if (data.length > 0 || event !== "message") yield {
982
+ event,
983
+ id,
984
+ data: data.join("\n")
985
+ };
986
+ event = "message";
987
+ data = [];
988
+ } else if (!line.startsWith(":")) {
989
+ const colon = line.indexOf(":");
990
+ const field = colon === -1 ? line : line.slice(0, colon);
991
+ const text = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
992
+ if (field === "data") data.push(text);
993
+ else if (field === "event") event = text;
994
+ else if (field === "id") id = text;
995
+ }
996
+ end = pending.search(/\r\n|\r|\n/);
997
+ }
998
+ if (done) return;
999
+ }
1000
+ } finally {
1001
+ reader.cancel().catch(() => {});
1002
+ }
1003
+ }
1004
+ /** Statuses that say "ask again" even though they refuse this time. */
1005
+ const RETRY = /* @__PURE__ */ new Set([
1006
+ 408,
1007
+ 425,
1008
+ 429
1009
+ ]);
1010
+ /** How long to wait before the next connection, the nth failure in a row. */
1011
+ function pause(failures, signal) {
1012
+ const ms = Math.min(3e4, 250 * 2 ** failures);
1013
+ return new Promise((resolve) => {
1014
+ const timer = setTimeout(done, ms);
1015
+ function done() {
1016
+ clearTimeout(timer);
1017
+ globalThis.removeEventListener?.("online", done);
1018
+ signal.removeEventListener("abort", done);
1019
+ resolve();
1020
+ }
1021
+ globalThis.addEventListener?.("online", done, { once: true });
1022
+ signal.addEventListener("abort", done, { once: true });
1023
+ });
1024
+ }
1025
+ /** The reconnecting iteration of one live call. */
1026
+ function liveIterable(stub, options) {
1027
+ const iterable = { [Symbol.asyncIterator]: () => {
1028
+ const controller = new AbortController();
1029
+ const running = loop(stub, options, iterable, controller);
1030
+ return {
1031
+ next: () => running.next(),
1032
+ return: (value) => {
1033
+ controller.abort();
1034
+ return running.return(value);
1035
+ }
1036
+ };
1037
+ } };
1038
+ return iterable;
1039
+ }
1040
+ async function* loop(stub, options, told, controller) {
1041
+ let lastEventId = null;
1042
+ let failures = 0;
1043
+ let connected = false;
1044
+ try {
1045
+ for (;;) {
1046
+ let response;
1047
+ try {
1048
+ response = await stub[LIVE_CALL](options, {
1049
+ lastEventId,
1050
+ signal: controller.signal
1051
+ });
1052
+ } catch (error) {
1053
+ if (controller.signal.aborted) return;
1054
+ if (!connected) throw error;
1055
+ told.onstatus?.("reconnecting", error);
1056
+ await pause(failures++, controller.signal);
1057
+ continue;
1058
+ }
1059
+ if (!response.ok || response.body === null) {
1060
+ const retries = RETRY.has(response.status) || response.headers.has("retry-after");
1061
+ const error = new ServerFnError(stub.meta.id, response.status, response);
1062
+ if (!connected || !retries && response.status >= 400 && response.status < 500) throw error;
1063
+ told.onstatus?.("reconnecting", error);
1064
+ await pause(failures++, controller.signal);
1065
+ continue;
1066
+ }
1067
+ connected = true;
1068
+ failures = 0;
1069
+ told.onstatus?.("connected");
1070
+ let yielded = void 0;
1071
+ let complete = false;
1072
+ let died = /* @__PURE__ */ new Error(`[barq] The live connection of ${JSON.stringify(stub.meta.id)} ended before it was complete.`);
1073
+ try {
1074
+ for await (const event of eventsOf(response.body)) {
1075
+ if (event.event === "complete") {
1076
+ complete = true;
1077
+ break;
1078
+ }
1079
+ if (event.id !== null) lastEventId = event.id;
1080
+ const data = JSON.parse(event.data);
1081
+ if (event.event === "frame") {
1082
+ const component = await applyFrameText(data);
1083
+ if (component !== yielded) {
1084
+ yielded = component;
1085
+ yield component;
1086
+ }
1087
+ continue;
1088
+ }
1089
+ yield decodeWire(data);
1090
+ }
1091
+ } catch (error) {
1092
+ died = error;
1093
+ }
1094
+ if (complete || controller.signal.aborted) return;
1095
+ told.onstatus?.("reconnecting", died);
1096
+ await pause(failures++, controller.signal);
1097
+ }
1098
+ } finally {
1099
+ controller.abort();
1100
+ told.onstatus?.("closed");
1101
+ }
1102
+ }
1103
+ // src/start-instance.ts
1104
+ /**
1105
+ * The application-wide middleware, declared once.
1106
+ *
1107
+ * TanStack Start's `createStart`, written in a project's `src/start.ts`:
1108
+ *
1109
+ * ```ts
1110
+ * export const startInstance = createStart(() => ({
1111
+ * requestMiddleware: [logging],
1112
+ * functionMiddleware: [requireSession],
1113
+ * }));
1114
+ * ```
1115
+ *
1116
+ * Its own module, importing nothing that reaches `node:async_hooks`, because
1117
+ * the client stub reads it: a global function middleware's client half runs in
1118
+ * the browser around every call.
1119
+ */
1120
+ /**
1121
+ * One instance for the process, whichever copy of this module asks.
1122
+ *
1123
+ * It is configuration, fixed once the application has loaded, so it has none
1124
+ * of the hazards an ambient request would: nothing a visitor does changes it.
1125
+ * On the global registry for the reason the server-function registry is: a
1126
+ * build compiles this module into its server bundle, and a host serving that
1127
+ * bundle through its own `serveBarq` has imported a second copy.
1128
+ */
1129
+ const REGISTERED = globalThis[Symbol.for("barq.start.instance")] ??= { instance: null };
1130
+ const NONE = Object.freeze({});
1131
+ /**
1132
+ * Declare the application's global middleware.
1133
+ *
1134
+ * The function is called once, the first time anything asks, so a middleware
1135
+ * module that imports this one back is fully evaluated by then.
1136
+ */
1137
+ function createStart(options) {
1138
+ let resolved;
1139
+ const instance = { getOptions: () => {
1140
+ if (resolved === void 0) {
1141
+ resolved = options();
1142
+ if (resolved.serializationAdapters !== void 0) registerSerializationAdapters(resolved.serializationAdapters);
1143
+ }
1144
+ return resolved;
1145
+ } };
1146
+ REGISTERED.instance = instance;
1147
+ return instance;
1148
+ }
1149
+ /** What the application declared, or nothing. */
1150
+ function startOptions() {
1151
+ return REGISTERED.instance?.getOptions() ?? NONE;
1152
+ }
1153
+ /** Test seam. Not for application use. */
1154
+ function clearStart() {
1155
+ REGISTERED.instance = null;
1156
+ }
1157
+ // src/live-client.ts
1158
+ /** Whether a server function is the server half, which runs in this process. */
1159
+ function inProcess(fn) {
1160
+ return typeof fn === "function" && "built" in fn;
1161
+ }
1162
+ /**
1163
+ * Declare a server function's answer a standing one. In the browser, calling
1164
+ * the result returns an iterable that stays connected; on the server it is the
1165
+ * call itself, a frame it answers with marked for the page to connect.
1166
+ */
1167
+ function live(fn) {
1168
+ if (inProcess(fn)) return ((...args) => fn(...args).then((answer) => {
1169
+ const frame = typeof answer === "function" ? answer[FRAME] : void 0;
1170
+ if (frame !== void 0) frame.live = true;
1171
+ return answer;
1172
+ }));
1173
+ return ((options) => liveIterable(fn, options));
1174
+ }
1175
+ // src/client.ts
1176
+ /**
1177
+ * The client half of a server function, and NOTHING the server half needs.
1178
+ *
1179
+ * Its own module because of what importing it costs. The compiler replaces a
1180
+ * server-function module's contents with `export const x = clientRpc("<id>")`,
1181
+ * and that stub used to import from `@barqjs/start` — whose index re-exports
1182
+ * `context.ts`, which is `node:async_hooks`. Every client bundle that reached
1183
+ * one server function therefore pulled the request-context machinery, the
1184
+ * middleware runner, the validators and the error classes, and Vite printed
1185
+ * "node:async_hooks has been externalized for browser compatibility" on every
1186
+ * build.
1187
+ *
1188
+ * That was survivable while a route module was `lazy()`, because the cost sat
1189
+ * in that route's own chunk. It stopped being survivable when `routeTree.gen.ts`
1190
+ * started importing route modules STATICALLY: measured on
1191
+ * `packages/kitchen-sink`, 25.7 kB of it moved into the set every page
1192
+ * preloads, for an application with two server functions on one route.
1193
+ *
1194
+ * So the stub imports from here. `index.ts` re-exports every name below, so an
1195
+ * application still writes `import { createServerFn } from "@barqjs/start"` and
1196
+ * nothing about the authoring surface changes.
1197
+ */
1198
+ const SERVER_FN = Symbol.for("barq.server-fn");
1199
+ /** Where mounted server functions answer. */
1200
+ const RPC_PREFIX = "/_barq/fn/";
1201
+ /**
1202
+ * What distinguishes an RPC call from a form submission: the URL, not a header.
1203
+ *
1204
+ * `/_barq/fn/<id>` is what `<form action={fn}>` writes, takes `FormData`, and
1205
+ * answers with a redirect a browser can follow with JS disabled.
1206
+ * `/_barq/fn/<id>.data` is the JSON channel and answers with a value.
1207
+ *
1208
+ * React Router's `.data` suffix, and the reason is its reason: a header decides
1209
+ * the response shape invisibly, and a form cannot set one. RedwoodSDK shows the
1210
+ * failure — it emits the right hidden fields for a no-JS submit and never reads
1211
+ * them, so the form posts, returns 200, and nothing happens.
1212
+ */
1213
+ const DATA_SUFFIX = ".data";
1214
+ /**
1215
+ * `/_barq/fn/<id>.live` is the live address: the data address's answer, framed
1216
+ * as server-sent events for as long as it stands. Its own URL, because a cache
1217
+ * keys on the URL and not on a header nothing tells it to vary by.
1218
+ */
1219
+ const LIVE_SUFFIX = ".live";
1220
+ /**
1221
+ * How the data channel says "the answer is an instruction, not a value".
1222
+ *
1223
+ * A HEADER rather than a body sniff, so a caller that does not care never
1224
+ * parses the body to find out, and so a handler returning a plain object that
1225
+ * happens to have a `to` field is never mistaken for a redirect.
1226
+ */
1227
+ const RPC_CONTROL = "x-barq-rpc";
1228
+ /**
1229
+ * The {@link RPC_CONTROL} value for a `Response` the handler returned.
1230
+ *
1231
+ * The response IS the result then, and its body is whatever the handler wrote,
1232
+ * so the stub hands it back whole rather than reading it as a wire value. No
1233
+ * body rides under this one, which is why it is not an {@link RpcControl} kind.
1234
+ */
1235
+ const RPC_RESPONSE = "response";
1236
+ /**
1237
+ * The {@link RPC_CONTROL} value for a `Response` a handler, a validator or a
1238
+ * middleware THREW: the call rejects with that response itself, as TanStack's
1239
+ * does. Its body and status are what the author wrote for the caller.
1240
+ */
1241
+ const RPC_THROWN = "thrown";
1242
+ /**
1243
+ * The {@link RPC_CONTROL} value for an answer that arrives over time.
1244
+ *
1245
+ * The body is then one JSON line for each value the function yielded, each
1246
+ * holding a wire-encoded value, and the stub hands the caller an async iterable
1247
+ * of them. A line that says the function failed ends it with a
1248
+ * {@link ServerFnError}.
1249
+ */
1250
+ const RPC_STREAM = "stream";
1251
+ /**
1252
+ * Present when a middleware's `sendContext` rides back with the result.
1253
+ *
1254
+ * A HEADER flagging a different body shape, which is what `RPC_CONTROL` already
1255
+ * does and for the same reason: an ordinary call — every call, in almost every
1256
+ * application — must not pay a second parse or a wrapper object to carry
1257
+ * something it does not have. With the flag the body is `{ result, context }`;
1258
+ * without it the body IS the result, byte for byte as before.
1259
+ */
1260
+ const RPC_CONTEXT = "x-barq-ctx";
1261
+ /**
1262
+ * A redirect that arrived over the wire, rebuilt on the client.
1263
+ *
1264
+ * NOT `@barqjs/router`'s `Redirect` — this package cannot construct that one.
1265
+ * It carries the same brand, so `isRedirect` from the router accepts it and the
1266
+ * router navigates on it exactly as it would on a redirect a loader threw. That
1267
+ * interchangeability is the whole reason those predicates are brand checks
1268
+ * rather than `instanceof`.
1269
+ */
1270
+ var RpcRedirect = class extends Error {
1271
+ [REDIRECT] = true;
1272
+ to;
1273
+ status;
1274
+ statusCode;
1275
+ /**
1276
+ * The navigation an options-form redirect described: `to`, `params`,
1277
+ * `search`, `hash`, `replace`, `reloadDocument`, `href`. The router goes
1278
+ * there in place of `to` when it is present.
1279
+ */
1280
+ options;
1281
+ constructor(to, status, options) {
1282
+ super(`redirect to ${to}`);
1283
+ this.name = "Redirect";
1284
+ this.to = to;
1285
+ this.status = status;
1286
+ this.statusCode = status;
1287
+ this.options = options;
1288
+ }
1289
+ };
1290
+ /** The `notFound()` counterpart, branded for the same reason. */
1291
+ var RpcNotFound = class extends Error {
1292
+ [NOT_FOUND] = true;
1293
+ isNotFound = true;
1294
+ /** What `notFound({ data })` carried, for the `notFoundComponent` that renders this. */
1295
+ data;
1296
+ /** The route whose `notFoundComponent` answers, when the thrower named one. */
1297
+ routeId;
1298
+ constructor(message, data, routeId) {
1299
+ super(message);
1300
+ this.name = "NotFound";
1301
+ this.data = data;
1302
+ this.routeId = routeId;
1303
+ }
1304
+ };
1305
+ /** The JSON a failed call answered with, read from a copy so `error.response` stays unread. */
1306
+ async function failedAnswer(response) {
1307
+ if (!(response.headers.get("content-type") ?? "").includes("application/json")) return void 0;
1308
+ try {
1309
+ return await response.clone().json();
1310
+ } catch {
1311
+ return;
1312
+ }
1313
+ }
1314
+ /**
1315
+ * The request header every GET call the stub makes carries, and is refused
1316
+ * without.
1317
+ *
1318
+ * A link, an `<img>`, a prefetch and a navigation cannot set a header; only
1319
+ * script can, and a cross-origin script that sets one is preflighted and
1320
+ * refused by the origin check. So a `GET` server function stays out of reach
1321
+ * of everything that is not this application's own code, which is the reason
1322
+ * `GET` was once refused outright: a mutation reachable by navigation is a
1323
+ * one-click CSRF carrying `SameSite=Lax` cookies.
1324
+ */
1325
+ const RPC_CALLER = "x-barq-fn";
1326
+ /**
1327
+ * The build a call was bundled with. A server stamped with another build
1328
+ * answers it with a 409 rather than running a function whose arguments or
1329
+ * result may have changed shape under the same id. A GET read does not send
1330
+ * it: its url is its identity to every cache in between.
1331
+ */
1332
+ const BUILD_HEADER = "x-barq-build";
1333
+ /** The build `@barqjs/vite` stamped this bundle with, or none outside a build. */
1334
+ const BUNDLED_BUILD = typeof __BARQ_BUILD__ === "string" ? __BARQ_BUILD__ : void 0;
1335
+ /** Where a GET call's payload rides, since a GET has no body. */
1336
+ const PAYLOAD_PARAM = "payload";
1337
+ /** The form endpoint of a mounted id, or nothing for a function with none. */
1338
+ function urlOf(id) {
1339
+ return id === "" ? "" : RPC_PREFIX + encodeURIComponent(id);
1340
+ }
1341
+ /** The `data` out of a call, whichever of the two shapes it arrived in. */
1342
+ function dataOf(options) {
1343
+ if (options instanceof FormData) return options;
1344
+ if (options === void 0 || options === null) return void 0;
1345
+ return options.data;
1346
+ }
1347
+ /** What a call asked for beside its `data`. A bare `FormData` asks for nothing. */
1348
+ function callOptionsOf(options) {
1349
+ if (options instanceof FormData || options === void 0 || options === null) return void 0;
1350
+ return options;
1351
+ }
1352
+ /**
1353
+ * The client half. The compiler emits this in a module compiled for the client,
1354
+ * with the id, the chain, and nothing else — no handler body, no validator, no
1355
+ * imports the body needed.
1356
+ *
1357
+ * `chain` is the middlewares the function declared, and it is here so a
1358
+ * `.client()` half can run around the fetch. Only the CLIENT halves survive the
1359
+ * compile: `createMiddleware(...).server(fn)` has its `server` argument deleted
1360
+ * in the client build, so a middleware may hold both without the server body —
1361
+ * or the database import it needed — reaching the browser.
1362
+ */
1363
+ function clientRpc(id, declaredChain = [], declared) {
1364
+ const method = declared?.method ?? "POST";
1365
+ const chain = inlineServerFns(declaredChain);
1366
+ let composed = null;
1367
+ const composition = () => {
1368
+ const global = startOptions().functionMiddleware;
1369
+ if (composed === null || composed.from !== global) composed = {
1370
+ from: global,
1371
+ chain: flattenMiddleware([...global ?? [], ...chain])
1372
+ };
1373
+ return composed.chain;
1374
+ };
1375
+ /**
1376
+ * The fetch, as the INNERMOST step of the chain.
1377
+ *
1378
+ * A client middleware therefore wraps the request the way a server one wraps
1379
+ * the handler: it can read what it is about to send, add to `sendContext`,
1380
+ * and see the result on the way back. TanStack reaches the same arrangement
1381
+ * by appending the server function itself to the chain as a middleware.
1382
+ */
1383
+ const send = async (input, sendContext, context, asked, chainHeaders, chainFetch, live) => {
1384
+ const form = input instanceof FormData;
1385
+ if (form && method === "GET") throw new TypeError(`[barq] The server function \`${id}\` answers GET, and a GET has no body to carry a form. Declare it \`createServerFn({ method: "POST" })\` to accept a \`FormData\`.`);
1386
+ const payload = form ? void 0 : JSON.stringify(Object.keys(sendContext).length === 0 ? { input: encodeWire(input) } : {
1387
+ input: encodeWire(input),
1388
+ context: encodeWire(sendContext)
1389
+ });
1390
+ let headers = method === "GET" ? CALLER : form ? void 0 : JSON_BODY;
1391
+ const mountedFrames = method === "POST" && live === void 0 ? mountedFramesHeader() : null;
1392
+ if (mountedFrames !== null) {
1393
+ const withFrames = new Headers(headers);
1394
+ withFrames.set(FRAMES_HEADER, mountedFrames);
1395
+ headers = withFrames;
1396
+ }
1397
+ if (chainHeaders !== void 0 || asked?.headers !== void 0) {
1398
+ const merged = new Headers(chainHeaders);
1399
+ if (mountedFrames !== null) merged.set(FRAMES_HEADER, mountedFrames);
1400
+ if (asked?.headers !== void 0) for (const [name, value] of new Headers(asked.headers)) merged.set(name, value);
1401
+ if (form || method === "GET") merged.delete("content-type");
1402
+ else merged.set("content-type", "application/json");
1403
+ if (method === "GET") merged.set(RPC_CALLER, "1");
1404
+ headers = merged;
1405
+ }
1406
+ if (live !== void 0) {
1407
+ const withPosition = new Headers(headers);
1408
+ if (live.lastEventId !== null) withPosition.set("last-event-id", live.lastEventId);
1409
+ headers = withPosition;
1410
+ }
1411
+ if (BUNDLED_BUILD !== void 0 && method !== "GET") {
1412
+ const withBuild = new Headers(headers);
1413
+ withBuild.set(BUILD_HEADER, BUNDLED_BUILD);
1414
+ headers = withBuild;
1415
+ }
1416
+ const endpoint = RPC_PREFIX + encodeURIComponent(id) + (live === void 0 ? DATA_SUFFIX : LIVE_SUFFIX);
1417
+ const response = await (asked?.fetch ?? chainFetch ?? startOptions().serverFns?.fetch ?? fetch)(method === "GET" ? `${endpoint}?${PAYLOAD_PARAM}=${encodeURIComponent(payload ?? "")}` : endpoint, {
1418
+ method,
1419
+ headers,
1420
+ signal: live?.signal ?? asked?.signal,
1421
+ body: method === "GET" ? void 0 : form ? input : payload,
1422
+ credentials: "same-origin",
1423
+ redirect: "manual"
1424
+ });
1425
+ if (response.type === "opaqueredirect") return response;
1426
+ if (live !== void 0) return response;
1427
+ const control = response.headers.get(RPC_CONTROL);
1428
+ if (control === "response") return response;
1429
+ if (control === "thrown") throw response;
1430
+ if (control === "stream") return received(response, id, context);
1431
+ if (control === "frame") return await applyFrameResponse(response);
1432
+ if (control === "flight") {
1433
+ const flown = await applyFlight(response);
1434
+ if (response.headers.get("x-barq-ctx") === null) return flown;
1435
+ const envelope = flown;
1436
+ if (context !== void 0) Object.assign(context, envelope.context);
1437
+ return envelope.result;
1438
+ }
1439
+ if (control !== null) throw fromControl(await response.json());
1440
+ if (!response.ok) throw new ServerFnError(id, response.status, response, await failedAnswer(response));
1441
+ if (response.headers.get("x-barq-ctx") === null) return decodeWire(await response.json());
1442
+ const envelope = decodeWire(await response.json());
1443
+ if (context !== void 0) Object.assign(context, envelope.context);
1444
+ return envelope.result;
1445
+ };
1446
+ const call = async (options, live) => {
1447
+ const input = dataOf(options);
1448
+ const asked = callOptionsOf(options);
1449
+ const flattened = composition();
1450
+ if (flattened.length === 0) return send(input, EMPTY_CONTEXT, void 0, asked, void 0, void 0, live);
1451
+ const context = {};
1452
+ const sendContext = {};
1453
+ const headers = new Headers();
1454
+ const chosen = { current: void 0 };
1455
+ return await runMiddleware(flattened, "client", {
1456
+ data: input,
1457
+ meta: { id },
1458
+ method,
1459
+ signal: asked?.signal ?? new AbortController().signal,
1460
+ context,
1461
+ sendContext,
1462
+ headers,
1463
+ fetch: chosen,
1464
+ run: (data) => send(data, sendContext, context, asked, headers, chosen.current, live)
1465
+ });
1466
+ };
1467
+ const meta = method === "GET" ? {
1468
+ id,
1469
+ method
1470
+ } : { id };
1471
+ const stub = Object.assign((options) => call(options), {
1472
+ [SERVER_FN]: true,
1473
+ [SERVER_FN_CHAIN]: chain,
1474
+ [LIVE_CALL]: (options, live) => call(options, live),
1475
+ meta,
1476
+ serverFnMeta: meta,
1477
+ method,
1478
+ url: urlOf(id)
1479
+ });
1480
+ registerStub(id, stub);
1481
+ return stub;
1482
+ }
1483
+ /**
1484
+ * A streamed answer, as the values it carries.
1485
+ *
1486
+ * Read a line at a time, so a value is handed over when its line has arrived
1487
+ * rather than when the answer is complete. Leaving the loop early cancels the
1488
+ * body, which is what tells the server to stop producing.
1489
+ */
1490
+ async function* received(response, id, context) {
1491
+ const body = response.body;
1492
+ if (body === null) return;
1493
+ const reader = body.getReader();
1494
+ const decoder = new TextDecoder();
1495
+ let pending = "";
1496
+ try {
1497
+ for (;;) {
1498
+ const { done, value } = await reader.read();
1499
+ pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
1500
+ let end = pending.indexOf("\n");
1501
+ while (end !== -1) {
1502
+ const line = JSON.parse(pending.slice(0, end));
1503
+ pending = pending.slice(end + 1);
1504
+ if ("e" in line) throw new ServerFnError(id, 500, void 0, { thrown: line.t });
1505
+ if ("c" in line) {
1506
+ if (context !== void 0) Object.assign(context, decodeWire(line.c));
1507
+ } else yield decodeWire(line.v);
1508
+ end = pending.indexOf("\n");
1509
+ }
1510
+ if (done) return;
1511
+ }
1512
+ } finally {
1513
+ reader.cancel().catch(() => {});
1514
+ }
1515
+ }
1516
+ /** One object for every JSON call, which only ever reads it. */
1517
+ const JSON_BODY = { "content-type": "application/json" };
1518
+ /** What a GET call carries in place of a body's type. */
1519
+ const CALLER = { [RPC_CALLER]: "1" };
1520
+ /** Shared, because the no-middleware path never writes to it. */
1521
+ const EMPTY_CONTEXT = {};
1522
+ /**
1523
+ * Rebuild the throwable a control answer describes.
1524
+ *
1525
+ * An UNKNOWN kind is an error rather than a pass-through: it means the server is
1526
+ * newer than the client and is describing something this build cannot act on,
1527
+ * and returning it as a value would let a navigation instruction be rendered as
1528
+ * data.
1529
+ */
1530
+ function fromControl(control) {
1531
+ if (control.kind === "redirect") return new RpcRedirect(control.to, control.status, control.options === void 0 ? void 0 : decodeWire(control.options));
1532
+ if (control.kind === "not-found") return new RpcNotFound(control.message, control.data === void 0 ? void 0 : decodeWire(control.data), control.routeId);
1533
+ return /* @__PURE__ */ new Error(`[barq] server function answered with an unrecognised ${RPC_CONTROL} kind ${JSON.stringify(control.kind)}; the server is newer than this client bundle.`);
1534
+ }
1535
+ /** Where a server function keeps the middleware it declared, for another to inline. */
1536
+ const SERVER_FN_CHAIN = Symbol.for("barq.server-fn-chain");
1537
+ /**
1538
+ * A chain with each server function in it replaced by the middleware that
1539
+ * function declared, which is TanStack's rule: listing a function lists its
1540
+ * guards, never its handler.
1541
+ */
1542
+ function inlineServerFns(chain) {
1543
+ return chain.flatMap((step) => isServerFn(step) ? chainOf(step) : [step]);
1544
+ }
1545
+ function chainOf(fn) {
1546
+ return fn[SERVER_FN_CHAIN] ?? [];
1547
+ }
1548
+ /** Whether a value is a server function, by brand rather than by shape. */
1549
+ function isServerFn(value) {
1550
+ return typeof value === "function" && value[SERVER_FN] === true;
1551
+ }
1552
+ export { FRAME as A, installFrames as B, live as C, applyFrameResponse as D, startOptions as E, RPC_FRAME as F, LIVE_CALL as G, regionMarkup as H, asFrame as I, UNKNOWN_HEADER as J, clientStub as K, bindEntries as L, FRAME_APPLIED_EVENT as M, FRAME_CLOSE as N, frameAdapter as O, RPC_FLIGHT as P, frameAddress as R, urlOf as S, createStart as T, slotClose as U, isFrame as V, slotOpen as W, callOptionsOf as _, PAYLOAD_PARAM as a, inlineServerFns as b, RPC_CONTROL as c, RPC_STREAM as d, RPC_THROWN as f, SERVER_FN_CHAIN as g, SERVER_FN as h, LIVE_SUFFIX as i, FRAMES_HEADER as j, FLIGHT_TYPE as k, RPC_PREFIX as l, RpcRedirect as m, BUNDLED_BUILD as n, RPC_CALLER as o, RpcNotFound as p, ServerFnError as q, DATA_SUFFIX as r, RPC_CONTEXT as s, BUILD_HEADER as t, RPC_RESPONSE as u, clientRpc as v, clearStart as w, isServerFn as x, dataOf as y, frameOpen as z };
1553
+
1554
+ //# sourceMappingURL=client-BsyxVCyu.js.map