@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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +791 -2
  3. package/dist/client-BHyIiYxt.js +1527 -0
  4. package/dist/client-BHyIiYxt.js.map +1 -0
  5. package/dist/client-DHCV7yvQ.d.ts +440 -0
  6. package/dist/client-DHCV7yvQ.d.ts.map +1 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-qA8EyOr1.d.ts +49 -0
  10. package/dist/env-qA8EyOr1.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +44 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-Bm_-MTj6.d.ts +915 -0
  15. package/dist/index-Bm_-MTj6.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-BdVlE8qm.d.ts +576 -0
  19. package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +282 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +98 -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 +58 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +26 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +135 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +223 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-BV3xKmLa.js +1148 -0
  36. package/dist/server-BV3xKmLa.js.map +1 -0
  37. package/dist/server.d.ts +142 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-ChnB_xug.js +1140 -0
  41. package/dist/src-ChnB_xug.js.map +1 -0
  42. package/dist/static-fn-DgjNArBe.js +123 -0
  43. package/dist/static-fn-DgjNArBe.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +672 -0
  46. package/src/context.ts +666 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +97 -0
  50. package/src/frames-client.ts +1216 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +714 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +182 -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 +990 -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 +139 -0
@@ -0,0 +1,1148 @@
1
+ import { C as draftedStatus, G as setRequestMiddlewareContext, Y as takeSendContext, b as collectRequestCss, s as serverTiming, v as applyResponseDraft, x as createResponseDraft, z as invalidatedFrames } from "./src-ChnB_xug.js";
2
+ import { B as regionMarkup, D as FLIGHT_TYPE, F as bindEntries, H as slotOpen, I as frameAddress, L as frameOpen, M as RPC_FLIGHT, N as RPC_FRAME, O as FRAME, R as installFrames, V as slotClose, a as RPC_CONTEXT, c as RPC_RESPONSE, j as FRAME_CLOSE, k as FRAMES_HEADER, l as RPC_STREAM, n as LIVE_SUFFIX, o as RPC_CONTROL, r as PAYLOAD_PARAM, s as RPC_PREFIX, t as DATA_SUFFIX, u as RPC_THROWN, w as startOptions, y as isServerFn, z as isFrame } from "./client-BHyIiYxt.js";
3
+ import { NOT_FOUND, REDIRECT, isInputError, runRequestMiddleware } from "./middleware.js";
4
+ import { SSR_HTML_BRAND, commitEventResponse, commitResponseStub, createRequestEvent, isNavigable, setHeadSink } from "@barqjs/web/internal";
5
+ import { SharedSources, diagnosticsEnabled, emitDiagnostic, setHydratable, shareSources, unshareSources } from "@barqjs/core/internal";
6
+ import { provideRequestEvent } from "@barqjs/server/storage";
7
+ import { decodeWire, encodeWire, registerSerializationAdapters, serializationAdapters } from "@barqjs/server/codec";
8
+ import { block, childScope, getOwner, isDev, isSafeError, runWithOwner, untrack } from "@barqjs/core";
9
+ import { createBodyTooLargeError, limitBodyStream } from "srvx/body-limit";
10
+ import { SlotValue, esc, html, renderFrame, setServerComponent } from "@barqjs/server";
11
+ //#region src/frames-server.ts
12
+ /**
13
+ * How a frame crosses inside the page's own seed: by address, as a reference
14
+ * the browser resolves to the region already on the page. Registered when a
15
+ * frame is made and the registry does not hold it, so an application that has
16
+ * none sends the bytes it always did.
17
+ */
18
+ const FRAME_ADAPTER = {
19
+ key: "barq.frame",
20
+ test: isFrame,
21
+ toSerializable: (frame) => ({
22
+ id: frame[FRAME].id,
23
+ address: frame[FRAME].address
24
+ }),
25
+ fromSerializable: (ref) => ref
26
+ };
27
+ function registerFrameAdapter() {
28
+ if (serializationAdapters().some((adapter) => adapter.key === FRAME_ADAPTER.key)) return;
29
+ registerSerializationAdapters([FRAME_ADAPTER]);
30
+ }
31
+ /** The server function's component result, as a frame. */
32
+ function serverFrame(id, data, component) {
33
+ registerFrameAdapter();
34
+ const args = data === void 0 ? void 0 : encodeWire(data);
35
+ const address = frameAddress(id, encodeWire(data ?? null));
36
+ const state = {
37
+ id,
38
+ address,
39
+ args,
40
+ component,
41
+ markup: (options) => renderMarkup(state, options)
42
+ };
43
+ const render = (props) => documentFrame(address, args, component, props, state.live === true);
44
+ return Object.assign(render, { [FRAME]: state });
45
+ }
46
+ /** A value read from a slot argument: a Cell is called, anything else is the value. */
47
+ function valueOf(argument) {
48
+ return typeof argument === "function" ? untrack(argument) : argument;
49
+ }
50
+ /** What a slot call returns that is never one of its properties: the markup's own names. */
51
+ const NOT_A_PROPERTY = /* @__PURE__ */ new Set([
52
+ "t",
53
+ "then",
54
+ "toString",
55
+ "toJSON",
56
+ "valueOf",
57
+ "constructor"
58
+ ]);
59
+ /**
60
+ * The props a server component is rendered with: every name is a slot.
61
+ *
62
+ * A slot call is placed as markup, `<props.comment … />`, or read as data,
63
+ * `props.row(args).done`, which makes it a binding slot. Which one is known
64
+ * only once the component uses what the call returned, so the call answers
65
+ * both: its markup when it is placed, a stand-in for each property read.
66
+ *
67
+ * `fills` are the page's own props, when the frame is written into the page:
68
+ * each slot then holds what the browser would put there, for the first paint,
69
+ * and a binding slot's stand-ins hold the fill's first values.
70
+ */
71
+ var Slots = class {
72
+ fills;
73
+ records = [];
74
+ props;
75
+ constructor(fills) {
76
+ this.fills = fills;
77
+ this.props = new Proxy({}, { get: (_, name) => typeof name === "string" ? this.slot(name) : void 0 });
78
+ }
79
+ slot(name) {
80
+ if (name === "children") {
81
+ const at = this.reserve();
82
+ this.records[at] = {
83
+ at,
84
+ name,
85
+ key: ""
86
+ };
87
+ return html(this.markup(at, this.fill(name, at, {}, void 0)));
88
+ }
89
+ return (args) => this.call(name, args);
90
+ }
91
+ /**
92
+ * Taken before the region renders, so an occurrence inside it numbers after
93
+ * this one, in document order.
94
+ */
95
+ reserve() {
96
+ this.records.push(null);
97
+ return this.records.length - 1;
98
+ }
99
+ call(name, args) {
100
+ const at = this.reserve();
101
+ const values = {};
102
+ let explicit = "";
103
+ for (const [key, argument] of Object.entries(args ?? {})) {
104
+ if (key === "children") continue;
105
+ if (key === "$key") explicit = String(valueOf(argument));
106
+ else values[key] = valueOf(argument);
107
+ }
108
+ const children = args?.children;
109
+ const region = children === void 0 ? void 0 : esc(children);
110
+ const record = {
111
+ at,
112
+ name,
113
+ key: explicit,
114
+ ...args === void 0 ? {} : { args: encodeWire(values) },
115
+ ...region === void 0 ? {} : {
116
+ region,
117
+ hasRegion: true
118
+ }
119
+ };
120
+ this.records[at] = record;
121
+ const filled = this.fill(name, at, values, region);
122
+ let markup = null;
123
+ const placed = () => {
124
+ if (record.bind === true) throw readTwice(name);
125
+ markup ??= this.markup(at, filled);
126
+ return markup;
127
+ };
128
+ const standIns = /* @__PURE__ */ new Map();
129
+ const read = (key) => {
130
+ if (markup !== null) throw readTwice(name);
131
+ record.bind = true;
132
+ let standIn = standIns.get(key);
133
+ if (standIn === void 0) {
134
+ const result = filled?.result;
135
+ const known = typeof result === "object" && result !== null;
136
+ const value = known ? runWithOwner(filled.scope, () => untrack(() => result[key])) : void 0;
137
+ standIn = new SlotValue(at, key, this.fills !== null && known, value);
138
+ standIns.set(key, standIn);
139
+ }
140
+ return standIn;
141
+ };
142
+ return new Proxy({}, {
143
+ get: (_, key) => {
144
+ if (key === SSR_HTML_BRAND) return record.bind !== true;
145
+ if (key === "t") return placed();
146
+ if (key === "toString") return placed;
147
+ if (typeof key === "symbol" || NOT_A_PROPERTY.has(key)) return void 0;
148
+ return read(key);
149
+ },
150
+ ownKeys: () => {
151
+ throw new Error(`[barq] A server component spread what \`props.${name}()\` returned. A binding slot's properties are placed one position at a time, so the markup shows what the browser fills: name each one, as in \`<li hidden={row.hidden}>\`.`);
152
+ }
153
+ });
154
+ }
155
+ markup(at, filled) {
156
+ const content = filled === null ? "" : runWithOwner(filled.scope, () => esc(filled.result));
157
+ return `<!--${slotOpen(at)}-->${content}<!--${slotClose(at)}-->`;
158
+ }
159
+ /**
160
+ * The page's fill for a slot, run once for the first paint: its content for
161
+ * a slot that is placed, its values for one read as data. Nothing over the
162
+ * wire, where the browser fills every slot itself.
163
+ */
164
+ fill(name, at, values, region) {
165
+ if (this.fills === null) return null;
166
+ const given = this.fills[name];
167
+ const scope = childScope(getOwner(), "branch");
168
+ setHydratable(scope, true);
169
+ setServerComponent(scope, false);
170
+ if (name === "children") return {
171
+ result: given,
172
+ scope
173
+ };
174
+ const props = {};
175
+ for (const [key, value] of Object.entries(values)) props[key] = () => value;
176
+ if (region !== void 0) props.children = block(() => html(regionMarkup(String(at), region)));
177
+ const result = runWithOwner(scope, () => {
178
+ const fill = valueOf(given);
179
+ return typeof fill === "function" ? fill(props) : fill;
180
+ });
181
+ return result === void 0 ? null : {
182
+ result,
183
+ scope
184
+ };
185
+ }
186
+ /**
187
+ * The records the markup still carries, keyed: a boundary resumed during the
188
+ * render built its slots again, so only the occurrences in the final markup
189
+ * count, and a positional key is taken in that markup's order. `inline`
190
+ * drops each region, which the page already carries inside the slot.
191
+ */
192
+ final(markup, inline) {
193
+ const present = /* @__PURE__ */ new Set();
194
+ for (const found of markup.matchAll(/<!--s:(\d+)-->/g)) present.add(Number(found[1]));
195
+ for (const found of markup.matchAll(/ _b-[^\s=>]+="([^"]*)"/g)) for (const entry of bindEntries(found[1])) present.add(entry.at);
196
+ for (const found of markup.matchAll(/<!--_b:(\d+):/g)) present.add(Number(found[1]));
197
+ const ordinal = /* @__PURE__ */ new Map();
198
+ const out = [];
199
+ for (const record of this.records) {
200
+ if (record === null || !present.has(record.at)) continue;
201
+ const count = ordinal.get(record.name) ?? 0;
202
+ ordinal.set(record.name, count + 1);
203
+ out.push({
204
+ at: record.at,
205
+ name: record.name,
206
+ key: record.key === "" ? `${record.name}:${count}` : `$${record.key}`,
207
+ ...record.args === void 0 ? {} : { args: record.args },
208
+ ...record.bind === true ? { bind: true } : {
209
+ ...record.hasRegion === true ? { hasRegion: true } : {},
210
+ ...inline || record.region === void 0 ? {} : { region: record.region }
211
+ }
212
+ });
213
+ }
214
+ return out;
215
+ }
216
+ };
217
+ function readTwice(name) {
218
+ return /* @__PURE__ */ new Error(`[barq] A server component both placed \`props.${name}()\` as markup and read it as data. A slot call is one or the other: place it, \`<props.` + name + " />`, for the browser's content, or read its properties, for a binding slot.");
219
+ }
220
+ /** Render a server component: what renders under it may read binding slots. */
221
+ function asServerComponent(render) {
222
+ const scope = childScope(getOwner(), "branch");
223
+ setServerComponent(scope, true);
224
+ return runWithOwner(scope, render);
225
+ }
226
+ /**
227
+ * The frame written into the page, where a route renders it.
228
+ *
229
+ * What the component declares for the head goes to the page's head as any
230
+ * component's does, and is recorded too, so the browser takes those tags over
231
+ * with the frame and drops them with it.
232
+ */
233
+ function documentFrame(address, args, component, fills, live) {
234
+ const slots = new Slots(fills);
235
+ const head = [];
236
+ let outer = null;
237
+ outer = setHeadSink({
238
+ add: (tags) => {
239
+ head.push(...tags);
240
+ outer?.add(tags);
241
+ },
242
+ module: (url) => outer?.module?.(url)
243
+ });
244
+ const scope = childScope(getOwner(), "branch");
245
+ setHydratable(scope, false);
246
+ setServerComponent(scope, true);
247
+ let region;
248
+ try {
249
+ region = runWithOwner(scope, () => esc(component(slots.props)));
250
+ } finally {
251
+ setHeadSink(outer);
252
+ }
253
+ const payload = {
254
+ v: 1,
255
+ args,
256
+ ...live ? { live: true } : {},
257
+ slots: slots.final(region, true),
258
+ head
259
+ };
260
+ return html(frameOpen(address, payload) + region + FRAME_CLOSE);
261
+ }
262
+ /**
263
+ * The answer to a call from the browser: the region rendered on its own, its
264
+ * slots empty. Its head carries what the region declared, the stylesheets and
265
+ * chunks its `lazy()` modules need, and the rules `@barqjs/css` registered
266
+ * while it rendered.
267
+ */
268
+ async function frameResponse(frame) {
269
+ const answer = new Response(await frameMarkup(frame));
270
+ answer.headers.set("content-type", "text/html; charset=utf-8");
271
+ answer.headers.set("cache-control", "no-store");
272
+ answer.headers.set("x-barq-rpc", RPC_FRAME);
273
+ return answer;
274
+ }
275
+ /**
276
+ * A frame's markup over the wire: the region rendered on its own, its slots
277
+ * empty. Rendered by the frame itself, so by the copy of this module that made
278
+ * it: a host serving a built server through its own `serveBarq` answers the
279
+ * call from another copy, whose renderer is not the one the component was
280
+ * compiled against.
281
+ */
282
+ function frameMarkup(frame, options = {}) {
283
+ return frame[FRAME].markup(options);
284
+ }
285
+ async function renderMarkup(frame, options) {
286
+ const { address, args, component } = frame;
287
+ const slots = new Slots(null);
288
+ const rendered = await renderFrame(() => asServerComponent(() => component(slots.props)), {
289
+ renderId: `f${address.slice(address.lastIndexOf("#") + 1)}-`,
290
+ session: options.session
291
+ });
292
+ const head = [...rendered.head];
293
+ const css = collectRequestCss();
294
+ if (css !== "") head.push({
295
+ tag: "style",
296
+ props: { "data-frame-css": address },
297
+ children: css
298
+ });
299
+ const payload = {
300
+ v: 1,
301
+ args,
302
+ ...frame.live === true ? { live: true } : {},
303
+ slots: slots.final(rendered.html, false),
304
+ head
305
+ };
306
+ return frameOpen(address, payload) + rendered.html + FRAME_CLOSE;
307
+ }
308
+ /**
309
+ * The frames a request says its page has mounted. Untrusted input like any
310
+ * other: each one is asked for through its own function, validator and
311
+ * middleware included, and a malformed list is no list.
312
+ */
313
+ function mountedFrames(header) {
314
+ if (header === null || header === "") return [];
315
+ let parsed;
316
+ try {
317
+ parsed = JSON.parse(header);
318
+ } catch {
319
+ return [];
320
+ }
321
+ if (!Array.isArray(parsed)) return [];
322
+ const out = [];
323
+ for (const entry of parsed.slice(0, 32)) {
324
+ if (typeof entry !== "object" || entry === null) continue;
325
+ const { id, args } = entry;
326
+ if (typeof id === "string") out.push({
327
+ id,
328
+ args
329
+ });
330
+ }
331
+ return out;
332
+ }
333
+ /**
334
+ * A mutation's answer with the regions it changed: its value in a script, then
335
+ * each changed frame's markup, as the page applies them. `ask` calls a mounted
336
+ * frame's server function again with the arguments the page sent.
337
+ */
338
+ async function flightResponse(value, mounted, invalidated, ask) {
339
+ const seen = /* @__PURE__ */ new Set();
340
+ let regions = "";
341
+ for (const frame of mounted) {
342
+ if (!invalidated.has(frame.id)) continue;
343
+ const answered = await ask(frame);
344
+ if (!isFrame(answered)) continue;
345
+ const { address } = answered[FRAME];
346
+ if (seen.has(address)) continue;
347
+ seen.add(address);
348
+ regions += await frameMarkup(answered);
349
+ }
350
+ const script = `<script type="${FLIGHT_TYPE}">${JSON.stringify(encodeWire(value)).replaceAll("<", "\\u003c")}<\/script>`;
351
+ const answer = new Response(script + regions);
352
+ answer.headers.set("content-type", "text/html; charset=utf-8");
353
+ answer.headers.set("cache-control", "no-store");
354
+ answer.headers.set("x-barq-rpc", RPC_FLIGHT);
355
+ return answer;
356
+ }
357
+ //#endregion
358
+ //#region src/live-server.ts
359
+ /**
360
+ * The server half of `live`: a call at the live address answered as server-sent
361
+ * events, for as long as the answer stands.
362
+ *
363
+ * A frame is rendered again each time an async source it reads moves, and each
364
+ * new rendering that differs from the last goes out as one event carrying the
365
+ * frame's markup. Any other answer goes out a value per event. An answer whose
366
+ * every source has ended says so with a `complete` event; a body that ends
367
+ * without one is a connection that died, which the page's loop reconnects.
368
+ *
369
+ * Each event's id is the digest of what it carried. A reconnect names the last
370
+ * one it applied in `Last-Event-ID`, and an answer that still matches it is not
371
+ * sent again.
372
+ */
373
+ /** The `x-barq-rpc` value a live answer carries. */
374
+ const RPC_LIVE = "live";
375
+ /** How often an idle connection says it is still there, against proxies that time one out. */
376
+ const HEARTBEAT_MS = 2e4;
377
+ function digest(text) {
378
+ let hash = 2166136261;
379
+ for (let at = 0; at < text.length; at++) {
380
+ hash ^= text.charCodeAt(at);
381
+ hash = Math.imul(hash, 16777619);
382
+ }
383
+ return (hash >>> 0).toString(36);
384
+ }
385
+ function isIterable$1(value) {
386
+ return typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
387
+ }
388
+ /**
389
+ * One event: its kind, an id, and data that is JSON and so carries no line
390
+ * break of its own. A frame's markup is `frame`, a value the default kind.
391
+ */
392
+ function event(kind, id, data) {
393
+ return `${kind === "frame" ? "event: frame\n" : ""}id: ${id}\ndata: ${data}\n\n`;
394
+ }
395
+ /** The answer to a call at the live address. */
396
+ function liveResponse(result, request) {
397
+ const encoder = new TextEncoder();
398
+ const last = request.headers.get("last-event-id");
399
+ let controller = null;
400
+ let ended = false;
401
+ const stops = [];
402
+ const end = (complete) => {
403
+ if (ended) return;
404
+ ended = true;
405
+ for (const stop of stops) stop();
406
+ if (controller === null) return;
407
+ try {
408
+ if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
409
+ controller.close();
410
+ } catch {}
411
+ };
412
+ const send = (text) => {
413
+ if (ended || controller === null) return;
414
+ try {
415
+ controller.enqueue(encoder.encode(text));
416
+ } catch {
417
+ end(false);
418
+ }
419
+ };
420
+ let sentId = last;
421
+ const emit = (data, kind = "message") => {
422
+ const id = digest(data);
423
+ if (id === sentId) return;
424
+ sentId = id;
425
+ send(event(kind, id, data));
426
+ };
427
+ const start = () => {
428
+ const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
429
+ heartbeat.unref?.();
430
+ stops.push(() => clearInterval(heartbeat));
431
+ const abort = () => end(false);
432
+ request.signal.addEventListener("abort", abort, { once: true });
433
+ stops.push(() => request.signal.removeEventListener("abort", abort));
434
+ if (isFrame(result)) frames(result);
435
+ else if (isIterable$1(result)) values(result);
436
+ else {
437
+ emit(JSON.stringify(encodeWire(result)));
438
+ end(true);
439
+ }
440
+ };
441
+ const frames = async (frame) => {
442
+ const shared = new SharedSources();
443
+ stops.push(() => shared.close());
444
+ let rendering = false;
445
+ let again = false;
446
+ const render = async () => {
447
+ if (rendering) {
448
+ again = true;
449
+ return;
450
+ }
451
+ rendering = true;
452
+ try {
453
+ for (;;) {
454
+ again = false;
455
+ const session = Symbol("live-frame");
456
+ shared.begin();
457
+ shareSources(session, shared);
458
+ let markup;
459
+ try {
460
+ markup = await frameMarkup(frame, { session });
461
+ } finally {
462
+ unshareSources(session);
463
+ }
464
+ shared.sweep();
465
+ if (ended) return;
466
+ emit(JSON.stringify(markup), "frame");
467
+ if (!again) break;
468
+ }
469
+ } catch (error) {
470
+ console.error("[barq] A live frame failed to render, so its connection ends and the page reconnects. The error:", error);
471
+ end(false);
472
+ return;
473
+ } finally {
474
+ rendering = false;
475
+ }
476
+ if (shared.settled) end(true);
477
+ };
478
+ shared.onChange(() => void render());
479
+ await render();
480
+ };
481
+ const values = async (source) => {
482
+ const iterator = source[Symbol.asyncIterator]();
483
+ stops.push(() => void iterator.return?.());
484
+ try {
485
+ for (;;) {
486
+ const step = await iterator.next();
487
+ if (ended) return;
488
+ if (step.done === true) break;
489
+ emit(JSON.stringify(encodeWire(step.value)));
490
+ }
491
+ end(true);
492
+ } catch (error) {
493
+ console.error("[barq] A live answer failed while streaming, so its connection ends and the page reconnects. The error:", error);
494
+ end(false);
495
+ }
496
+ };
497
+ const body = new ReadableStream({
498
+ start(given) {
499
+ controller = given;
500
+ start();
501
+ },
502
+ cancel() {
503
+ end(false);
504
+ }
505
+ });
506
+ const answer = new Response(body);
507
+ answer.headers.set("content-type", "text/event-stream; charset=utf-8");
508
+ answer.headers.set("cache-control", "no-store");
509
+ answer.headers.set("x-accel-buffering", "no");
510
+ answer.headers.set("x-barq-rpc", RPC_LIVE);
511
+ return answer;
512
+ }
513
+ //#endregion
514
+ //#region src/server.ts
515
+ /**
516
+ * The request handler: one URL shape, one lookup, and the checks that run
517
+ * before a handler body does.
518
+ *
519
+ * Every default here is the strict one, because the survey found the same four
520
+ * failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,
521
+ * publicly-mounted endpoint reached by an id enumerable from the client bundle.
522
+ * Each is cheap to close and expensive to retrofit.
523
+ */
524
+ installFrames(serverFrame);
525
+ /**
526
+ * ONE registry per process, whichever copy of this module asks.
527
+ *
528
+ * A build compiles this module INTO its server bundle, and a host that serves
529
+ * that bundle through its own `serveBarq` has imported a second copy. Kept in
530
+ * a module variable, each copy had a registry of its own: the bundle mounted
531
+ * every function into one and the host answered 404 out of the other.
532
+ */
533
+ const MOUNTED = globalThis[Symbol.for("barq.start.server-fns")] ??= {
534
+ registry: /* @__PURE__ */ new Map(),
535
+ manifest: null
536
+ };
537
+ const REGISTRY = MOUNTED.registry;
538
+ /**
539
+ * Say how the build's manifest is mounted, so a call can ask for it.
540
+ *
541
+ * The server entry imports the manifest when it first renders a page, which is
542
+ * late for a function called before any page has been asked for: a server that
543
+ * has just started and a browser tab that was already open. The id it names
544
+ * was in no registry yet, and the answer was a 404 for a function that exists.
545
+ */
546
+ function mountOnDemand(manifest) {
547
+ MOUNTED.manifest = manifest;
548
+ }
549
+ /**
550
+ * Mount a server function. The compiler emits one call per EXPORTED server
551
+ * function in a module compiled for the server.
552
+ *
553
+ * Export-ness is what decides reachability, which is SvelteKit's rule and the
554
+ * only genuine notion of an internal server function in the survey: a
555
+ * non-exported one is never registered, so it has no id and no endpoint, and is
556
+ * still callable from its siblings.
557
+ */
558
+ function mount(id, fn) {
559
+ if (!isServerFn(fn)) throw new TypeError(`[barq] \`mount(${JSON.stringify(id)}, fn)\` was given something that is not a server function, so there is nothing to answer calls with. Pass a function built with \`createServerFn().handler(...)\`.`);
560
+ if (id === "") throw new TypeError("[barq] `mount(id, fn)` was given an empty `id`, so no request could reach the function. Pass a non-empty string that is unique in the application.");
561
+ fn.meta.id = id;
562
+ REGISTRY.set(id, fn);
563
+ }
564
+ /** The mounted surface, for the build to record and a reviewer to read. */
565
+ function mounted() {
566
+ return [...REGISTRY.keys()].toSorted();
567
+ }
568
+ /**
569
+ * The function mounted at an id, or `undefined`.
570
+ *
571
+ * Exported for the BUILD's chain check, which has to ask each reachable id what
572
+ * middleware it actually carries. It reads the registry inside whichever bundle
573
+ * it is called from, which is why the check runs through the server entry
574
+ * rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`
575
+ * INTO the ssr bundle, so a plugin importing this module would be asking a
576
+ * second, empty registry.
577
+ */
578
+ function mountedFn(id) {
579
+ return REGISTRY.get(id);
580
+ }
581
+ /** Test seam. Not for application use. */
582
+ function unmountAll() {
583
+ REGISTRY.clear();
584
+ MOUNTED.manifest = null;
585
+ }
586
+ /**
587
+ * Is this request allowed to invoke a server function?
588
+ *
589
+ * `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback
590
+ * is Waku's post-CVE shape and it is the strictest default found: `Origin` is
591
+ * legitimately absent on some same-origin requests and on non-browser clients,
592
+ * while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged
593
+ * from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.
594
+ */
595
+ function originAllowed(request, options) {
596
+ const origin = request.headers.get("origin");
597
+ if (origin !== null) {
598
+ if (origin === "null") return false;
599
+ if (origin === new URL(request.url).origin) return true;
600
+ return options?.allowedOrigins?.includes(origin) ?? false;
601
+ }
602
+ const site = request.headers.get("sec-fetch-site");
603
+ if (site === null) return false;
604
+ return site === "same-origin" || site === "none";
605
+ }
606
+ /** Methods that cannot change state, so CSRF does not apply to them. */
607
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
608
+ "GET",
609
+ "HEAD",
610
+ "OPTIONS"
611
+ ]);
612
+ /**
613
+ * Is this a request a BROWSER made from another origin?
614
+ *
615
+ * A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole
616
+ * design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be
617
+ * called by this application's own pages — so a request with no origin signal at
618
+ * all is refused there, because there is no legitimate caller that omits one.
619
+ *
620
+ * A route handler is the opposite: an API route exists so that something OTHER
621
+ * than a browser can call it. A Stripe webhook, a GitHub delivery, a cron
622
+ * hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and
623
+ * refusing on their absence would refuse the main reason API routes exist.
624
+ *
625
+ * So this answers the narrower question, and the narrower question is the one
626
+ * CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER
627
+ * with the victim's cookies attached, and a browser making a cross-origin
628
+ * state-changing request always says so — `Origin` on any cross-origin POST
629
+ * since forever, `Sec-Fetch-Site` on everything in every current browser. So:
630
+ * refuse when a signal is present and says cross-origin; allow when there is no
631
+ * signal, because then it is not a browser and cannot be a forgery.
632
+ *
633
+ * `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than
634
+ * read as absent, which is a bypass that has shipped.
635
+ */
636
+ function crossOriginRefused(request, allowedOrigins) {
637
+ if (SAFE_METHODS.has(request.method.toUpperCase())) return false;
638
+ const origin = request.headers.get("origin");
639
+ if (origin !== null) {
640
+ if (origin === "null") return true;
641
+ if (origin === new URL(request.url).origin) return false;
642
+ return !(allowedOrigins?.includes(origin) ?? false);
643
+ }
644
+ const site = request.headers.get("sec-fetch-site");
645
+ if (site === null) return false;
646
+ return site !== "same-origin" && site !== "none";
647
+ }
648
+ /**
649
+ * Handle one server-function request, or return null if the URL is not one.
650
+ *
651
+ * Returning null rather than a 404 is what lets this compose as middleware in
652
+ * front of a page handler.
653
+ */
654
+ async function handleServerFn(request, options) {
655
+ const url = new URL(request.url);
656
+ if (!url.pathname.startsWith("/_barq/fn/")) return null;
657
+ const method = request.method;
658
+ if (method !== "POST" && method !== "GET") return new Response("method not allowed", {
659
+ status: 405,
660
+ headers: { allow: "GET, POST" }
661
+ });
662
+ if (!originAllowed(request, options)) return new Response("forbidden", { status: 403 });
663
+ const path = url.pathname.slice(RPC_PREFIX.length);
664
+ const isLive = path.endsWith(LIVE_SUFFIX);
665
+ const isData = isLive || path.endsWith(".data");
666
+ let id;
667
+ try {
668
+ id = decodeURIComponent(isLive ? path.slice(0, -LIVE_SUFFIX.length) : isData ? path.slice(0, -DATA_SUFFIX.length) : path);
669
+ } catch {
670
+ return new Response("bad request", { status: 400 });
671
+ }
672
+ let fn = REGISTRY.get(id);
673
+ if (fn === void 0 && MOUNTED.manifest !== null) {
674
+ await MOUNTED.manifest();
675
+ fn = REGISTRY.get(id);
676
+ }
677
+ if (fn === void 0) return new Response("not found", { status: 404 });
678
+ if (options?.reachable?.(id) === false) return new Response("not found", { status: 404 });
679
+ const expected = fn.meta.method ?? "POST";
680
+ if (method !== expected) return new Response("method not allowed", {
681
+ status: 405,
682
+ headers: { allow: expected }
683
+ });
684
+ if (method === "GET") {
685
+ if (!isData) return new Response("not found", { status: 404 });
686
+ if (request.headers.get("x-barq-fn") === null) return new Response("forbidden", { status: 403 });
687
+ }
688
+ const bodyLimit = options?.maxBodySize ?? DEFAULT_BODY_LIMIT;
689
+ const target = fn;
690
+ const draft = createResponseDraft();
691
+ /**
692
+ * The call itself: read the body, run the function, build the answer. The
693
+ * innermost step of the request middleware chain, so a global middleware
694
+ * that refuses does so before a byte of the payload has been parsed.
695
+ */
696
+ const respond = async () => {
697
+ let input;
698
+ let clientContext;
699
+ if (isData && (method === "GET" || !isFormBody(request))) try {
700
+ const body = method === "GET" ? queryPayload(url, bodyLimit) : await capped(request, bodyLimit).json();
701
+ input = body?.input === void 0 ? void 0 : decodeWire(body.input);
702
+ clientContext = body?.context === void 0 ? void 0 : { ...decodeWire(body.context) };
703
+ } catch (error) {
704
+ return unreadable(error);
705
+ }
706
+ else try {
707
+ input = await capped(request, options?.maxFormSize ?? bodyLimit).formData();
708
+ } catch (error) {
709
+ return unreadable(error);
710
+ }
711
+ try {
712
+ const result = await (input instanceof FormData ? target(input) : target({ data: input }, clientContext));
713
+ const sendContext = takeSendContext();
714
+ if (isLive) {
715
+ if (result instanceof Response) return applyResponseDraft(result, draft);
716
+ return applyResponseDraft(liveResponse(result, request), draft);
717
+ }
718
+ if (result instanceof Response) {
719
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_RESPONSE);
720
+ return applyResponseDraft(result, draft);
721
+ }
722
+ if (isFrame(result)) {
723
+ if (isData) return applyResponseDraft(await frameResponse(result), draft);
724
+ return applyResponseDraft(seeOther(request), draft);
725
+ }
726
+ if (isIterable(result)) {
727
+ if (isData) return applyResponseDraft(streamed(result, sendContext, id, revealerOf(options)), draft);
728
+ result[Symbol.asyncIterator]().return?.();
729
+ return applyResponseDraft(seeOther(request), draft);
730
+ }
731
+ if (isData) {
732
+ const answer = draftedStatus(draft, 200);
733
+ const mountedHere = mountedFrames(request.headers.get(FRAMES_HEADER));
734
+ const changed = invalidatedFrames();
735
+ if (mountedHere.length > 0 && changed.size > 0) {
736
+ const flight = await flightResponse(Object.keys(sendContext).length === 0 ? result : {
737
+ result,
738
+ context: sendContext
739
+ }, mountedHere, changed, async (frame) => {
740
+ const asked = REGISTRY.get(frame.id);
741
+ if (asked === void 0 || options?.reachable?.(frame.id) === false) return void 0;
742
+ try {
743
+ return await asked({ data: frame.args === void 0 ? void 0 : decodeWire(frame.args) });
744
+ } catch (error) {
745
+ console.error(`[barq] The frame of ${JSON.stringify(frame.id)} could not be rendered again for the mutation ${JSON.stringify(id)}, so its answer leaves it out. The error:`, error);
746
+ return;
747
+ }
748
+ });
749
+ if (Object.keys(sendContext).length > 0) flight.headers.set(RPC_CONTEXT, "1");
750
+ return applyResponseDraft(new Response(flight.body, {
751
+ ...answer,
752
+ headers: flight.headers
753
+ }), draft);
754
+ }
755
+ if (Object.keys(sendContext).length === 0) return applyResponseDraft(Response.json(encodeWire(result), answer), draft);
756
+ return applyResponseDraft(Response.json(encodeWire({
757
+ result,
758
+ context: sendContext
759
+ }), {
760
+ ...answer,
761
+ headers: { [RPC_CONTEXT]: "1" }
762
+ }), draft);
763
+ }
764
+ return applyResponseDraft(seeOther(request), draft);
765
+ } catch (error) {
766
+ if (error instanceof Response) return thrownAnswer(error, isData, draft);
767
+ const control = controlOf(error);
768
+ if (control !== null) return applyResponseDraft(controlResponse(control, isData, error.headers), draft);
769
+ if (isInputError(error)) return applyResponseDraft(isData ? Response.json(inputAnswer(error), { status: 400 }) : new Response("invalid input", { status: 400 }), draft);
770
+ return applyResponseDraft(failed(id, error, isData, options, "threw"), draft);
771
+ }
772
+ };
773
+ const context = {};
774
+ const timing = isDev ? serverTiming() : void 0;
775
+ const event = createRequestEvent(request, { response: draft });
776
+ try {
777
+ const response = await provideRequestEvent(event, () => {
778
+ setRequestMiddlewareContext(context);
779
+ return runRequestMiddleware(startOptions().requestMiddleware ?? [], {
780
+ request,
781
+ pathname: url.pathname,
782
+ handlerType: "serverFn",
783
+ context
784
+ }, respond);
785
+ });
786
+ if (timing !== void 0) {
787
+ timing.phase("barq-fn", id);
788
+ draft.headers.append("server-timing", timing.header());
789
+ }
790
+ return commitEventResponse(response, event);
791
+ } catch (error) {
792
+ if (error instanceof Response) return commitEventResponse(thrownAnswer(error, isData, draft), event);
793
+ return commitEventResponse(failed(id, error, isData, options, "middleware"), event);
794
+ } finally {
795
+ commitResponseStub(draft, { event });
796
+ }
797
+ }
798
+ /**
799
+ * The 400 a refused input answers with: the refusal and each issue with the
800
+ * path to the field it is about.
801
+ */
802
+ function inputAnswer(error) {
803
+ const issues = error.issues ?? [];
804
+ return {
805
+ error: "invalid input",
806
+ message: error.message,
807
+ issues: issues.map((issue) => {
808
+ const { message, path } = issue ?? {};
809
+ const keys = Array.isArray(path) ? path.map((segment) => {
810
+ const key = typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment;
811
+ return typeof key === "number" ? key : String(key);
812
+ }) : [];
813
+ return keys.length === 0 ? { message: String(message) } : {
814
+ message: String(message),
815
+ path: keys
816
+ };
817
+ })
818
+ };
819
+ }
820
+ /**
821
+ * What a failed call may tell its caller: everything the development server
822
+ * asks for, and in production only an error the application branded with
823
+ * `markSafeError`, by its name and message.
824
+ */
825
+ function revealerOf(options) {
826
+ const reveal = options?.revealError;
827
+ return (error) => {
828
+ if (reveal !== void 0) return reveal(error);
829
+ if (!(error instanceof Error) || !isSafeError(error)) return void 0;
830
+ return {
831
+ name: error.name,
832
+ message: error.message
833
+ };
834
+ };
835
+ }
836
+ /**
837
+ * A call that failed on the server: logged there, reported on the diagnostics
838
+ * channel, and answered 500. The caller learns what was thrown only when the
839
+ * development server asked for it.
840
+ */
841
+ function failed(id, error, isData, options, where) {
842
+ const thrown = revealerOf(options)(error);
843
+ const happened = where === "threw" ? `The server function ${JSON.stringify(id)} threw` : `A request middleware threw before the server function ${JSON.stringify(id)} ran`;
844
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
845
+ console.error(`[barq] ${happened}, so the call answered 500${thrown === void 0 ? " without the error's text" : ""}. The error:`, error);
846
+ if (thrown === void 0) return new Response("internal server error", { status: 500 });
847
+ return isData ? Response.json({
848
+ error: "internal server error",
849
+ thrown
850
+ }, { status: 500 }) : new Response(`internal server error\n\n${thrown.stack ?? `${thrown.name}: ${thrown.message}`}`, { status: 500 });
851
+ }
852
+ function reportFailure(id, error, happened) {
853
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
854
+ emitDiagnostic({
855
+ code: "SERVER_FUNCTION_FAILED",
856
+ kind: "ssr",
857
+ severity: "error",
858
+ message: `${happened}: \`${text}\`. The caller received a 500. Fix the throw at the top of the stack, or throw a \`Response\`, \`redirect()\` or \`notFound()\` to answer the caller on purpose.`,
859
+ data: {
860
+ id,
861
+ error
862
+ }
863
+ }, null);
864
+ }
865
+ /**
866
+ * A `Response` the chain or the handler threw, as the answer. The data
867
+ * channel's client rejects the call with it, so the header says it was thrown
868
+ * rather than returned; a browser following a form needs no telling.
869
+ */
870
+ function thrownAnswer(error, isData, draft) {
871
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_THROWN);
872
+ return applyResponseDraft(error, draft);
873
+ }
874
+ /**
875
+ * Read a thrown value as a control answer, by BRAND rather than by class.
876
+ *
877
+ * The classes are `@barqjs/router`'s and this package cannot import them; see
878
+ * {@link REDIRECT}. A brand check is also what lets the same code recognise a
879
+ * redirect the router threw and one `@barqjs/start/client` rebuilt off the
880
+ * wire, which matters when a server function calls another one.
881
+ */
882
+ function controlOf(error) {
883
+ if (typeof error !== "object" || error === null) return null;
884
+ const branded = error;
885
+ if (branded[REDIRECT] === true) {
886
+ if (typeof branded.to !== "string") return null;
887
+ const status = typeof branded.status === "number" ? branded.status : 302;
888
+ const options = describedNavigation(branded.options);
889
+ return {
890
+ kind: "redirect",
891
+ to: branded.to,
892
+ status,
893
+ ...options === void 0 ? {} : { options: encodeWire(options) }
894
+ };
895
+ }
896
+ if (branded[NOT_FOUND] === true) {
897
+ const message = error.message;
898
+ return {
899
+ kind: "not-found",
900
+ message: typeof message === "string" ? message : "not found",
901
+ ...branded.data === void 0 ? {} : { data: encodeWire(branded.data) },
902
+ ...typeof branded.routeId === "string" ? { routeId: branded.routeId } : {}
903
+ };
904
+ }
905
+ return null;
906
+ }
907
+ /** The parts of a navigation that are values, and so can be sent. */
908
+ const NAVIGATION = [
909
+ "to",
910
+ "from",
911
+ "params",
912
+ "search",
913
+ "hash",
914
+ "replace",
915
+ "reloadDocument",
916
+ "href"
917
+ ];
918
+ /**
919
+ * The navigation an options-form redirect described, as far as it can cross.
920
+ *
921
+ * A function among them cannot: `search: (current) => ...` is asked about a
922
+ * location only the browser has. A redirect holding one is sent as its resolved
923
+ * target alone, which is what every redirect was sent as before this existed.
924
+ * `statusCode` and `headers` are the answer rather than the navigation, and
925
+ * travel as the status and on the response.
926
+ */
927
+ function describedNavigation(described) {
928
+ if (typeof described !== "object" || described === null) return void 0;
929
+ const given = described;
930
+ const out = {};
931
+ for (const name of NAVIGATION) {
932
+ const value = given[name];
933
+ if (value === void 0) continue;
934
+ if (typeof value === "function") return void 0;
935
+ out[name] = value;
936
+ }
937
+ if (typeof given.statusCode === "number") out.statusCode = given.statusCode;
938
+ return out;
939
+ }
940
+ /**
941
+ * A control answer, on whichever channel asked.
942
+ *
943
+ * THE TWO CHANNELS DIVERGE HERE ON PURPOSE, because their clients are different
944
+ * programs. The form channel's client is a BROWSER following the response
945
+ * itself, so a redirect has to be a real 3xx with a `Location`. The data
946
+ * channel's client is `clientRpc`, and a real 3xx there would be FOLLOWED by
947
+ * `fetch` — the caller would receive the target page's HTML instead of a
948
+ * navigation. So the data channel answers 200 and describes the redirect in the
949
+ * body, and the client re-throws it for the router to act on. That is a soft
950
+ * navigation rather than a document load, which is both correct and faster;
951
+ * TanStack returns the raw 3xx and the fetch follows it.
952
+ *
953
+ * `not-found` is a 404 on both, because 404 is the honest status and no client
954
+ * follows one.
955
+ *
956
+ * `extra` is the thrown value's own `headers`, which are the response's on
957
+ * either channel: a redirect that signs a visitor out carries the cookie that
958
+ * does it.
959
+ */
960
+ function controlResponse(control, isData, extra) {
961
+ const headers = answerHeaders(extra);
962
+ if (control.kind === "not-found") {
963
+ if (!isData) return new Response(control.message, {
964
+ status: 404,
965
+ headers
966
+ });
967
+ headers.set(RPC_CONTROL, control.kind);
968
+ return Response.json(control, {
969
+ status: 404,
970
+ headers
971
+ });
972
+ }
973
+ if (!isNavigable(control.to)) {
974
+ reportRefusedRedirect(control.to);
975
+ return new Response("bad redirect", { status: 500 });
976
+ }
977
+ if (isData) {
978
+ headers.set(RPC_CONTROL, control.kind);
979
+ return Response.json(control, {
980
+ status: 200,
981
+ headers
982
+ });
983
+ }
984
+ const status = control.status === 302 ? 303 : control.status;
985
+ headers.set("location", control.to);
986
+ return new Response(null, {
987
+ status,
988
+ headers
989
+ });
990
+ }
991
+ /** A thrown answer's `headers`, or none when it carried nothing a response can take. */
992
+ function answerHeaders(extra) {
993
+ if (extra === void 0 || extra === null) return new Headers();
994
+ try {
995
+ return new Headers(extra);
996
+ } catch {
997
+ return new Headers();
998
+ }
999
+ }
1000
+ function reportRefusedRedirect(to) {
1001
+ console.error(`[barq] A server function threw \`redirect(${JSON.stringify(to)})\`, which is not a path or an \`http(s)\` URL, so the redirect was refused and the call answered 500. Validate the value passed to \`redirect()\` before using it, especially when it comes from the request.`);
1002
+ }
1003
+ function isIterable(value) {
1004
+ return typeof value === "object" && value !== null && typeof value[Symbol.asyncIterator] === "function";
1005
+ }
1006
+ /**
1007
+ * An answer that arrives over time: one JSON line for each value yielded.
1008
+ *
1009
+ * Produced from `start`, so the function keeps running inside the request it
1010
+ * was called for: a `pull` is made from wherever the body is read, where there
1011
+ * is no request. It waits to be asked all the same, so a reader that falls
1012
+ * behind holds the function at its next `yield` rather than filling memory.
1013
+ *
1014
+ * A failure after the first value cannot become a status, so it is one last
1015
+ * line that says so and nothing else: a handler's message can name a table, a
1016
+ * column or a path.
1017
+ */
1018
+ function streamed(values, sendContext, id, reveal) {
1019
+ const encoder = new TextEncoder();
1020
+ const line = (payload) => encoder.encode(`${JSON.stringify(payload)}\n`);
1021
+ const source = values[Symbol.asyncIterator]();
1022
+ let wanted = null;
1023
+ let cancelled = false;
1024
+ const produce = async (controller) => {
1025
+ try {
1026
+ if (Object.keys(sendContext).length > 0) controller.enqueue(line({ c: encodeWire(sendContext) }));
1027
+ for (;;) {
1028
+ if ((controller.desiredSize ?? 1) <= 0) await new Promise((resolve) => {
1029
+ wanted = resolve;
1030
+ });
1031
+ if (cancelled) return;
1032
+ const next = await source.next();
1033
+ if (cancelled || next.done === true) break;
1034
+ controller.enqueue(line({ v: encodeWire(next.value) }));
1035
+ }
1036
+ if (!cancelled) controller.close();
1037
+ } catch (error) {
1038
+ if (cancelled) return;
1039
+ const thrown = reveal(error);
1040
+ const happened = `The server function ${JSON.stringify(id)} threw while streaming its result`;
1041
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
1042
+ console.error(`[barq] ${happened}, so the stream ended early and the caller receives a \`ServerFnError\`. The error:`, error);
1043
+ controller.enqueue(line(thrown === void 0 ? { e: 1 } : {
1044
+ e: 1,
1045
+ t: thrown
1046
+ }));
1047
+ controller.close();
1048
+ }
1049
+ };
1050
+ const body = new ReadableStream({
1051
+ start(controller) {
1052
+ produce(controller);
1053
+ },
1054
+ pull() {
1055
+ const waiting = wanted;
1056
+ wanted = null;
1057
+ waiting?.();
1058
+ },
1059
+ cancel() {
1060
+ cancelled = true;
1061
+ const waiting = wanted;
1062
+ wanted = null;
1063
+ waiting?.();
1064
+ source.return?.();
1065
+ }
1066
+ });
1067
+ return new Response(body, { headers: {
1068
+ "content-type": "application/x-ndjson; charset=utf-8",
1069
+ "cache-control": "no-store",
1070
+ [RPC_CONTROL]: RPC_STREAM
1071
+ } });
1072
+ }
1073
+ const DEFAULT_BODY_LIMIT = 1048576;
1074
+ /**
1075
+ * The request's body behind a cap, as something that can still be parsed.
1076
+ *
1077
+ * The declared length is only the early exit. A chunked request declares none
1078
+ * and a header can understate, so the stream is counted as it is read and
1079
+ * errors the moment it passes the limit, with the rest left unread.
1080
+ *
1081
+ * A `Response` carrying the content type, because that is what parses a
1082
+ * multipart body: the boundary is in the header, and srvx's own
1083
+ * `limitRequestBody` drops it and so cannot read a form.
1084
+ */
1085
+ function capped(request, limit) {
1086
+ if (Number(request.headers.get("content-length")) > limit) throw createBodyTooLargeError(limit);
1087
+ const type = request.headers.get("content-type");
1088
+ return new Response(request.body === null ? null : limitBodyStream(request.body, limit), type === null ? void 0 : { headers: { "content-type": type } });
1089
+ }
1090
+ /**
1091
+ * A GET call's payload: the body a POST would have sent, in `?payload=`.
1092
+ *
1093
+ * Held to the body limit, since a URL is a body a caller chose the size of,
1094
+ * and refused as a 413 the way an oversized body is.
1095
+ */
1096
+ function queryPayload(url, limit) {
1097
+ const payload = url.searchParams.get(PAYLOAD_PARAM);
1098
+ if (payload === null) return {};
1099
+ if (payload.length > limit) throw createBodyTooLargeError(limit);
1100
+ return JSON.parse(payload);
1101
+ }
1102
+ /**
1103
+ * What a body that could not be read is answered with.
1104
+ *
1105
+ * By the error's code and not by who threw it: a server in front that enforces
1106
+ * `maxRequestBodySize` fails the read with the same error, and that caller is
1107
+ * owed the same 413.
1108
+ */
1109
+ function unreadable(error) {
1110
+ return error?.code === "ERR_BODY_TOO_LARGE" ? new Response("payload too large", { status: 413 }) : new Response("bad request", { status: 400 });
1111
+ }
1112
+ /**
1113
+ * Whether the body is a form rather than a value. The enhanced path posts
1114
+ * `FormData` to the data channel so that a handler sees the SAME input type
1115
+ * whether or not JS ran.
1116
+ */
1117
+ function isFormBody(request) {
1118
+ const type = request.headers.get("content-type") ?? "";
1119
+ return type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded");
1120
+ }
1121
+ /**
1122
+ * Back where the form was. 303 and not 302, so the browser re-issues as GET and
1123
+ * a reload does not repost — the POST/redirect/GET the no-JS path exists for.
1124
+ *
1125
+ * `Referer` is used only as a destination and never as a decision. SvelteKit's
1126
+ * docs make the distinction for the same reason: values derived from the
1127
+ * request are fine to navigate to and never fine to authorize with.
1128
+ */
1129
+ function seeOther(request) {
1130
+ const referer = request.headers.get("referer");
1131
+ const origin = new URL(request.url).origin;
1132
+ let location = "/";
1133
+ if (referer !== null) try {
1134
+ const target = new URL(referer);
1135
+ if (target.origin === origin) {
1136
+ const path = target.pathname + target.search;
1137
+ location = path.startsWith("//") ? origin + path : path;
1138
+ }
1139
+ } catch {}
1140
+ return new Response(null, {
1141
+ status: 303,
1142
+ headers: { location }
1143
+ });
1144
+ }
1145
+ //#endregion
1146
+ export { mounted as a, unmountAll as c, mountOnDemand as i, handleServerFn as n, mountedFn as o, mount as r, originAllowed as s, crossOriginRefused as t };
1147
+
1148
+ //# sourceMappingURL=server-BV3xKmLa.js.map