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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
package/src/index.ts ADDED
@@ -0,0 +1,740 @@
1
+ /**
2
+ * Server functions — the builder, and the two stubs the compiler emits.
3
+ *
4
+ * A server function is written once and reachable from both sides. The compiler
5
+ * decides which side a module is being compiled for and replaces the handler
6
+ * with the matching stub: `serverRpc` on the server, where the body runs, and
7
+ * `clientRpc` on the client, where it becomes a fetch. That decision is a
8
+ * compile-time one and is never taken at runtime, so the body cannot reach a
9
+ * client bundle by being unreachable-but-present.
10
+ *
11
+ * Nothing in this file is safe to call from a browser bundle except
12
+ * `clientRpc`. `./server` is where the request handler lives.
13
+ */
14
+
15
+ export {
16
+ type ForwardedForTrust,
17
+ type RequestContext,
18
+ type ResponseDraft,
19
+ appendResponseHeader,
20
+ applyResponseDraft,
21
+ clearResponseHeaders,
22
+ collectRequestCss,
23
+ createResponseDraft,
24
+ devStylesheets,
25
+ type DevStylesheets,
26
+ deleteCookie,
27
+ draftedStatus,
28
+ getCookie,
29
+ getCookies,
30
+ getGlobalStartContext,
31
+ getRequest,
32
+ getRequestHeader,
33
+ markResponseSent,
34
+ getRequestHeaders,
35
+ getRequestHost,
36
+ getRequestIP,
37
+ getRequestProtocol,
38
+ getRequestUrl,
39
+ getResponseHeader,
40
+ getResponseHeaders,
41
+ getResponseStatus,
42
+ invalidateFrames,
43
+ peekRequest,
44
+ peekResponseDraft,
45
+ removeResponseHeader,
46
+ setCookie,
47
+ setResponseHeader,
48
+ setResponseHeaders,
49
+ installCssSink,
50
+ setRequestMiddlewareContext,
51
+ setResponseStatus,
52
+ takeSendContext,
53
+ withRequest,
54
+ } from "./context.ts";
55
+
56
+ export { type CookieOptions, deleteCookieLine, parseCookies, serializeCookie } from "./cookies.ts";
57
+
58
+ /**
59
+ * Sessions: a sealed cookie, with no store behind it.
60
+ *
61
+ * The interface is TanStack's; the SEALING is not: AES-GCM through WebCrypto rather than iron's AES-CBC plus a separate
62
+ * HMAC, which costs no dependency and has no encrypt-then-MAC composition to get
63
+ * wrong. A cookie sealed by one does not open in the other, and `session.ts`
64
+ * says so where it can be read.
65
+ */
66
+ /**
67
+ * Rate limiting, as a middleware — so one closure guards a server function and a
68
+ * route handler alike. The STORE has no default on purpose; `rate-limit.ts` says
69
+ * why at length.
70
+ */
71
+ export {
72
+ type RateLimitCount,
73
+ type RateLimitOptions,
74
+ type RateLimitStore,
75
+ byIP,
76
+ memoryStore,
77
+ rateLimit,
78
+ } from "./rate-limit.ts";
79
+
80
+ export {
81
+ type Session,
82
+ type SessionConfig,
83
+ type SessionData,
84
+ type SessionManager,
85
+ clearSession,
86
+ getSession,
87
+ sealSession,
88
+ unsealSession,
89
+ updateSession,
90
+ useSession,
91
+ } from "./session.ts";
92
+
93
+ /**
94
+ * The client half lives in `./client.ts` and is re-exported here.
95
+ *
96
+ * SPLIT FOR ONE REASON: the compiler's client stub imports `clientRpc`, and
97
+ * importing it from THIS module dragged `context.ts` — `node:async_hooks` — plus
98
+ * the middleware runner and the validators into every client bundle that
99
+ * reached one server function. Re-exporting keeps `import { createServerFn }
100
+ * from "@barqjs/start"` the only thing an application writes.
101
+ */
102
+ export {
103
+ type AnyServerFn,
104
+ type ChainStep,
105
+ type RpcControl,
106
+ type ServerFn,
107
+ type ServerFnArgs,
108
+ type ServerFnCallOptions,
109
+ type ServerFnMeta,
110
+ type ServerFnMethod,
111
+ type Streamed,
112
+ BUILD_HEADER,
113
+ DATA_SUFFIX,
114
+ LIVE_SUFFIX,
115
+ NOT_FOUND,
116
+ PAYLOAD_PARAM,
117
+ REDIRECT,
118
+ RPC_CALLER,
119
+ RPC_CONTEXT,
120
+ RPC_CONTROL,
121
+ RPC_PREFIX,
122
+ RPC_STREAM,
123
+ RpcNotFound,
124
+ RpcRedirect,
125
+ SERVER_FN,
126
+ STATIC_PREFIX,
127
+ ServerFnError,
128
+ UNKNOWN_HEADER,
129
+ clientRpc,
130
+ isServerFn,
131
+ staticFunctionMiddleware,
132
+ staticUrl,
133
+ } from "./client.ts";
134
+ export type { ServerFnInputAnswer, ServerFnIssue, ServerFnThrown } from "./client.ts";
135
+ export { type ServerTiming, serverTiming } from "./timing.ts";
136
+ export { type BindingSlot, FRAME_APPLIED_EVENT, type Slot, isFrame } from "./frames.ts";
137
+ export { type LiveIterable, type LiveStatus, live } from "./live-client.ts";
138
+
139
+ import {
140
+ type AnyServerFn,
141
+ type ChainStep,
142
+ SERVER_FN,
143
+ SERVER_FN_CHAIN,
144
+ type ServerFn,
145
+ type ServerFnMeta,
146
+ type ServerFnMethod,
147
+ type Streamed,
148
+ callOptionsOf,
149
+ dataOf,
150
+ inlineServerFns,
151
+ urlOf,
152
+ } from "./client.ts";
153
+ import { getGlobalStartContext, offerSendContext, peekRequest } from "./context.ts";
154
+ import { asFrame } from "./frames.ts";
155
+ import {
156
+ type Carries,
157
+ type ChainContribution,
158
+ type Contribution,
159
+ type Empty,
160
+ type Merged,
161
+ type Middleware,
162
+ type NoContribution,
163
+ type OpenContext,
164
+ type StandardInput,
165
+ type StandardOutput,
166
+ type StandardSchemaLike,
167
+ type Validator,
168
+ type ValidatorInput,
169
+ UncheckedInputError,
170
+ applyValidator,
171
+ flattenMiddleware,
172
+ isBuiltMiddleware,
173
+ runMiddleware,
174
+ toValidator,
175
+ } from "./middleware.ts";
176
+ import { type GlobalFunctionContext, startOptions } from "./start-instance.ts";
177
+ import type { Crossable, InputProblem, ResultProblem, StrictOn, Strictness } from "./wire-types.ts";
178
+
179
+ export type {
180
+ Crossable,
181
+ InputProblem,
182
+ ResultProblem,
183
+ StrictOn,
184
+ Strictness,
185
+ WireProblem,
186
+ } from "./wire-types.ts";
187
+
188
+ export {
189
+ type FunctionContextOf,
190
+ type GlobalFunctionContext,
191
+ type GlobalRequestContext,
192
+ type Register,
193
+ type RequestContextOf,
194
+ type StartInstance,
195
+ type StartOptions,
196
+ clearStart,
197
+ createStart,
198
+ startOptions,
199
+ } from "./start-instance.ts";
200
+
201
+ /**
202
+ * Middleware and the validator surface it composes, re-exported so an
203
+ * application still writes one import. `middleware.ts` says why they live apart.
204
+ */
205
+ export {
206
+ type IsomorphicBuilder,
207
+ type IsomorphicFn,
208
+ createClientOnlyFn,
209
+ createIsomorphicFn,
210
+ createServerOnlyFn,
211
+ } from "./env.ts";
212
+
213
+ export {
214
+ type BuiltMiddleware,
215
+ type Carries,
216
+ type ChainContribution,
217
+ type ClientReplaced,
218
+ type DataAt,
219
+ type FreshMiddleware,
220
+ type FromNext,
221
+ type OwnReplaced,
222
+ type Plain,
223
+ type ValidatorReplaced,
224
+ type WithChain,
225
+ type WithClient,
226
+ type WithServer,
227
+ type WithValidator,
228
+ type ClientMiddlewareContext,
229
+ type ContributedBy,
230
+ type Contribution,
231
+ type ContributionOf,
232
+ type Empty,
233
+ type Merged,
234
+ type Middleware,
235
+ type MiddlewareContext,
236
+ type MiddlewareFn,
237
+ type MiddlewareNext,
238
+ type MiddlewareOptions,
239
+ type MiddlewareState,
240
+ type NextOptions,
241
+ type NextResult,
242
+ type NoContribution,
243
+ type OpenContext,
244
+ type RequestMiddleware,
245
+ type RequestMiddlewareContext,
246
+ type RequestMiddlewareFn,
247
+ type RequestMiddlewareNext,
248
+ type RequestMiddlewareStart,
249
+ type StandardInput,
250
+ type StandardOutput,
251
+ type StandardSchema,
252
+ type StandardSchemaLike,
253
+ type Validator,
254
+ type ValidatorInput,
255
+ InputError,
256
+ UncheckedInputError,
257
+ ValidationError,
258
+ applyValidator,
259
+ createMiddleware,
260
+ isInputError,
261
+ flattenMiddleware,
262
+ isBuiltMiddleware,
263
+ runMiddleware,
264
+ runRequestMiddleware,
265
+ toValidator,
266
+ } from "./middleware.ts";
267
+
268
+ export {
269
+ type AnySerializationAdapter,
270
+ type SerializationAdapter,
271
+ createSerializationAdapter,
272
+ } from "@barqjs/server/codec";
273
+
274
+ /** TanStack's `json`: a JSON `Response`, which a handler returns as its answer. */
275
+ export function json(payload: unknown, init?: ResponseInit): Response {
276
+ return Response.json(payload, init);
277
+ }
278
+
279
+ export async function checkInput(
280
+ built: { readonly validator: Validator<unknown> | null },
281
+ raw: unknown,
282
+ /**
283
+ * Whether a MIDDLEWARE in the chain declared a validator.
284
+ *
285
+ * The refusal below asks "does anything expect input?", and before middleware
286
+ * validators existed the function's own was the only thing that could answer.
287
+ * A chain that validates has opened the channel just as surely, so refusing
288
+ * here would make `.validator(schema)` on a middleware unusable by any
289
+ * function that declares none of its own — which is the whole point of
290
+ * putting one there.
291
+ */
292
+ chainValidates = false,
293
+ ): Promise<unknown> {
294
+ if (built.validator === null) {
295
+ // `undefined` is what a no-argument call sends, and it is the only input a
296
+ // function with no validator accepts.
297
+ if (raw !== undefined && !chainValidates) throw new UncheckedInputError();
298
+ return raw;
299
+ }
300
+ return applyValidator(built.validator, raw);
301
+ }
302
+
303
+ /**
304
+ * What a handler is handed, which is TanStack's shape:
305
+ * `.handler(async ({ data }) => …)`.
306
+ *
307
+ * `context` is what the middleware chain contributed, merged outermost-first,
308
+ * and typed by what each middleware passed to `next({ context })`.
309
+ * `signal` aborts with the request, so a handler can hand it to `fetch` and a
310
+ * client that navigates away stops paying for the work.
311
+ */
312
+ export interface HandlerContext<In, Context extends object = Empty> {
313
+ readonly data: In;
314
+ readonly context: OpenContext<Context>;
315
+ readonly signal: AbortSignal;
316
+ /** The method this function answers. */
317
+ readonly method: ServerFnMethod;
318
+ /** Which function is running, by the id it is mounted at. Empty when it is not mounted. */
319
+ readonly serverFnMeta: { readonly id: string };
320
+ }
321
+
322
+ interface Built<Data, Out, Context extends object = Empty> {
323
+ validator: Validator<unknown> | null;
324
+ middleware: readonly Middleware[];
325
+ handler: (context: HandlerContext<Data, Context>) => Out | Promise<Out>;
326
+ }
327
+
328
+ interface Staged {
329
+ readonly validator: Validator<unknown> | null;
330
+ readonly middleware: readonly Middleware[];
331
+ readonly method: ServerFnMethod;
332
+ readonly broadcast: boolean;
333
+ }
334
+
335
+ /**
336
+ * Where a server function's builder is: its chain, its own validator, its
337
+ * method, and whether what crosses the wire is checked.
338
+ */
339
+ export interface ServerFnState {
340
+ readonly chain: Contribution;
341
+ readonly own: Contribution;
342
+ readonly method: ServerFnMethod;
343
+ readonly strict: Strictness;
344
+ }
345
+
346
+ export interface FreshServerFn<
347
+ Method extends ServerFnMethod,
348
+ Strict extends Strictness = true,
349
+ > extends ServerFnState {
350
+ readonly chain: NoContribution;
351
+ readonly own: NoContribution;
352
+ readonly method: Method;
353
+ readonly strict: Strict;
354
+ }
355
+
356
+ export interface FnWithChain<State extends ServerFnState, Chain> extends ServerFnState {
357
+ readonly chain: Merged<State["chain"], ChainContribution<Chain>>;
358
+ readonly own: State["own"];
359
+ readonly method: State["method"];
360
+ readonly strict: State["strict"];
361
+ }
362
+
363
+ export interface Validates<In, Out> extends Contribution {
364
+ readonly context: Empty;
365
+ readonly sent: Empty;
366
+ readonly clientContext: Empty;
367
+ readonly input: In;
368
+ readonly output: Out;
369
+ readonly validates: true;
370
+ }
371
+
372
+ export interface FnWithValidator<State extends ServerFnState, In, Out> extends ServerFnState {
373
+ readonly chain: State["chain"];
374
+ readonly own: Validates<In, Out>;
375
+ readonly method: State["method"];
376
+ readonly strict: State["strict"];
377
+ }
378
+
379
+ /**
380
+ * What a validator's input must also be: anything, unless it holds something
381
+ * the codec cannot carry, when it must be a type naming that, which nothing is.
382
+ */
383
+ export type InputCheck<State extends ServerFnState, In> =
384
+ StrictOn<State["strict"], "input"> extends true
385
+ ? Crossable<InputProblem<In, State["method"]>>
386
+ : unknown;
387
+
388
+ /** The same, for what a handler returns. */
389
+ export type ResultCheck<State extends ServerFnState, Result> =
390
+ StrictOn<State["strict"], "output"> extends true ? Crossable<ResultProblem<Result>> : unknown;
391
+
392
+ /**
393
+ * What the caller passes: the input of the first validator that runs, which is
394
+ * a middleware's when the chain validates. `undefined` when nothing validates,
395
+ * since a function that declares no validator accepts no argument.
396
+ */
397
+ export type CallerInput<State extends ServerFnState> = State["chain"]["validates"] extends true
398
+ ? State["chain"]["input"]
399
+ : State["own"]["validates"] extends true
400
+ ? State["own"]["input"]
401
+ : undefined;
402
+
403
+ /** What the handler is handed: the last validator's output. */
404
+ export type HandlerData<State extends ServerFnState> = State["own"]["validates"] extends true
405
+ ? State["own"]["output"]
406
+ : State["chain"]["validates"] extends true
407
+ ? State["chain"]["output"]
408
+ : undefined;
409
+
410
+ /** What the handler's `context` holds: the global middleware's, then its own chain's. */
411
+ export type HandlerContextOf<State extends ServerFnState> = GlobalFunctionContext &
412
+ State["chain"]["context"];
413
+
414
+ /**
415
+ * The three-state discriminator, which is SvelteKit's idea and the best value
416
+ * in the survey: no validator means any argument is a 400, and opening the
417
+ * channel costs a schema or the literal `'unchecked'`.
418
+ *
419
+ * Every step is typed: the schema decides what a caller passes and what the
420
+ * handler is handed, and each middleware's `next({ context })` decides what the
421
+ * handler's `context` holds.
422
+ */
423
+ export interface ServerFnBuilder<State extends ServerFnState = ServerFnState> {
424
+ /**
425
+ * Middleware that runs before the handler, after any listed before. A server
426
+ * function in the list stands for the middleware it declared: its guards
427
+ * run here, its handler does not.
428
+ */
429
+ middleware<const Chain extends readonly ChainStep[]>(
430
+ chain: Chain,
431
+ ): ServerFnBuilder<FnWithChain<State, Chain>>;
432
+ /**
433
+ * Open the input channel: a Standard Schema, a function that returns the
434
+ * validated value or throws, an object with a `parse`, or `"unchecked"`.
435
+ * What a caller passes is the schema's input, and what it produces is the
436
+ * type of `data` in the handler. The schema form is tried first: an arktype
437
+ * type is callable as well, and read as a function its input would be lost.
438
+ */
439
+ validator<Schema extends StandardSchemaLike>(
440
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
441
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
442
+ validator<In, Out>(
443
+ validate: ((input: In) => Out) & InputCheck<State, In>,
444
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
445
+ validator<In, Out>(
446
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
447
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
448
+ validator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
449
+ /** `validator` under the name TanStack's release candidates used. */
450
+ inputValidator<Schema extends StandardSchemaLike>(
451
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
452
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
453
+ inputValidator<In, Out>(
454
+ validate: ((input: In) => Out) & InputCheck<State, In>,
455
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
456
+ inputValidator<In, Out>(
457
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
458
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
459
+ inputValidator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
460
+ /**
461
+ * The body. What it returns must cross the wire: a function, a symbol, or an
462
+ * instance of a class the codec refuses is a type error here, naming where
463
+ * it is. `createServerFn({ strict: false })` turns the check off.
464
+ */
465
+ handler<Result>(
466
+ fn: ((
467
+ context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,
468
+ ) => Result | Promise<Result>) &
469
+ ResultCheck<State, Result>,
470
+ ): ServerFn<CallerInput<State>, Streamed<Awaited<Result>>, State["method"]> &
471
+ Carries<State["chain"]>;
472
+ }
473
+
474
+ /**
475
+ * What `createServerFn` accepts.
476
+ *
477
+ * `method` is TanStack's, with TanStack's default: `GET`. A function that
478
+ * writes declares `POST`, which is also the only method a form can reach. A
479
+ * link still cannot reach a `GET` one: every call carries the
480
+ * {@link RPC_CALLER} header, which nothing but script can set, and the server
481
+ * refuses a `GET` without it.
482
+ */
483
+ export interface ServerFnOptions<
484
+ Method extends ServerFnMethod = ServerFnMethod,
485
+ Strict extends Strictness = Strictness,
486
+ > {
487
+ readonly method?: Method;
488
+ /**
489
+ * Whether the types refuse an input or a result the codec cannot carry. On
490
+ * by default; `false` turns both off, `{ input: false }` or
491
+ * `{ output: false }` one side. The codec still refuses at runtime what it
492
+ * cannot carry: this only says the author knows, as for a class a
493
+ * `createSerializationAdapter` carries.
494
+ */
495
+ readonly strict?: Strict;
496
+ /**
497
+ * The answer is the same for every caller with the same arguments, so a
498
+ * `live` call shares one rendering with every other connection asking the
499
+ * same thing: Solid 2.0's `broadcast`. The handler still runs per call, as the
500
+ * gate it is (an auth check, a redirect), and a joiner's own answer is closed
501
+ * unread. The shared rendering belongs to no request: it reads no cookie,
502
+ * header or session, and it stops when its last connection goes.
503
+ */
504
+ readonly broadcast?: boolean;
505
+ }
506
+
507
+ /**
508
+ * Author a server function. The value this returns is replaced by the compiler
509
+ * on both sides, so what it does when compiled by nothing is only the
510
+ * uncompiled-development path: it runs the handler in-process.
511
+ */
512
+ export function createServerFn<
513
+ Method extends ServerFnMethod = "GET",
514
+ const Strict extends Strictness = true,
515
+ >(options: ServerFnOptions<Method, Strict> = {}): ServerFnBuilder<FreshServerFn<Method, Strict>> {
516
+ // A runtime refusal beside the type one, because a JavaScript application has
517
+ // no type to fail.
518
+ const method = options.method ?? "GET";
519
+ if (method !== "POST" && method !== "GET") {
520
+ throw new TypeError(
521
+ `[barq] \`createServerFn({ method: ${JSON.stringify(method)} })\` is not supported: a server function answers GET or POST. ` +
522
+ "Use a route's `server.handlers` for any other method.",
523
+ );
524
+ }
525
+ return builderAt<FreshServerFn<Method, Strict>>({
526
+ validator: null,
527
+ middleware: [],
528
+ method,
529
+ broadcast: options.broadcast === true,
530
+ });
531
+ }
532
+
533
+ /**
534
+ * A NEW BUILDER PER STEP, as `createMiddleware` is: one that mutated a shared
535
+ * record would let a base kept in a variable and finished twice hand the first
536
+ * function the second one's handler, validator and chain.
537
+ */
538
+ function builderAt<State extends ServerFnState>(staged: Staged): ServerFnBuilder<State> {
539
+ function validated<Schema extends StandardSchemaLike>(
540
+ schema: Schema & InputCheck<State, StandardInput<Schema>>,
541
+ ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
542
+ function validated<In, Out>(
543
+ validate: ((input: In) => Out) & InputCheck<State, In>,
544
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
545
+ function validated<In, Out>(
546
+ schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,
547
+ ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
548
+ function validated(
549
+ unchecked: "unchecked",
550
+ ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
551
+ function validated(
552
+ schema: ValidatorInput<unknown>,
553
+ ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>> {
554
+ return builderAt({ ...staged, validator: toValidator(schema) });
555
+ }
556
+ return {
557
+ middleware: <const Chain extends readonly ChainStep[]>(chain: Chain) =>
558
+ builderAt<FnWithChain<State, Chain>>({
559
+ ...staged,
560
+ middleware: [...staged.middleware, ...inlineServerFns(chain)],
561
+ }),
562
+ validator: validated,
563
+ inputValidator: validated,
564
+ handler: <Result>(
565
+ fn: ((
566
+ context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,
567
+ ) => Result | Promise<Result>) &
568
+ ResultCheck<State, Result>,
569
+ ) =>
570
+ serverRpc<
571
+ CallerInput<State>,
572
+ Result,
573
+ HandlerData<State>,
574
+ HandlerContextOf<State>,
575
+ State["method"]
576
+ >(
577
+ {
578
+ id: "",
579
+ ...(staged.method === "GET" ? { method: "GET" as const } : {}),
580
+ ...(staged.broadcast ? { broadcast: true as const } : {}),
581
+ },
582
+ {
583
+ validator: staged.validator,
584
+ middleware: staged.middleware,
585
+ handler: fn,
586
+ },
587
+ ),
588
+ };
589
+ }
590
+
591
+ /**
592
+ * The server half. The compiler emits this in a module compiled for the server,
593
+ * with the real handler and the id it assigned.
594
+ *
595
+ * `In` is what a caller passes and `Data` what the handler is handed; the
596
+ * validator is what turns one into the other, at runtime.
597
+ */
598
+ export function serverRpc<
599
+ In,
600
+ Out,
601
+ Data = In,
602
+ Context extends object = Empty,
603
+ Method extends ServerFnMethod = "POST",
604
+ >(
605
+ meta: ServerFnMeta,
606
+ built: Built<Data, Out, Context>,
607
+ ): ServerFn<In, Streamed<Awaited<Out>>, Method> {
608
+ // The application's global function middleware runs ahead of the function's
609
+ // own, and is read when it is first needed: `src/start.ts` may be evaluated
610
+ // after the module that declares this function. Flattening drops a step the
611
+ // function lists again, so a guard named in both places runs once.
612
+ let composed: {
613
+ readonly from: readonly Middleware[] | undefined;
614
+ readonly chain: readonly Middleware[];
615
+ /** Whether a bare argument has somewhere to be validated before the handler. */
616
+ readonly validates: boolean;
617
+ } | null = null;
618
+ const composition = (): NonNullable<typeof composed> => {
619
+ const global = startOptions().functionMiddleware;
620
+ if (composed !== null && composed.from === global) return composed;
621
+ const chain = flattenMiddleware([...(global ?? []), ...built.middleware]);
622
+ composed = {
623
+ from: global,
624
+ chain,
625
+ validates: chain.some(
626
+ (step) => isBuiltMiddleware(step) && step.options.validator !== undefined,
627
+ ),
628
+ };
629
+ return composed;
630
+ };
631
+
632
+ const call = async (
633
+ options?: unknown,
634
+ /**
635
+ * What the CLIENT's halves sent, and it is UNTRUSTED.
636
+ *
637
+ * A second positional rather than a property of `options`, so it is
638
+ * invisible to the public `ServerFn` signature and cannot be reached by
639
+ * writing `fn({ data, context })` in application code. The request handler
640
+ * is the only caller that passes it.
641
+ *
642
+ * Handed to the chain BESIDE `context` and never merged into it. Merging it
643
+ * under would let it survive wherever no server step set the same key on
644
+ * this request, and a middleware that names the user only for a signed-in
645
+ * caller would leave `context.user` to whoever is not signed in.
646
+ */
647
+ clientContext?: Record<string, unknown>,
648
+ ): Promise<Streamed<Awaited<Out>>> => {
649
+ const input = dataOf(options);
650
+ const { chain, validates: chainValidates } = composition();
651
+ // What the chain contributed, merged as it unwinds inward. One object the
652
+ // chain mutates rather than one per step: `next({ context })` is additive
653
+ // by definition, and a handler wants the union of everything above it. It
654
+ // starts from what the request's own middleware already said.
655
+ const context: Record<string, unknown> = { ...getGlobalStartContext() };
656
+ const sendContext: Record<string, unknown> = {};
657
+ // The call's own when it named one, which only an in-process caller can.
658
+ // Otherwise the request's, so a caller that goes away stops the work it
659
+ // asked for; with neither there is nothing to abort it.
660
+ const signal =
661
+ callOptionsOf(options)?.signal ?? peekRequest()?.signal ?? new AbortController().signal;
662
+
663
+ // Middleware runs BEFORE the function's own validation. An unauthenticated
664
+ // caller should be refused without the server parsing its payload first,
665
+ // and a rejection that depended on the payload being well-formed would be
666
+ // one an attacker could skip by sending a malformed one. A MIDDLEWARE's own
667
+ // validator is the exception and has to be: its body is handed `data`.
668
+ const method = meta.method ?? "POST";
669
+ const result = await runMiddleware(chain, "server", {
670
+ data: input,
671
+ meta,
672
+ method,
673
+ signal,
674
+ context,
675
+ clientContext,
676
+ sendContext,
677
+ run: async (data) =>
678
+ built.handler({
679
+ // What the validators produced and what the chain wrote: the two
680
+ // facts the builder's types describe, which exist only at runtime.
681
+ data: (await checkInput(built, data, chainValidates)) as Data,
682
+ context: context as OpenContext<Context>,
683
+ signal,
684
+ method,
685
+ serverFnMeta: { id: meta.id },
686
+ }),
687
+ });
688
+
689
+ offerSendContext(sendContext);
690
+ // A `ReadableStream` is handed on as the async iterable every caller is
691
+ // told to expect, so one in process reads what one in a browser does, and
692
+ // a component is a frame, which a route renders and a browser asks for.
693
+ if (result instanceof ReadableStream) return valuesOf(result) as Streamed<Awaited<Out>>;
694
+ return asFrame(meta.id, input, result) as Streamed<Awaited<Out>>;
695
+ };
696
+
697
+ const fn = Object.assign(call, {
698
+ [SERVER_FN]: true as const,
699
+ [SERVER_FN_CHAIN]: built.middleware,
700
+ meta,
701
+ serverFnMeta: meta,
702
+ method: meta.method ?? "POST",
703
+ built,
704
+ url: "",
705
+ });
706
+ // Read when asked: the id is stamped when the function is mounted.
707
+ Object.defineProperty(fn, "url", { enumerable: true, get: () => urlOf(meta.id) });
708
+ return fn;
709
+ }
710
+
711
+ /**
712
+ * The middleware chain a server function carries, by REFERENCE.
713
+ *
714
+ * `serverRpc` attaches `built` to the function object, so the chain is the real
715
+ * array of closures rather than something re-derived. That matters: a build
716
+ * cannot read a chain out of source. `.middleware([m])`, `.middleware([...c])`
717
+ * and `.middleware(c.filter(Boolean))` are all runtime expressions, and
718
+ * `Middleware` is an anonymous closure with no build-visible identity — so the
719
+ * only sound comparison is `===` against the same closure the route declared.
720
+ *
721
+ * Empty for a client stub, which carries no chain because it carries no handler.
722
+ */
723
+ export function middlewareOf(fn: AnyServerFn): readonly Middleware[] {
724
+ const built = (fn as unknown as { built?: Built<unknown, unknown> }).built;
725
+ return built?.middleware ?? [];
726
+ }
727
+
728
+ /** A stream's values, releasing it when the reader leaves early. */
729
+ async function* valuesOf(stream: ReadableStream<unknown>): AsyncIterableIterator<unknown> {
730
+ const reader = stream.getReader();
731
+ try {
732
+ for (;;) {
733
+ const { done, value } = await reader.read();
734
+ if (done) return;
735
+ yield value;
736
+ }
737
+ } finally {
738
+ void reader.cancel().catch(() => {});
739
+ }
740
+ }