@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
package/src/server.ts ADDED
@@ -0,0 +1,990 @@
1
+ /**
2
+ * The request handler: one URL shape, one lookup, and the checks that run
3
+ * before a handler body does.
4
+ *
5
+ * Every default here is the strict one, because the survey found the same four
6
+ * failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,
7
+ * publicly-mounted endpoint reached by an id enumerable from the client bundle.
8
+ * Each is cheap to close and expensive to retrofit.
9
+ */
10
+
11
+ import { isDev, isSafeError } from "@barqjs/core";
12
+ import {
13
+ commitEventResponse,
14
+ commitResponseStub,
15
+ createRequestEvent,
16
+ isNavigable,
17
+ } from "@barqjs/web/internal";
18
+ import { diagnosticsEnabled, emitDiagnostic } from "@barqjs/core/internal";
19
+ import { decodeWire, encodeWire } from "@barqjs/server/codec";
20
+ import { provideRequestEvent } from "@barqjs/server/storage";
21
+ import { createBodyTooLargeError, limitBodyStream } from "srvx/body-limit";
22
+
23
+ import {
24
+ type ResponseDraft,
25
+ applyResponseDraft,
26
+ createResponseDraft,
27
+ draftedStatus,
28
+ invalidatedFrames,
29
+ setRequestMiddlewareContext,
30
+ } from "./context.ts";
31
+ import {
32
+ NOT_FOUND,
33
+ PAYLOAD_PARAM,
34
+ REDIRECT,
35
+ RPC_CALLER,
36
+ RPC_CONTEXT,
37
+ RPC_CONTROL,
38
+ RPC_RESPONSE,
39
+ RPC_THROWN,
40
+ RPC_STREAM,
41
+ type RpcControl,
42
+ type RpcStreamLine,
43
+ type ServerFnInputAnswer,
44
+ type ServerFnIssue,
45
+ type ServerFnThrown,
46
+ } from "./client.ts";
47
+ import {
48
+ type AnyServerFn,
49
+ DATA_SUFFIX,
50
+ LIVE_SUFFIX,
51
+ type InputError,
52
+ isInputError,
53
+ RPC_PREFIX,
54
+ type ServerFn,
55
+ isServerFn,
56
+ runRequestMiddleware,
57
+ startOptions,
58
+ takeSendContext,
59
+ } from "./index.ts";
60
+ import { serverTiming } from "./timing.ts";
61
+ import {
62
+ type ServerFrame,
63
+ flightResponse,
64
+ frameResponse,
65
+ mountedFrames,
66
+ serverFrame,
67
+ } from "./frames-server.ts";
68
+ import { FRAMES_HEADER, installFrames, isFrame } from "./frames.ts";
69
+ import { liveResponse } from "./live-server.ts";
70
+
71
+ installFrames(serverFrame as never);
72
+
73
+ /**
74
+ * id → function, and the ONLY way an id becomes callable.
75
+ *
76
+ * A `Map` rather than an object, because the id comes off the wire and an
77
+ * object's prototype is reachable through one. A client-supplied name used as a
78
+ * raw property access has shipped as a critical RCE elsewhere: asking for
79
+ * `constructor` yields `Function`, and then arbitrary code. `Map.get`
80
+ * has no prototype chain to walk into, so the guard is structural rather than a
81
+ * `hasOwnProperty` call someone can later forget.
82
+ */
83
+ interface Mounted {
84
+ readonly registry: Map<string, ServerFn<unknown, unknown>>;
85
+ /** How to mount the build's manifest, once something has said. */
86
+ manifest: (() => Promise<unknown>) | null;
87
+ }
88
+
89
+ /**
90
+ * ONE registry per process, whichever copy of this module asks.
91
+ *
92
+ * A build compiles this module INTO its server bundle, and a host that serves
93
+ * that bundle through its own `serveBarq` has imported a second copy. Kept in
94
+ * a module variable, each copy had a registry of its own: the bundle mounted
95
+ * every function into one and the host answered 404 out of the other.
96
+ */
97
+ const MOUNTED = ((globalThis as Record<symbol, unknown>)[Symbol.for("barq.start.server-fns")] ??= {
98
+ registry: new Map<string, ServerFn<unknown, unknown>>(),
99
+ manifest: null,
100
+ }) as Mounted;
101
+
102
+ const REGISTRY = MOUNTED.registry;
103
+
104
+ /**
105
+ * Say how the build's manifest is mounted, so a call can ask for it.
106
+ *
107
+ * The server entry imports the manifest when it first renders a page, which is
108
+ * late for a function called before any page has been asked for: a server that
109
+ * has just started and a browser tab that was already open. The id it names
110
+ * was in no registry yet, and the answer was a 404 for a function that exists.
111
+ */
112
+ export function mountOnDemand(manifest: () => Promise<unknown>): void {
113
+ MOUNTED.manifest = manifest;
114
+ }
115
+
116
+ /**
117
+ * Mount a server function. The compiler emits one call per EXPORTED server
118
+ * function in a module compiled for the server.
119
+ *
120
+ * Export-ness is what decides reachability, which is SvelteKit's rule and the
121
+ * only genuine notion of an internal server function in the survey: a
122
+ * non-exported one is never registered, so it has no id and no endpoint, and is
123
+ * still callable from its siblings.
124
+ */
125
+ export function mount(id: string, fn: AnyServerFn): void {
126
+ if (!isServerFn(fn))
127
+ throw new TypeError(
128
+ `[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(...)\`.`,
129
+ );
130
+ if (id === "")
131
+ throw new TypeError(
132
+ "[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.",
133
+ );
134
+ // RE-MOUNTING AN ID REPLACES, and refusing it was a dev-server bug rather
135
+ // than a safeguard. The generated manifest is invalidated whenever a
136
+ // server-function module is transformed and re-imported on the next request,
137
+ // while this registry lives in a module nothing invalidates — so the second
138
+ // evaluation was refusing ids the first had legitimately claimed, and every
139
+ // page answered 500 after the first edit.
140
+ //
141
+ // Nothing is lost by replacing: an id is `<root-relative file>#<export>`, so
142
+ // two DISTINCT functions can only collide if two paths normalise to one, and
143
+ // the manifest generator refuses that where it can see the whole set at once.
144
+ // Here there is no second set to compare against — only the same module,
145
+ // again, newer.
146
+ // Stamped rather than read. The compiler leaves the SERVER half of a module
147
+ // alone — it is the module, compiled — so the builder has no id of its own;
148
+ // the id lives in the manifest the build generates, and mounting is where the
149
+ // two meet. `formAttr` reads it back off the function to write a form's
150
+ // action, so a function that is mounted has a URL and one that is not has
151
+ // neither an id nor an endpoint.
152
+ fn.meta.id = id;
153
+ REGISTRY.set(id, fn);
154
+ }
155
+
156
+ /** The mounted surface, for the build to record and a reviewer to read. */
157
+ export function mounted(): string[] {
158
+ return [...REGISTRY.keys()].toSorted();
159
+ }
160
+
161
+ /**
162
+ * The function mounted at an id, or `undefined`.
163
+ *
164
+ * Exported for the BUILD's chain check, which has to ask each reachable id what
165
+ * middleware it actually carries. It reads the registry inside whichever bundle
166
+ * it is called from, which is why the check runs through the server entry
167
+ * rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`
168
+ * INTO the ssr bundle, so a plugin importing this module would be asking a
169
+ * second, empty registry.
170
+ */
171
+ export function mountedFn(id: string): ServerFn<unknown, unknown> | undefined {
172
+ return REGISTRY.get(id);
173
+ }
174
+
175
+ /** Test seam. Not for application use. */
176
+ export function unmountAll(): void {
177
+ REGISTRY.clear();
178
+ MOUNTED.manifest = null;
179
+ }
180
+
181
+ export interface HandlerOptions {
182
+ /**
183
+ * Origins allowed to call, beyond the request's own. Same-origin is always
184
+ * allowed; this widens it.
185
+ */
186
+ allowedOrigins?: readonly string[];
187
+ /**
188
+ * The largest body a call may send, in bytes. 1 MiB when omitted.
189
+ *
190
+ * Enforced on the bytes as they are read, and answered with a 413. The body
191
+ * is parsed BEFORE the chain runs, so this is the only thing standing between
192
+ * a caller no middleware has seen yet and the server's memory.
193
+ *
194
+ * srvx's `maxRequestBodySize` is the same idea for the whole server and has
195
+ * no default; this one is for the server-function channel alone, so it holds
196
+ * under a handler that srvx is not in front of.
197
+ */
198
+ maxBodySize?: number;
199
+ /**
200
+ * The largest FORM body, multipart or urlencoded. `maxBodySize` when omitted.
201
+ *
202
+ * Apart from it because a file upload is the one body that legitimately
203
+ * outgrows the default, and raising `maxBodySize` to admit one would widen
204
+ * the value channel by the same amount for no caller that needs it. A form is
205
+ * parsed whole into memory, so this is what one request can make the server
206
+ * hold.
207
+ */
208
+ maxFormSize?: number;
209
+ /**
210
+ * What a failed call may tell its caller about the error, beyond its status.
211
+ *
212
+ * Only the development server passes it, so a production server answers a
213
+ * handler's failure with the status and a fixed line and nothing of the
214
+ * error: its message can name a table, a column or a path. In development the
215
+ * caller is the developer, and the error's name, message and stack (mapped
216
+ * to source by the dev server) are what make the failure debuggable from the
217
+ * browser.
218
+ */
219
+ revealError?: (error: unknown) => ServerFnThrown;
220
+ /**
221
+ * Whether some route in this application can reach this id.
222
+ *
223
+ * The narrow half of the route-action manifest. Export-ness already decides
224
+ * what is MOUNTED, and that is deliberately generous — a server function
225
+ * exported for a sibling to import is mounted whether or not any page calls
226
+ * it. Next.js concedes the consequence in its own release notes: "Even if a
227
+ * Server Action or utility function is not imported elsewhere in your code,
228
+ * it's still a publicly accessible HTTP endpoint."
229
+ *
230
+ * This closes that: an id no route reaches answers the 404 an unknown id
231
+ * already answers, so the two are indistinguishable from outside.
232
+ *
233
+ * It takes NO route from the caller, deliberately. A client-supplied route
234
+ * selecting a policy lets the caller pick the weakest one that reaches the
235
+ * action, and this file's own rule says why that is not allowed — values
236
+ * derived from the request are fine to navigate to and never fine to
237
+ * authorize with. Which CHAIN runs is decided at build time by
238
+ * `@barqjs/router`, not here and not per request.
239
+ */
240
+ reachable?: (id: string) => boolean;
241
+ }
242
+
243
+ /**
244
+ * Is this request allowed to invoke a server function?
245
+ *
246
+ * `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback
247
+ * is Waku's post-CVE shape and it is the strictest default found: `Origin` is
248
+ * legitimately absent on some same-origin requests and on non-browser clients,
249
+ * while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged
250
+ * from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.
251
+ */
252
+ export function originAllowed(request: Request, options?: HandlerOptions): boolean {
253
+ const origin = request.headers.get("origin");
254
+ if (origin !== null) {
255
+ // A sandboxed iframe sends the literal string, so it is refused rather than
256
+ // read as absent and fallen through.
257
+ if (origin === "null") return false;
258
+ if (origin === new URL(request.url).origin) return true;
259
+ return options?.allowedOrigins?.includes(origin) ?? false;
260
+ }
261
+ const site = request.headers.get("sec-fetch-site");
262
+ if (site === null) return false;
263
+ return site === "same-origin" || site === "none";
264
+ }
265
+
266
+ /** Methods that cannot change state, so CSRF does not apply to them. */
267
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
268
+
269
+ /**
270
+ * Is this a request a BROWSER made from another origin?
271
+ *
272
+ * A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole
273
+ * design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be
274
+ * called by this application's own pages — so a request with no origin signal at
275
+ * all is refused there, because there is no legitimate caller that omits one.
276
+ *
277
+ * A route handler is the opposite: an API route exists so that something OTHER
278
+ * than a browser can call it. A Stripe webhook, a GitHub delivery, a cron
279
+ * hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and
280
+ * refusing on their absence would refuse the main reason API routes exist.
281
+ *
282
+ * So this answers the narrower question, and the narrower question is the one
283
+ * CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER
284
+ * with the victim's cookies attached, and a browser making a cross-origin
285
+ * state-changing request always says so — `Origin` on any cross-origin POST
286
+ * since forever, `Sec-Fetch-Site` on everything in every current browser. So:
287
+ * refuse when a signal is present and says cross-origin; allow when there is no
288
+ * signal, because then it is not a browser and cannot be a forgery.
289
+ *
290
+ * `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than
291
+ * read as absent, which is a bypass that has shipped.
292
+ */
293
+ export function crossOriginRefused(request: Request, allowedOrigins?: readonly string[]): boolean {
294
+ if (SAFE_METHODS.has(request.method.toUpperCase())) return false;
295
+
296
+ const origin = request.headers.get("origin");
297
+ if (origin !== null) {
298
+ if (origin === "null") return true;
299
+ if (origin === new URL(request.url).origin) return false;
300
+ return !(allowedOrigins?.includes(origin) ?? false);
301
+ }
302
+
303
+ const site = request.headers.get("sec-fetch-site");
304
+ // No signal at all: not a browser, so not a forgery.
305
+ if (site === null) return false;
306
+ return site !== "same-origin" && site !== "none";
307
+ }
308
+
309
+ /**
310
+ * Handle one server-function request, or return null if the URL is not one.
311
+ *
312
+ * Returning null rather than a 404 is what lets this compose as middleware in
313
+ * front of a page handler.
314
+ */
315
+ export async function handleServerFn(
316
+ request: Request,
317
+ options?: HandlerOptions,
318
+ ): Promise<Response | null> {
319
+ const url = new URL(request.url);
320
+ if (!url.pathname.startsWith(RPC_PREFIX)) return null;
321
+
322
+ // A mutation must not be reachable by navigation. RedwoodSDK shipped server
323
+ // functions invocable over GET, which made a plain link a one-click mutation
324
+ // carrying SameSite=Lax cookies. A GET reaches only a function that asked for
325
+ // it, and only with the header no link can send; both are checked below.
326
+ const method = request.method;
327
+ if (method !== "POST" && method !== "GET") {
328
+ return new Response("method not allowed", { status: 405, headers: { allow: "GET, POST" } });
329
+ }
330
+ if (!originAllowed(request, options)) return new Response("forbidden", { status: 403 });
331
+
332
+ // The URL decides the shape, so a form and an RPC call cannot be confused for
333
+ // one another by a header either of them can set.
334
+ const path = url.pathname.slice(RPC_PREFIX.length);
335
+ // The live address answers what the data address does, framed as events for
336
+ // as long as the answer stands. Only `live`'s loop calls it.
337
+ const isLive = path.endsWith(LIVE_SUFFIX);
338
+ const isData = isLive || path.endsWith(DATA_SUFFIX);
339
+ let id: string;
340
+ try {
341
+ id = decodeURIComponent(
342
+ isLive
343
+ ? path.slice(0, -LIVE_SUFFIX.length)
344
+ : isData
345
+ ? path.slice(0, -DATA_SUFFIX.length)
346
+ : path,
347
+ );
348
+ } catch {
349
+ // Not percent-encoding at all, so it names nothing.
350
+ return new Response("bad request", { status: 400 });
351
+ }
352
+
353
+ let fn = REGISTRY.get(id);
354
+ if (fn === undefined && MOUNTED.manifest !== null) {
355
+ await MOUNTED.manifest();
356
+ fn = REGISTRY.get(id);
357
+ }
358
+ if (fn === undefined) return new Response("not found", { status: 404 });
359
+ // Same answer as an unknown id, so a caller cannot tell a function that
360
+ // exists but is unrouted from one that does not exist.
361
+ if (options?.reachable?.(id) === false) return new Response("not found", { status: 404 });
362
+ // The function's own method, and only on the channel that can carry it: a
363
+ // form is a POST, so a GET function has the data channel alone.
364
+ const expected = fn.meta.method ?? "POST";
365
+ if (method !== expected) {
366
+ return new Response("method not allowed", { status: 405, headers: { allow: expected } });
367
+ }
368
+ if (method === "GET") {
369
+ if (!isData) return new Response("not found", { status: 404 });
370
+ if (request.headers.get(RPC_CALLER) === null) return new Response("forbidden", { status: 403 });
371
+ }
372
+
373
+ const bodyLimit = options?.maxBodySize ?? DEFAULT_BODY_LIMIT;
374
+ const target = fn;
375
+ // The draft the handler writes to through `setCookie` / `setResponseHeader`,
376
+ // held HERE because the response is built after the handler has returned.
377
+ const draft = createResponseDraft();
378
+
379
+ /**
380
+ * The call itself: read the body, run the function, build the answer. The
381
+ * innermost step of the request middleware chain, so a global middleware
382
+ * that refuses does so before a byte of the payload has been parsed.
383
+ */
384
+ const respond = async (): Promise<Response> => {
385
+ let input: unknown;
386
+ let clientContext: Record<string, unknown> | undefined;
387
+ if (isData && (method === "GET" || !isFormBody(request))) {
388
+ try {
389
+ const body = (
390
+ method === "GET" ? queryPayload(url, bodyLimit) : await capped(request, bodyLimit).json()
391
+ ) as {
392
+ input?: unknown;
393
+ context?: unknown;
394
+ };
395
+ input = body?.input === undefined ? undefined : decodeWire(body.input);
396
+ // WHAT THE CLIENT HALVES SENT, and it is UNTRUSTED — a caller writes this
397
+ // body by hand as readily as the stub does. It reaches a server half as
398
+ // `clientContext` and is never merged into `context`; `serverRpc` says
399
+ // what merging it would let through. Spread, so a body that put a string
400
+ // or a list here still hands the chain an object.
401
+ clientContext =
402
+ body?.context === undefined ? undefined : { ...(decodeWire(body.context) as object) };
403
+ } catch (error) {
404
+ return unreadable(error);
405
+ }
406
+ } else {
407
+ try {
408
+ input = await capped(request, options?.maxFormSize ?? bodyLimit).formData();
409
+ } catch (error) {
410
+ return unreadable(error);
411
+ }
412
+ }
413
+
414
+ try {
415
+ // `{ data }` on the value channel; a bare `FormData` on the form one, which
416
+ // is the shape `<form action={fn}>` hands the function on the enhanced path
417
+ // — so a handler sees the same input type whether or not JS ran.
418
+ // `sendContext` is taken INSIDE the request context, because that is where
419
+ // the function's chain left it: each request has its own, so two calls that
420
+ // settle together cannot read one another's.
421
+ const result = await (input instanceof FormData
422
+ ? target(input)
423
+ : (target as (o: unknown, c?: Record<string, unknown>) => Promise<unknown>)(
424
+ { data: input },
425
+ clientContext,
426
+ ));
427
+ const sendContext = takeSendContext();
428
+ if (isLive) {
429
+ if (result instanceof Response) return applyResponseDraft(result, draft);
430
+ return applyResponseDraft(liveResponse(result, request), draft);
431
+ }
432
+ // A RETURNED RESPONSE IS HONOURED ON BOTH CHANNELS, and it did not used to
433
+ // be: the value channel handed it to `encodeWire`, which answered
434
+ // `Seroval Error (step: 1)` and a 500 with nothing in it. So a function that
435
+ // set a cookie by returning a response worked with JS disabled and crashed
436
+ // with JS enabled — the one divergence the form path exists to prevent.
437
+ if (result instanceof Response) {
438
+ // The data channel's client reads every other answer as a wire value, so
439
+ // this one says it is not. A browser following a form needs no telling.
440
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_RESPONSE);
441
+ return applyResponseDraft(result, draft);
442
+ }
443
+ // A component is a frame: the region it renders, for the page to apply.
444
+ // A browser following a form has no page to apply it to.
445
+ if (isFrame(result)) {
446
+ if (isData) return applyResponseDraft(await frameResponse(result as ServerFrame), draft);
447
+ return applyResponseDraft(seeOther(request), draft);
448
+ }
449
+ if (isIterable(result)) {
450
+ if (isData) {
451
+ return applyResponseDraft(streamed(result, sendContext, id, revealerOf(options)), draft);
452
+ }
453
+ // A browser following a form has nothing to read a stream with, so the
454
+ // function is told nobody is listening and the form goes back.
455
+ void result[Symbol.asyncIterator]().return?.();
456
+ return applyResponseDraft(seeOther(request), draft);
457
+ }
458
+ if (isData) {
459
+ // `draftedStatus` here and NOT inside `applyResponseDraft`, because the
460
+ // two answer different questions: this response is the framework's to
461
+ // build, so `setResponseStatus(201)` decides it — where a response the
462
+ // handler RETURNED has already decided for itself.
463
+ const answer = draftedStatus(draft, 200);
464
+ // SINGLE FLIGHT: a mutation that said which frames it changed answers
465
+ // with them, rendered again for the arguments the page has them
466
+ // mounted with, beside its value. Each is asked for through its own
467
+ // function, so its validator and its middleware decide as for a call.
468
+ const mountedHere = mountedFrames(request.headers.get(FRAMES_HEADER));
469
+ const changed = invalidatedFrames();
470
+ if (mountedHere.length > 0 && changed.size > 0) {
471
+ const flight = await flightResponse(
472
+ Object.keys(sendContext).length === 0 ? result : { result, context: sendContext },
473
+ mountedHere,
474
+ changed,
475
+ async (frame) => {
476
+ const asked = REGISTRY.get(frame.id);
477
+ if (asked === undefined || options?.reachable?.(frame.id) === false) return undefined;
478
+ try {
479
+ return await (asked as (o: unknown) => Promise<unknown>)({
480
+ data: frame.args === undefined ? undefined : decodeWire(frame.args),
481
+ });
482
+ } catch (error) {
483
+ console.error(
484
+ `[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:`,
485
+ error,
486
+ );
487
+ return undefined;
488
+ }
489
+ },
490
+ );
491
+ if (Object.keys(sendContext).length > 0) flight.headers.set(RPC_CONTEXT, "1");
492
+ return applyResponseDraft(
493
+ new Response(flight.body, { ...answer, headers: flight.headers }),
494
+ draft,
495
+ );
496
+ }
497
+ // The ordinary shape is the RESULT and nothing around it. A chain that
498
+ // sent something back gets the envelope instead, flagged by a header, so
499
+ // a call that sends nothing pays neither the wrapper nor a second parse.
500
+ if (Object.keys(sendContext).length === 0) {
501
+ return applyResponseDraft(Response.json(encodeWire(result), answer), draft);
502
+ }
503
+ return applyResponseDraft(
504
+ Response.json(encodeWire({ result, context: sendContext }), {
505
+ ...answer,
506
+ headers: { [RPC_CONTEXT]: "1" },
507
+ }),
508
+ draft,
509
+ );
510
+ }
511
+ // Otherwise the browser goes back where it came from, which is what makes
512
+ // the no-JS path a round trip rather than a dead end.
513
+ return applyResponseDraft(seeOther(request), draft);
514
+ } catch (error) {
515
+ // A middleware rejects by throwing a Response — `throw new Response("", {
516
+ // status: 401 })` — and it is returned as it stands.
517
+ // The draft rides an error out as well. A middleware that rotated a session
518
+ // cookie and THEN refused must not lose the rotation — the browser would
519
+ // keep replaying a token the server has already retired.
520
+ if (error instanceof Response) return thrownAnswer(error, isData, draft);
521
+ // `throw redirect(...)` and `throw notFound()` are ANSWERS, and a server
522
+ // function is entitled to both — a handler that finds the session expired
523
+ // redirects to the login page, and one asked for a row that is gone says
524
+ // so. Left to the catch-all below they would be a 500 with nothing in it,
525
+ // and the two most ordinary control-flow throws in the framework would be
526
+ // the two it could not carry.
527
+ const control = controlOf(error);
528
+ if (control !== null) {
529
+ return applyResponseDraft(
530
+ controlResponse(control, isData, (error as { headers?: unknown }).headers),
531
+ draft,
532
+ );
533
+ }
534
+ // A validation failure is the caller's fault and says so, with what was
535
+ // wrong with each field: the issues describe the caller's own input, so a
536
+ // form can show them. Anything else is reported without a body: a
537
+ // handler's message can name a table, a column or a path, and none of that
538
+ // is the caller's business.
539
+ if (isInputError(error)) {
540
+ return applyResponseDraft(
541
+ isData
542
+ ? Response.json(inputAnswer(error), { status: 400 })
543
+ : new Response("invalid input", { status: 400 }),
544
+ draft,
545
+ );
546
+ }
547
+ return applyResponseDraft(failed(id, error, isData, options, "threw"), draft);
548
+ }
549
+ };
550
+
551
+ // AFTER the method, the origin and the id have been checked, never before: a
552
+ // forged or mistyped call is refused above without a middleware having run
553
+ // for it, so it costs nothing and reaches nothing.
554
+ const context: Record<string, unknown> = {};
555
+ const timing = isDev ? serverTiming() : undefined;
556
+ const event = createRequestEvent(request, { response: draft });
557
+ try {
558
+ const response = await provideRequestEvent(event, () => {
559
+ setRequestMiddlewareContext(context);
560
+ return runRequestMiddleware(
561
+ startOptions().requestMiddleware ?? [],
562
+ { request, pathname: url.pathname, handlerType: "serverFn", context },
563
+ respond,
564
+ );
565
+ });
566
+ if (timing !== undefined) {
567
+ timing.phase("barq-fn", id);
568
+ draft.headers.append("server-timing", timing.header());
569
+ }
570
+ return commitEventResponse(response, event);
571
+ } catch (error) {
572
+ // A request middleware refuses the way a function's own does.
573
+ if (error instanceof Response)
574
+ return commitEventResponse(thrownAnswer(error, isData, draft), event);
575
+ return commitEventResponse(failed(id, error, isData, options, "middleware"), event);
576
+ } finally {
577
+ commitResponseStub(draft, { event });
578
+ }
579
+ }
580
+
581
+ /**
582
+ * The 400 a refused input answers with: the refusal and each issue with the
583
+ * path to the field it is about.
584
+ */
585
+ function inputAnswer(error: InputError): ServerFnInputAnswer {
586
+ const issues = (error as { issues?: ReadonlyArray<unknown> }).issues ?? [];
587
+ return {
588
+ error: "invalid input",
589
+ message: error.message,
590
+ issues: issues.map((issue): ServerFnIssue => {
591
+ const { message, path } = (issue ?? {}) as { message?: unknown; path?: unknown };
592
+ const keys = Array.isArray(path)
593
+ ? path.map((segment: unknown) => {
594
+ const key =
595
+ typeof segment === "object" && segment !== null && "key" in segment
596
+ ? segment.key
597
+ : segment;
598
+ return typeof key === "number" ? key : String(key);
599
+ })
600
+ : [];
601
+ return keys.length === 0
602
+ ? { message: String(message) }
603
+ : { message: String(message), path: keys };
604
+ }),
605
+ };
606
+ }
607
+
608
+ /**
609
+ * What a failed call may tell its caller: everything the development server
610
+ * asks for, and in production only an error the application branded with
611
+ * `markSafeError`, by its name and message.
612
+ */
613
+ function revealerOf(
614
+ options: HandlerOptions | undefined,
615
+ ): (error: unknown) => ServerFnThrown | undefined {
616
+ const reveal = options?.revealError;
617
+ return (error) => {
618
+ if (reveal !== undefined) return reveal(error);
619
+ if (!(error instanceof Error) || !isSafeError(error)) return undefined;
620
+ return { name: error.name, message: error.message };
621
+ };
622
+ }
623
+
624
+ /**
625
+ * A call that failed on the server: logged there, reported on the diagnostics
626
+ * channel, and answered 500. The caller learns what was thrown only when the
627
+ * development server asked for it.
628
+ */
629
+ function failed(
630
+ id: string,
631
+ error: unknown,
632
+ isData: boolean,
633
+ options: HandlerOptions | undefined,
634
+ where: "threw" | "middleware",
635
+ ): Response {
636
+ const thrown = revealerOf(options)(error);
637
+ const happened =
638
+ where === "threw"
639
+ ? `The server function ${JSON.stringify(id)} threw`
640
+ : `A request middleware threw before the server function ${JSON.stringify(id)} ran`;
641
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
642
+ console.error(
643
+ `[barq] ${happened}, so the call answered 500${thrown === undefined ? " without the error's text" : ""}. The error:`,
644
+ error,
645
+ );
646
+ if (thrown === undefined) return new Response("internal server error", { status: 500 });
647
+ return isData
648
+ ? Response.json({ error: "internal server error", thrown }, { status: 500 })
649
+ : new Response(
650
+ `internal server error\n\n${thrown.stack ?? `${thrown.name}: ${thrown.message}`}`,
651
+ {
652
+ status: 500,
653
+ },
654
+ );
655
+ }
656
+
657
+ function reportFailure(id: string, error: unknown, happened: string): void {
658
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
659
+ emitDiagnostic(
660
+ {
661
+ code: "SERVER_FUNCTION_FAILED",
662
+ kind: "ssr",
663
+ severity: "error",
664
+ message:
665
+ `${happened}: \`${text}\`. The caller received a 500. Fix the throw at the top of the ` +
666
+ "stack, or throw a `Response`, `redirect()` or `notFound()` to answer the caller on purpose.",
667
+ data: { id, error },
668
+ },
669
+ null,
670
+ );
671
+ }
672
+
673
+ /**
674
+ * A `Response` the chain or the handler threw, as the answer. The data
675
+ * channel's client rejects the call with it, so the header says it was thrown
676
+ * rather than returned; a browser following a form needs no telling.
677
+ */
678
+ function thrownAnswer(error: Response, isData: boolean, draft: ResponseDraft): Response {
679
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_THROWN);
680
+ return applyResponseDraft(error, draft);
681
+ }
682
+
683
+ /**
684
+ * Read a thrown value as a control answer, by BRAND rather than by class.
685
+ *
686
+ * The classes are `@barqjs/router`'s and this package cannot import them; see
687
+ * {@link REDIRECT}. A brand check is also what lets the same code recognise a
688
+ * redirect the router threw and one `@barqjs/start/client` rebuilt off the
689
+ * wire, which matters when a server function calls another one.
690
+ */
691
+ function controlOf(error: unknown): RpcControl | null {
692
+ if (typeof error !== "object" || error === null) return null;
693
+ const branded = error as Record<symbol, unknown> & {
694
+ to?: unknown;
695
+ status?: unknown;
696
+ options?: unknown;
697
+ data?: unknown;
698
+ routeId?: unknown;
699
+ };
700
+ if (branded[REDIRECT] === true) {
701
+ // The shape is checked rather than trusted: the brand says what this claims
702
+ // to be, and a `to` that is not a string would put `undefined` in a
703
+ // `Location` header.
704
+ if (typeof branded.to !== "string") return null;
705
+ const status = typeof branded.status === "number" ? branded.status : 302;
706
+ const options = describedNavigation(branded.options);
707
+ return {
708
+ kind: "redirect",
709
+ to: branded.to,
710
+ status,
711
+ ...(options === undefined ? {} : { options: encodeWire(options) }),
712
+ };
713
+ }
714
+ if (branded[NOT_FOUND] === true) {
715
+ const message = (error as { message?: unknown }).message;
716
+ return {
717
+ kind: "not-found",
718
+ message: typeof message === "string" ? message : "not found",
719
+ ...(branded.data === undefined ? {} : { data: encodeWire(branded.data) }),
720
+ ...(typeof branded.routeId === "string" ? { routeId: branded.routeId } : {}),
721
+ };
722
+ }
723
+ return null;
724
+ }
725
+
726
+ /** The parts of a navigation that are values, and so can be sent. */
727
+ const NAVIGATION = ["to", "from", "params", "search", "hash", "replace", "reloadDocument", "href"];
728
+
729
+ /**
730
+ * The navigation an options-form redirect described, as far as it can cross.
731
+ *
732
+ * A function among them cannot: `search: (current) => ...` is asked about a
733
+ * location only the browser has. A redirect holding one is sent as its resolved
734
+ * target alone, which is what every redirect was sent as before this existed.
735
+ * `statusCode` and `headers` are the answer rather than the navigation, and
736
+ * travel as the status and on the response.
737
+ */
738
+ function describedNavigation(described: unknown): Record<string, unknown> | undefined {
739
+ if (typeof described !== "object" || described === null) return undefined;
740
+ const given = described as Record<string, unknown>;
741
+ const out: Record<string, unknown> = {};
742
+ for (const name of NAVIGATION) {
743
+ const value = given[name];
744
+ if (value === undefined) continue;
745
+ if (typeof value === "function") return undefined;
746
+ out[name] = value;
747
+ }
748
+ if (typeof given.statusCode === "number") out.statusCode = given.statusCode;
749
+ return out;
750
+ }
751
+
752
+ /**
753
+ * A control answer, on whichever channel asked.
754
+ *
755
+ * THE TWO CHANNELS DIVERGE HERE ON PURPOSE, because their clients are different
756
+ * programs. The form channel's client is a BROWSER following the response
757
+ * itself, so a redirect has to be a real 3xx with a `Location`. The data
758
+ * channel's client is `clientRpc`, and a real 3xx there would be FOLLOWED by
759
+ * `fetch` — the caller would receive the target page's HTML instead of a
760
+ * navigation. So the data channel answers 200 and describes the redirect in the
761
+ * body, and the client re-throws it for the router to act on. That is a soft
762
+ * navigation rather than a document load, which is both correct and faster;
763
+ * TanStack returns the raw 3xx and the fetch follows it.
764
+ *
765
+ * `not-found` is a 404 on both, because 404 is the honest status and no client
766
+ * follows one.
767
+ *
768
+ * `extra` is the thrown value's own `headers`, which are the response's on
769
+ * either channel: a redirect that signs a visitor out carries the cookie that
770
+ * does it.
771
+ */
772
+ function controlResponse(control: RpcControl, isData: boolean, extra?: unknown): Response {
773
+ const headers = answerHeaders(extra);
774
+ if (control.kind === "not-found") {
775
+ if (!isData) return new Response(control.message, { status: 404, headers });
776
+ headers.set(RPC_CONTROL, control.kind);
777
+ return Response.json(control, { status: 404, headers });
778
+ }
779
+ if (!isNavigable(control.to)) {
780
+ reportRefusedRedirect(control.to);
781
+ return new Response("bad redirect", { status: 500 });
782
+ }
783
+ if (isData) {
784
+ headers.set(RPC_CONTROL, control.kind);
785
+ return Response.json(control, { status: 200, headers });
786
+ }
787
+ // 303 unless the handler asked for something else, so the browser re-issues
788
+ // as GET and a reload does not repost — the same reason `seeOther` below is
789
+ // 303. A handler that set an explicit status gets the one it set.
790
+ const status = control.status === 302 ? 303 : control.status;
791
+ headers.set("location", control.to);
792
+ return new Response(null, { status, headers });
793
+ }
794
+
795
+ /** A thrown answer's `headers`, or none when it carried nothing a response can take. */
796
+ function answerHeaders(extra: unknown): Headers {
797
+ if (extra === undefined || extra === null) return new Headers();
798
+ try {
799
+ return new Headers(extra as HeadersInit);
800
+ } catch {
801
+ return new Headers();
802
+ }
803
+ }
804
+
805
+ function reportRefusedRedirect(to: string): void {
806
+ console.error(
807
+ `[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. ` +
808
+ "Validate the value passed to `redirect()` before using it, especially when it comes from the request.",
809
+ );
810
+ }
811
+
812
+ function isIterable(value: unknown): value is AsyncIterable<unknown> {
813
+ return (
814
+ typeof value === "object" &&
815
+ value !== null &&
816
+ typeof (value as Partial<AsyncIterable<unknown>>)[Symbol.asyncIterator] === "function"
817
+ );
818
+ }
819
+
820
+ /**
821
+ * An answer that arrives over time: one JSON line for each value yielded.
822
+ *
823
+ * Produced from `start`, so the function keeps running inside the request it
824
+ * was called for: a `pull` is made from wherever the body is read, where there
825
+ * is no request. It waits to be asked all the same, so a reader that falls
826
+ * behind holds the function at its next `yield` rather than filling memory.
827
+ *
828
+ * A failure after the first value cannot become a status, so it is one last
829
+ * line that says so and nothing else: a handler's message can name a table, a
830
+ * column or a path.
831
+ */
832
+ function streamed(
833
+ values: AsyncIterable<unknown>,
834
+ sendContext: Record<string, unknown>,
835
+ id: string,
836
+ reveal: (error: unknown) => ServerFnThrown | undefined,
837
+ ): Response {
838
+ const encoder = new TextEncoder();
839
+ const line = (payload: RpcStreamLine): Uint8Array =>
840
+ encoder.encode(`${JSON.stringify(payload)}\n`);
841
+ const source = values[Symbol.asyncIterator]();
842
+ let wanted: (() => void) | null = null;
843
+ let cancelled = false;
844
+
845
+ const produce = async (
846
+ controller: ReadableStreamDefaultController<Uint8Array>,
847
+ ): Promise<void> => {
848
+ try {
849
+ if (Object.keys(sendContext).length > 0) {
850
+ controller.enqueue(line({ c: encodeWire(sendContext) }));
851
+ }
852
+ for (;;) {
853
+ if ((controller.desiredSize ?? 1) <= 0) {
854
+ await new Promise<void>((resolve) => {
855
+ wanted = resolve;
856
+ });
857
+ }
858
+ if (cancelled) return;
859
+ const next = await source.next();
860
+ if (cancelled || next.done === true) break;
861
+ controller.enqueue(line({ v: encodeWire(next.value) }));
862
+ }
863
+ if (!cancelled) controller.close();
864
+ } catch (error) {
865
+ if (cancelled) return;
866
+ const thrown = reveal(error);
867
+ const happened = `The server function ${JSON.stringify(id)} threw while streaming its result`;
868
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
869
+ console.error(
870
+ `[barq] ${happened}, so the stream ended early and the caller receives a \`ServerFnError\`. The error:`,
871
+ error,
872
+ );
873
+ controller.enqueue(line(thrown === undefined ? { e: 1 } : { e: 1, t: thrown }));
874
+ controller.close();
875
+ }
876
+ };
877
+
878
+ const body = new ReadableStream<Uint8Array>({
879
+ start(controller) {
880
+ void produce(controller);
881
+ },
882
+ pull() {
883
+ const waiting = wanted;
884
+ wanted = null;
885
+ waiting?.();
886
+ },
887
+ cancel() {
888
+ cancelled = true;
889
+ const waiting = wanted;
890
+ wanted = null;
891
+ waiting?.();
892
+ void source.return?.();
893
+ },
894
+ });
895
+ return new Response(body, {
896
+ headers: {
897
+ "content-type": "application/x-ndjson; charset=utf-8",
898
+ "cache-control": "no-store",
899
+ [RPC_CONTROL]: RPC_STREAM,
900
+ },
901
+ });
902
+ }
903
+
904
+ const DEFAULT_BODY_LIMIT = 1024 * 1024;
905
+
906
+ /**
907
+ * The request's body behind a cap, as something that can still be parsed.
908
+ *
909
+ * The declared length is only the early exit. A chunked request declares none
910
+ * and a header can understate, so the stream is counted as it is read and
911
+ * errors the moment it passes the limit, with the rest left unread.
912
+ *
913
+ * A `Response` carrying the content type, because that is what parses a
914
+ * multipart body: the boundary is in the header, and srvx's own
915
+ * `limitRequestBody` drops it and so cannot read a form.
916
+ */
917
+ function capped(request: Request, limit: number): Response {
918
+ if (Number(request.headers.get("content-length")) > limit) throw createBodyTooLargeError(limit);
919
+ const type = request.headers.get("content-type");
920
+ return new Response(
921
+ request.body === null ? null : limitBodyStream(request.body, limit),
922
+ type === null ? undefined : { headers: { "content-type": type } },
923
+ );
924
+ }
925
+
926
+ /**
927
+ * A GET call's payload: the body a POST would have sent, in `?payload=`.
928
+ *
929
+ * Held to the body limit, since a URL is a body a caller chose the size of,
930
+ * and refused as a 413 the way an oversized body is.
931
+ */
932
+ function queryPayload(url: URL, limit: number): unknown {
933
+ const payload = url.searchParams.get(PAYLOAD_PARAM);
934
+ if (payload === null) return {};
935
+ if (payload.length > limit) throw createBodyTooLargeError(limit);
936
+ return JSON.parse(payload);
937
+ }
938
+
939
+ /**
940
+ * What a body that could not be read is answered with.
941
+ *
942
+ * By the error's code and not by who threw it: a server in front that enforces
943
+ * `maxRequestBodySize` fails the read with the same error, and that caller is
944
+ * owed the same 413.
945
+ */
946
+ function unreadable(error: unknown): Response {
947
+ return (error as { code?: unknown } | null)?.code === "ERR_BODY_TOO_LARGE"
948
+ ? new Response("payload too large", { status: 413 })
949
+ : new Response("bad request", { status: 400 });
950
+ }
951
+
952
+ /**
953
+ * Whether the body is a form rather than a value. The enhanced path posts
954
+ * `FormData` to the data channel so that a handler sees the SAME input type
955
+ * whether or not JS ran.
956
+ */
957
+ function isFormBody(request: Request): boolean {
958
+ const type = request.headers.get("content-type") ?? "";
959
+ return type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded");
960
+ }
961
+
962
+ /**
963
+ * Back where the form was. 303 and not 302, so the browser re-issues as GET and
964
+ * a reload does not repost — the POST/redirect/GET the no-JS path exists for.
965
+ *
966
+ * `Referer` is used only as a destination and never as a decision. SvelteKit's
967
+ * docs make the distinction for the same reason: values derived from the
968
+ * request are fine to navigate to and never fine to authorize with.
969
+ */
970
+ function seeOther(request: Request): Response {
971
+ const referer = request.headers.get("referer");
972
+ const origin = new URL(request.url).origin;
973
+ let location = "/";
974
+ if (referer !== null) {
975
+ try {
976
+ const target = new URL(referer);
977
+ // An off-site Referer would make this an open redirect.
978
+ if (target.origin === origin) {
979
+ const path = target.pathname + target.search;
980
+ // A path that opens `//` is another HOST to a browser handed it alone,
981
+ // and `/\` parses to the same thing. Written with its origin it can only
982
+ // be what it was: a path on this one.
983
+ location = path.startsWith("//") ? origin + path : path;
984
+ }
985
+ } catch {
986
+ // A malformed Referer is not a destination.
987
+ }
988
+ }
989
+ return new Response(null, { status: 303, headers: { location } });
990
+ }