@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/README.md CHANGED
@@ -1,3 +1,818 @@
1
- # Temporary Holding Version
1
+ # @barqjs/start
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server functions, middleware, the request context, sessions, cookies, rate
4
+ limiting, and the server the build emits. A server function is a typed `GET` or
5
+ `POST` endpoint you call like a function. A `GET` call needs barq's `x-barq-fn`
6
+ header and passes an origin check. A production server sends a thrown error's
7
+ message only when it was marked with `markSafeError`. With `verify` on, the
8
+ build refuses to ship a route whose server functions skip its middleware. The API follows TanStack Start's design:
9
+ `createServerFn`, `createMiddleware`, `createStart`, `useSession`, and the
10
+ request helpers under their names.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ bun add @barqjs/start
16
+ bun add -d @barqjs/vite vite
17
+ ```
18
+
19
+ `bun create barq` installs it for you. This document is the reference for what
20
+ that project uses. Routing, the document and API routes are in
21
+ [@barqjs/router](../router/README.md).
22
+
23
+ ## Example
24
+
25
+ The smallest server function, and a call to it:
26
+
27
+ ```tsx
28
+ import { createServerFn } from "@barqjs/start";
29
+
30
+ export const serverTime = createServerFn().handler(() => new Date());
31
+
32
+ const at = await serverTime(); // a Date, fetched from the server
33
+ ```
34
+
35
+ ## Coming from TanStack Start
36
+
37
+ `createServerFn` with `GET` as the default method, `.validator`, `.middleware`,
38
+ `.handler`, `createMiddleware` with `.server` and `.client` halves,
39
+ `createStart` with request and function middleware, `redirect`, `notFound`,
40
+ `useSession` and the request helpers follow TanStack Start under their names.
41
+ What barq adds is the build-time route-action check (`verify`), the wire-type
42
+ check on results, and the `x-barq-fn` header on `GET` calls.
43
+
44
+ ## Server functions
45
+
46
+ ```ts
47
+ import { createServerFn } from "@barqjs/start";
48
+
49
+ export const createPost = createServerFn({ method: "POST" })
50
+ .validator(PostSchema) // any Standard Schema, such as zod, valibot or arktype
51
+ .handler(async ({ data, context, signal }) => db.posts.insert(data));
52
+ ```
53
+
54
+ `.validator` is TanStack's name for it. `.inputValidator`, the name their
55
+ release candidates used, is the same method and is accepted so code written
56
+ against them keeps working. It takes a Standard Schema, a function that returns
57
+ the validated value or throws, or an object with a `parse`. The caller passes
58
+ the schema's INPUT and the handler is handed its OUTPUT, so a schema that turns
59
+ an ISO string into a `Date` is called with a string. A function validator's
60
+ parameter type is what the caller passes:
61
+
62
+ ```ts
63
+ export const byId = createServerFn()
64
+ .validator((input: { id: string }) => ({ id: Number(input.id) }))
65
+ .handler(({ data }) => db.users.find(data.id)); // data: { id: number }
66
+
67
+ await byId({ data: { id: "41" } }); // { id: 41 } is a type error
68
+ ```
69
+
70
+ A function handed a form receives the `FormData` itself.
71
+
72
+ Call it like a function. It is an HTTP endpoint:
73
+
74
+ ```tsx
75
+ const post = await createPost({ data: { title: "Hello" } });
76
+ ```
77
+
78
+ The compiler replaces this module's exports with client stubs that call
79
+ `/_barq/fn/<id>`, so the handler's body, and the database driver it imports,
80
+ is in no client chunk. The id is `<project-relative module>#<export>`, derived
81
+ once and used by both halves, because deriving it twice is how the two drift
82
+ into a call that reaches nothing.
83
+
84
+ **A function with no validator accepts no argument.** That is the safe default:
85
+ opening the input is a decision you make per function. `.validator("unchecked")`
86
+ takes anything.
87
+
88
+ ### GET and POST
89
+
90
+ `GET` is the default, as it is TanStack's. A function that writes declares
91
+ `POST`, which is also the only method a form can reach:
92
+
93
+ ```ts
94
+ export const listNotes = createServerFn() // GET
95
+ .middleware([requireSession])
96
+ .handler(({ context }) => {
97
+ setResponseHeader("cache-control", "private, max-age=60");
98
+ return notesOf(context.user);
99
+ });
100
+ ```
101
+
102
+ The call is the same either way. A `GET` call carries its payload in
103
+ `?payload=`, so one input is one URL, and a long input belongs in a `POST`.
104
+ `method` must be a literal, since the compiler reads it to write the stub; a
105
+ value it cannot read is taken as the default. Nothing is cached unless the
106
+ handler says so: an answer carries no `cache-control` and no `Vary` of its own, which is
107
+ TanStack's behaviour too.
108
+
109
+ A link still cannot reach a `GET` function, so one that writes and forgot to
110
+ say `POST` is not a one-click CSRF carrying `SameSite=Lax` cookies. Every `GET`
111
+ call carries an `x-barq-fn` header, which a link, an `<img>`, a prefetch or a
112
+ navigation cannot set, and the server answers a `GET` without it with a 403. A
113
+ script on another site that sets it is preflighted, and the origin check
114
+ refuses it either way. A function answers its own method only (a `POST` to a
115
+ `GET` function is a 405, and the reverse), a `GET` function has no form channel, and a
116
+ payload longer than `maxBodySize` is a 413. Keep `public` out of `cache-control`
117
+ for anything that reads a session: a shared cache would hand one user's answer to
118
+ the next.
119
+
120
+ A call takes three options beside `data`:
121
+
122
+ ```ts
123
+ const controller = new AbortController();
124
+ await createPost({
125
+ data: { title: "Hello" },
126
+ signal: controller.signal, // cancels the fetch; the handler's `signal` follows the request
127
+ headers: { "x-trace": id }, // wins over a client middleware's `next({ headers })`
128
+ fetch: tracedFetch, // in place of the global one
129
+ });
130
+ ```
131
+
132
+ A `Response` a middleware, a validator or the handler throws
133
+ (`throw new Response("sign in first", { status: 401 })`) is what the call
134
+ rejects with, as in TanStack: its status, headers and body are the author's
135
+ words to the caller. Any other failure rejects with `ServerFnError`, carrying
136
+ the `status`, the server's `response`, and `issues` when the validator refused
137
+ the input. A handler's own error is answered with one fixed line and nothing
138
+ else, so a thrown `Error`'s message never leaves the server. A development
139
+ server also sends `thrown`, the error's name, message and stack; production
140
+ leaves it `undefined`.
141
+
142
+ A page that outlived a deploy can call a function the new server does not have,
143
+ or one whose arguments changed under the same id. `@barqjs/vite` stamps each
144
+ build with an id (`barqStart({ buildId })` names it, such as a commit hash), a
145
+ call from another build is answered `409` without running, and an unknown id is
146
+ answered `404`. Both reject with `error.unknownFunction` set, so the page can
147
+ reload onto the current build: `if (error.unknownFunction) location.reload()`.
148
+
149
+ `throw redirect({ to, params, search, hash, replace, reloadDocument, href })`
150
+ and `throw notFound({ data, routeId })` from a handler reach the caller with
151
+ everything they said, and their `headers` leave on the response. `useServerFn`
152
+ from `@barqjs/router` navigates on the redirect. A redirect whose `params` or
153
+ `search` is a function cannot cross and arrives as its resolved target alone.
154
+
155
+ `fn.url` is the address `<form action={fn}>` posts to, `fn.method` the method it
156
+ answers, and `fn.serverFnMeta.id` (also `fn.meta.id`) the id it is mounted at.
157
+ A handler is handed the same two beside `data`, `context` and `signal`:
158
+
159
+ ```ts
160
+ createServerFn().handler(({ method, serverFnMeta }) => `${method} ${serverFnMeta.id}`);
161
+ ```
162
+
163
+ `json(payload, init)` builds a JSON `Response`, for a handler that answers with
164
+ one.
165
+
166
+ ### What crosses the wire
167
+
168
+ A handler's result and a validator's input are checked against what the codec
169
+ carries, so a value it would refuse at runtime is a type error where it is
170
+ written, naming where. A component is the exception, and crosses as a frame:
171
+
172
+ ```ts
173
+ createServerFn().handler(() => ({ user: { format: () => "x" } }));
174
+ // ... { readonly "cannot cross the wire": "the result.user.format is a function" }
175
+ ```
176
+
177
+ Primitives, `bigint`, `Date`, `Error`, `Map`, `Set`, `Promise`, typed arrays and
178
+ plain objects cross; a function, a symbol, a `RegExp`, a `URL`, a `Blob` and an
179
+ instance of a class with methods do not. A form crosses as a `POST`'s input. A
180
+ class with no methods is a plain object to a type and is refused by the codec
181
+ at runtime only. `createServerFn({ strict: false })` turns the check off, and
182
+ `strict: { input: false }` or `strict: { output: false }` one side of it, for a
183
+ class a `createSerializationAdapter` carries.
184
+
185
+ ### Static server functions
186
+
187
+ ```ts
188
+ import { staticFunctionMiddleware } from "@barqjs/start/client";
189
+
190
+ export const buildInfo = createServerFn({ method: "GET" })
191
+ .middleware([staticFunctionMiddleware])
192
+ .validator((input: { page: string }) => input)
193
+ .handler(({ data }) => ({ page: data.page, builtAt: new Date() }));
194
+ ```
195
+
196
+ While the build prerenders, each call writes its result to
197
+ `/_barq/static/<key>.json` in the client output, one file per function and
198
+ input. Reordering the input's keys gives the same file. In the browser the call reads
199
+ that file first and goes to the server only when there is none, so a page
200
+ prerendered whole works from a host that serves files and nothing else.
201
+
202
+ Import it from `@barqjs/start/client`, the subpath the client stub already
203
+ imports from: a chain naming anything from another package is not carried into
204
+ the browser. List it last, since the key is the input as it sees it. Only the
205
+ result is stored: a `sendContext` is not, and a `Response`, a stream or a result
206
+ of `undefined` is never written. Two calls whose keys collide stop the build.
207
+
208
+ ### Streaming
209
+
210
+ A handler that returns an async generator, or a `ReadableStream` of values,
211
+ answers over time. The caller reads an async iterable of the same values:
212
+
213
+ ```ts
214
+ export const ticks = createServerFn().handler(async function* () {
215
+ for (const row of await rows()) yield { row, at: new Date() };
216
+ });
217
+
218
+ for await (const { row, at } of await ticks()) render(row, at);
219
+ ```
220
+
221
+ Leaving the loop early stops the generator. A failure after the first value ends
222
+ the iterable with a `ServerFnError`.
223
+
224
+ ### Frames
225
+
226
+ A handler that returns a component answers with a frame: the component runs on
227
+ the server, and the page receives its markup and never its code. Its props are
228
+ slots, positions the server marks and the page fills: with components of its
229
+ own where a slot is placed, and with behaviour where a slot is read as data.
230
+
231
+ ```tsx
232
+ import type { Child } from "@barqjs/core";
233
+ import { dynamic } from "@barqjs/web";
234
+ import { type Slot, createServerFn } from "@barqjs/start";
235
+
236
+ export const getStory = createServerFn({ method: "GET" })
237
+ .validator((input: { id: string }) => input)
238
+ .handler(({ data }) => {
239
+ const story = loadStory(data.id);
240
+ return (props: { comment: Slot<{ cid: number }>; children?: Child }) => (
241
+ <article>
242
+ <h2>{story.title}</h2>
243
+ {story.comments.map((c) => (
244
+ <props.comment $key={c.id} cid={c.id}>
245
+ <p>{c.text}</p>
246
+ </props.comment>
247
+ ))}
248
+ <footer>{props.children}</footer>
249
+ </article>
250
+ );
251
+ });
252
+ ```
253
+
254
+ A route renders what its loader answered with:
255
+
256
+ ```tsx
257
+ export const Route = createFileRoute("/story")({
258
+ loader: () => getStory({ data: { id: "1" } }),
259
+ component: (props: RouteProps) => {
260
+ const Story = dynamic(() => props.data() as (props: Record<string, unknown>) => Node);
261
+ return (
262
+ <Story
263
+ comment={(slot: Incoming<{ cid: number; children: Child }>) => (
264
+ <Comment cid={slot.cid()}>{slot.children}</Comment>
265
+ )}
266
+ >
267
+ <ShareBar />
268
+ </Story>
269
+ );
270
+ },
271
+ });
272
+ ```
273
+
274
+ - **In the document**, where the server renders the route, the frame is written
275
+ inline as `<barq-frame>` with a payload script naming its slots, and the
276
+ slots hold the page's components rendered for the first paint. The page's
277
+ seed names the frame by address, so the browser asks for nothing at boot: it
278
+ claims the region where it stands, and the slots' content with it, as
279
+ hydration claims the rest of the page.
280
+ - **Over the wire**, a call from the browser answers under
281
+ `x-barq-rpc: frame` with the same markup, the region rendered on its own and
282
+ its slots empty. A slot call's `children` cross in the payload as a nested
283
+ region of server markup, the fill's own `children`.
284
+ - **One component per address.** A call's address is its function and its
285
+ arguments, and asking again answers with the same component, so a `dynamic`
286
+ over it does not remount: `applyFrameResponse` morphs the new markup into
287
+ every place the region is mounted. A slot's content is the page's, kept with
288
+ its state, moved when the server moved it (by `$key`, or by position among
289
+ the calls of that name) and given the new arguments. `barq:frame-applied`
290
+ (`FRAME_APPLIED_EVENT`) is dispatched on `document` once it is applied.
291
+ - **A region's assets** are what it declared with `useHead` and what its
292
+ `lazy()` modules need. They are owned by the frame and go when it is
293
+ unmounted, and an update waits for a stylesheet it names to load.
294
+ - **The same checks.** A frame is a server function's answer, so the origin
295
+ check, the body limit and the request middleware run before the component
296
+ does. A browser posting a form to one is sent back with a `303`.
297
+
298
+ A slot the component calls and reads, rather than places, is a binding slot:
299
+ the server's own markup, with the page's behaviour bound to it. Each property
300
+ goes whole at one position, an attribute, a class name or style property in
301
+ object form, a handler, a ref or a text child:
302
+
303
+ ```tsx
304
+ import { type BindingSlot } from "@barqjs/start";
305
+
306
+ type Like = { liked: boolean; label: string; toggle: () => void };
307
+
308
+ // In the server component, per comment:
309
+ const like = props.like({ $key: c.id, cid: c.id });
310
+ <button class={{ liked: like.liked }} aria-pressed={like.liked} onClick={like.toggle}>
311
+ {like.label}
312
+ </button>;
313
+
314
+ // In the page, the fill, run once per occurrence:
315
+ <Story
316
+ like={(slot: Incoming<{ cid: number }>): Like => {
317
+ const [liked, setLiked] = createSignal(false);
318
+ return {
319
+ get liked() {
320
+ return liked();
321
+ },
322
+ get label() {
323
+ return liked() ? "liked" : "like";
324
+ },
325
+ toggle: () => setLiked((was) => !was),
326
+ };
327
+ }}
328
+ />;
329
+ ```
330
+
331
+ The server writes a marker beside each position, with the fill's first value
332
+ in the document and none over the wire, and never has the value to compute
333
+ with: a stand-in is an object, so a comparison or a branch on one is decided on
334
+ the page, in the fill. The browser binds each position once, the claim writing
335
+ nothing the server already wrote. An update keeps the fill and its state,
336
+ leaves the positions it owns alone and binds the ones the server added.
337
+
338
+ A mutation that changes a frame says so, and its answer carries the region
339
+ beside its value, in one request:
340
+
341
+ ```ts
342
+ export const reviseStory = createServerFn({ method: "POST" })
343
+ .validator((input: { id: string }) => input)
344
+ .handler(({ data }) => {
345
+ saveRevision(data.id);
346
+ invalidateFrames(getStory);
347
+ return "saved";
348
+ });
349
+ ```
350
+
351
+ A page names the frames it has mounted on each `POST` (`x-barq-frames`, the
352
+ first 32), each one is asked for again through its own function, validator and
353
+ middleware included, and the regions it answers are applied where they stand
354
+ before the caller is handed the value.
355
+
356
+ `live(fn)` keeps a frame current over one connection. On the server a frame
357
+ that reads a standing source, an async iterable in a memo, is rendered again
358
+ each time the source moves, and each rendering goes out as a server-sent event
359
+ applied in place:
360
+
361
+ ```tsx
362
+ const board = createMemo(() => live(getBoard)());
363
+ const Board = dynamic(() => board() as (props: Record<string, unknown>) => Node);
364
+ ```
365
+
366
+ A dropped connection reconnects with backoff from the last event it applied,
367
+ which is not sent again, and `onstatus` hears `"connected"`, `"reconnecting"`
368
+ and `"closed"`. A frame the document was served through `live` connects once
369
+ the page is claimed, and closes when the last place it is mounted goes. A
370
+ `live` call to a function that answers with values rather than a frame reads
371
+ one value per event.
372
+
373
+ A `live` answer is rendered once per connection, because it may depend on who
374
+ is asking. When it does not, `broadcast` renders it once for everyone asking
375
+ with the same arguments:
376
+
377
+ ```ts
378
+ export const getTicker = createServerFn({ method: "GET", broadcast: true })
379
+ .validator((input: { symbol: string }) => input)
380
+ .handler(async ({ data }) => {
381
+ if (!(await canSee(data.symbol))) throw new Response("forbidden", { status: 403 });
382
+ return tickerFor(data.symbol);
383
+ });
384
+ ```
385
+
386
+ The handler still runs for every caller, so it is where a check belongs, and a
387
+ later caller's own answer is closed unread. A connection that joins is handed
388
+ the latest event at once. The shared rendering runs outside every request, so
389
+ it reads no cookie, header or session, and it stops when its last connection
390
+ goes.
391
+
392
+ ### With JavaScript off
393
+
394
+ ```tsx
395
+ <form action={createPost}>
396
+ <input name="title" />
397
+ <button type="submit">post</button>
398
+ </form>
399
+ ```
400
+
401
+ `action={fn}` writes the endpoint and `method="post"` together, and the handler
402
+ receives a real `FormData`. The same function sees the same input type whether
403
+ or not JS ran, which is the divergence progressive enhancement exists to
404
+ prevent.
405
+
406
+ ## Middleware, and the check the build runs
407
+
408
+ ```ts
409
+ import { createMiddleware, createServerFn, useSession } from "@barqjs/start";
410
+
411
+ export const requireSession = createMiddleware().server(async ({ next }) => {
412
+ const session = await useSession<{ user: string }>(sessionConfig);
413
+ if (session.data.user === undefined) throw new Response("sign in first", { status: 401 });
414
+ return next({ context: { user: session.data.user } });
415
+ });
416
+
417
+ export const adminStats = createServerFn()
418
+ .middleware([requireSession])
419
+ .handler(({ context }) => stats(context.user)); // context.user: string
420
+ ```
421
+
422
+ What a middleware passes to `next({ context })` is TYPED into everything after
423
+ it: the handler's `context`, the `context` of a middleware that lists it in its
424
+ own `.middleware([...])`, and a route handler's under `server.middleware`. A key
425
+ no typed step declared still reads, as `unknown`. A bare closure states what it
426
+ adds, and is checked against it:
427
+
428
+ ```ts
429
+ const tenant: Middleware<{ tenant: string }> = async (next) => next({ context: { tenant } });
430
+ ```
431
+
432
+ A middleware's `.validator()` types its own `data` and, when the function has
433
+ none of its own, the handler's and the caller's. A client half's `next()` takes
434
+ `headers`, `sendContext` and `fetch`; the call's own `headers` and `fetch` win
435
+ over a middleware's, and a later middleware's over an earlier one's. What a
436
+ client half sends arrives on the server as `clientContext`, untyped on purpose:
437
+ it is whatever the caller chose to send.
438
+
439
+ A middleware ends in `return next(...)`, answers with a result of its own (a
440
+ `Response` included), or throws. Returning `undefined` is neither: without
441
+ `next()` the call would have no answer, and after it the handler's result would
442
+ be lost. Either way the call fails with an error naming the middleware (its
443
+ function's name when it has one), its place in the chain and the server
444
+ function, as TanStack's does. A returned `redirect()` or `notFound()` is thrown
445
+ as the answer it describes. A middleware's halves are also handed `method` and
446
+ `serverFnMeta`.
447
+
448
+ A server function in the list stands for the middleware it declared, as in
449
+ TanStack: `.middleware([whoami])` runs `whoami`'s guards, typed, and never its
450
+ handler. A second `.middleware([...])` call adds to the chain.
451
+
452
+ Middleware runs BEFORE validation, deliberately: an unauthenticated caller
453
+ should be refused without the server parsing its payload, and a rejection that
454
+ depended on well-formed input is one an attacker skips by sending malformed
455
+ input. A middleware refuses by THROWING a `Response`.
456
+
457
+ Declare the same closure on the route, and the build checks the two agree:
458
+
459
+ ```ts
460
+ // vite.config.ts
461
+ barq({ ssr: true, start: { verify: true } });
462
+
463
+ // src/routes/admin.tsx
464
+ export const Route = createFileRoute("/admin")({ middleware: [requireSession] });
465
+ ```
466
+
467
+ A server function is its own HTTP endpoint, so a guard on the route that
468
+ renders it does not run when the function is called directly. Next.js and
469
+ TanStack both document that gap and leave it to the author. `vite build` walks
470
+ the client module graph from each route to the functions it can reach, and fails
471
+ naming the route, the function, and how much of the chain is missing.
472
+
473
+ It VALIDATES AND REJECTS, never redispatches. Re-running a mis-routed action
474
+ under the owning route's middleware executes it in a different request context.
475
+ The deeper reason: a client-supplied route selecting a middleware chain lets the
476
+ caller pick the weakest chain that reaches the action.
477
+
478
+ The chain is compared by reference identity. `Middleware` is an anonymous
479
+ closure with no build-visible name, and every attempt to read `.middleware([…])`
480
+ out of source dies on the shapes people write: `[m]`, `[...chain]`,
481
+ `chain.filter(Boolean)`.
482
+
483
+ ## The request context
484
+
485
+ ```ts
486
+ import { getRequest, getRequestHeader, setCookie, setResponseHeader } from "@barqjs/start";
487
+ ```
488
+
489
+ These read an ambient request, so a loader, a route handler, a server function
490
+ and a middleware all reach it the same way. It is an `AsyncLocalStorage` and not
491
+ a module variable: two requests are in flight at once on any real server, and a
492
+ module variable hands one request's session to another. That has shipped
493
+ elsewhere as cross-user data disclosure.
494
+
495
+ `setCookie` and `deleteCookie` default to `path: "/"`. A browser would otherwise
496
+ scope the cookie to `/_barq/fn`, the directory of the URL that set it, and no
497
+ page would receive it. `appendResponseHeader` adds to a list header such as
498
+ `Vary`, where `setResponseHeader` replaces.
499
+
500
+ `setResponseHeader` and `setCookie` write to a DRAFT, because the response is
501
+ built after the handler returns and a streamed response is handed back before
502
+ its body exists. The draft rides an error out too, so a middleware that rotated
503
+ a session cookie and then refused does not lose the rotation.
504
+
505
+ ## Sessions
506
+
507
+ ```ts
508
+ import { type SessionConfig, useSession } from "@barqjs/start";
509
+
510
+ const sessionConfig: SessionConfig = {
511
+ password: process.env.SESSION_PASSWORD!, // at least 32 characters
512
+ cookie: { secure: true },
513
+ };
514
+
515
+ const session = await useSession<{ user: string }>(sessionConfig);
516
+ session.data.user;
517
+ const next = await session.update({ user: "salama" });
518
+ ```
519
+
520
+ A sealed cookie with no store behind it: AES-GCM through WebCrypto, so no
521
+ dependency and no encrypt-then-MAC composition to get wrong.
522
+
523
+ `session.data` is READ-ONLY and `update()` returns a NEW manager. The handle you
524
+ already hold is deliberately unchanged, so nothing can read a half-applied
525
+ session.
526
+
527
+ The expiry is enforced on UNSEAL as well as on the cookie, because a cookie's
528
+ own expiry is a request the client is free to ignore.
529
+
530
+ The cookie's NAME is under the seal. Two sessions sharing a password (`name:
531
+ "barq-session-admin"` beside the default) are two sessions: a value issued under
532
+ one name does not open under the other. Envelopes start `b2.`; a `b1.` cookie
533
+ from an older release opens until it expires, under any name, and is sealed as
534
+ `b2` the next time the session is updated.
535
+
536
+ The password is a KEY: anyone holding it can mint a session for any user.
537
+ Rotating it logs everyone out, which is the intended way to do that.
538
+
539
+ ## Rate limiting
540
+
541
+ ```ts
542
+ import { byIP, createServerFn, memoryStore, rateLimit } from "@barqjs/start";
543
+
544
+ const limit = rateLimit({
545
+ limit: 30,
546
+ windowMs: 60_000,
547
+ key: byIP(),
548
+ store: memoryStore(),
549
+ });
550
+
551
+ export const login = createServerFn({ method: "POST" })
552
+ .middleware([limit])
553
+ .validator(LoginSchema)
554
+ .handler(({ data }) => signIn(data));
555
+ ```
556
+
557
+ `rateLimit` returns a middleware, so the same value guards a server function or
558
+ a route's `server.middleware`. It runs before validation. Past the limit it
559
+ throws a 429 with `Retry-After`, or what `onLimit(info)` returns. A store that
560
+ throws lets the request through and logs the error, because a limiter that
561
+ refuses everything while its store is down has become the outage.
562
+
563
+ Build it ONCE at module scope. The store is the state, and a fresh one per
564
+ request counts to one forever. A store is one atomic method,
565
+ `hit(key, windowMs)`, returning `{ count, resetAt }`; Redis does it with `INCR`
566
+ and `PEXPIRE`.
567
+
568
+ Neither `key` nor `store` has a default, and that is the point:
569
+
570
+ - Keying by IP is right for a public endpoint and wrong for an authenticated
571
+ one behind a corporate NAT, where it limits a building as though it were one user.
572
+ Key by user id where there is one. Returning `null` exempts the caller.
573
+ - `memoryStore()` is correct for a single instance and wrong behind a load
574
+ balancer, where three instances permit three times the limit.
575
+
576
+ `byIP()` does not trust `X-Forwarded-For` unless you ask, because a caller who
577
+ can set that header picks their own bucket. There are two ways to ask:
578
+
579
+ - `byIP({ xForwardedFor: true })` reads the leftmost entry. That is the client
580
+ only when your edge proxy OVERWRITES the header. Behind one that appends, the
581
+ leftmost entry is whatever the caller sent.
582
+ - `byIP({ xForwardedFor: { trustedProxies: 1 } })` counts from the right: the
583
+ entry the nth proxy you run wrote. A forged prefix is never read, and a
584
+ header with fewer entries than proxies is ignored.
585
+
586
+ ### Global middleware
587
+
588
+ `src/start.ts` declares what runs for the whole application:
589
+
590
+ ```ts
591
+ import { createMiddleware, createStart } from "@barqjs/start";
592
+
593
+ const logging = createMiddleware({ type: "request" }).server(
594
+ async ({ next, request, pathname }) => {
595
+ const started = performance.now();
596
+ const response = await next({ context: { requestId: crypto.randomUUID() } });
597
+ log(request.method, pathname, performance.now() - started);
598
+ return response;
599
+ },
600
+ );
601
+
602
+ export const startInstance = createStart(() => ({
603
+ requestMiddleware: [logging], // every page, route handler and server function
604
+ functionMiddleware: [requireSession], // every server function, ahead of its own chain
605
+ serializationAdapters: [money], // a type only the application knows, both ways
606
+ serverFns: { fetch: tracedFetch }, // every call, unless a middleware or the call names one
607
+ defaultSsr: "data-only", // every route that says nothing about `ssr`
608
+ }));
609
+ ```
610
+
611
+ `createSerializationAdapter({ key, test, toSerializable, fromSerializable })`
612
+ makes an adapter. The ones named here are installed the first time the options
613
+ are read, which the server does before it answers anything and the browser
614
+ before it reads the page's seed. `defaultSsr` wins over the router's own, on
615
+ both sides.
616
+
617
+ The order is global request, global function, then the function's own. What a
618
+ request middleware passes to `next({ context })` starts every server function's
619
+ `context`, reaches a route handler's, and is `getGlobalStartContext()` anywhere
620
+ in the request. A `{ type: "function" }` middleware may have a `.client()` half,
621
+ which runs in the browser around every call.
622
+
623
+ A global request middleware runs after a call has passed the method, origin and
624
+ id checks, and before its body is read, so a forged request reaches none of it.
625
+
626
+ Register the instance and what the global middleware adds is typed too, in every
627
+ handler's `context` and in `getGlobalStartContext()` (each key optional there,
628
+ since it can be called outside a request):
629
+
630
+ ```ts
631
+ declare module "@barqjs/start" {
632
+ interface Register {
633
+ start: typeof startInstance;
634
+ }
635
+ }
636
+ ```
637
+
638
+ ### With Solid's async primitives
639
+
640
+ A server function returns a promise, so it is what an async memo reads and what
641
+ an `action` yields:
642
+
643
+ ```tsx
644
+ const notes = createMemo(async () => listNotes());
645
+ const [guesses, setGuesses] = createOptimistic<readonly Note[]>([]);
646
+
647
+ const add = action(function* (text: string) {
648
+ setGuesses((list) => [...list, { id: -1, text }]); // shown at once, dropped when this settles
649
+ yield addNote({ data: { text } });
650
+ refresh(notes); // the real row arrives with the refreshed list
651
+ });
652
+ ```
653
+
654
+ On the server the memo's call is in-process and its answer seeds the page, so
655
+ the browser does not ask again until `refresh`.
656
+
657
+ ## Subpaths
658
+
659
+ - `@barqjs/start`: the isomorphic surface. `createServerFn`, `createMiddleware`,
660
+ `createStart`, the request context, sessions, cookies, rate limiting.
661
+ - `@barqjs/start/client`: the RPC stub the compiler emits,
662
+ `staticFunctionMiddleware`, `live`, and the browser half of frames:
663
+ `applyFrameResponse` and `frameAdapter`, which `@barqjs/router`'s client
664
+ entry installs for a frame named in the seed.
665
+ - `@barqjs/start/server`: `handleServerFn`, `mount`, the origin check.
666
+ - `@barqjs/start/serve`: `serveBarq`, `createFetchHandler`, the asset
667
+ middleware.
668
+ - `@barqjs/start/prerender`: the prerenderer, for a custom build.
669
+ - `@barqjs/start/middleware` and `@barqjs/start/env`: the middleware runner and
670
+ the one-side functions, split out so the client stub can import them without
671
+ reaching `node:async_hooks`. The compiler emits these; import from
672
+ `@barqjs/start` instead.
673
+ - `@barqjs/start/protocol`: the server-entry contract router and vite share.
674
+ Not public API.
675
+
676
+ ## The build and the server
677
+
678
+ The Vite side is `@barqjs/vite`, one plugin for the compiler, the file routes
679
+ and this package's build:
680
+
681
+ ```ts
682
+ import barq from "@barqjs/vite";
683
+
684
+ barq({ ssr: true, start: { prerender: { routes: ["/"] } } }); // server-rendered
685
+ barq({ start: true }); // an SPA: `index.html` is the document, the server keeps the RPC
686
+ ```
687
+
688
+ `start` is what this package adds: server functions and API routes, the dev
689
+ server's page and function middleware, `vite preview`, and a `vite build` that
690
+ builds the client and then the server. `ssr` decides whether the server renders
691
+ pages, and with them whether both halves compile hydratable.
692
+
693
+ `vite build` emits two directories:
694
+
695
+ ```
696
+ dist/client/ the browser bundle, plus every prerendered page
697
+ dist/server/
698
+ server.js importable; default-exports the handler and serves nothing
699
+ serve.js runnable: `bun dist/server/serve.js`
700
+ index.js `{ fetch }` over server functions and pages, for a host
701
+ ```
702
+
703
+ They are two files because `bun <file>` auto-serves any default export carrying
704
+ a `fetch`, so one entry that both exported the handler and started a server
705
+ would bind the port twice. It also keeps a `serve()` out of the module `vite
706
+ build` imports to prerender.
707
+
708
+ `serve.js` answers in this order: static assets from a manifest the build wrote,
709
+ then server functions, then the page handler. The static lookup costs 0.33 µs
710
+ per request against the 0.75 µs a `statSync` costs, and a prerendered page keeps
711
+ the status it was rendered as.
712
+
713
+ `vite preview` serves `dist/client` and sends everything else through
714
+ `index.js`, so it runs what a deployment runs.
715
+
716
+ A plugin that owns the `ssr` environment, such as `@cloudflare/vite-plugin` or
717
+ Nitro, runs the server half itself. The dev server then leaves pages and server
718
+ functions to that plugin's runtime, which imports the `index` input the way a
719
+ deployment does, and a host that orchestrates `vite build` builds the server
720
+ after barq has built the client. `prerender` and `verify` import the server
721
+ bundle barq builds, so under such a host they do not run, and the build says so.
722
+
723
+ Prerendering takes three more options:
724
+
725
+ ```ts
726
+ barq({
727
+ ssr: true,
728
+ start: {
729
+ prerender: {
730
+ routes: ["/", "/404"],
731
+ retryCount: 2, // ask again after a throw or a 5xx; a 4xx is an answer
732
+ retryDelay: 500, // ms between attempts
733
+ sitemap: { host: "https://example.com" }, // outputPath defaults to sitemap.xml
734
+ },
735
+ },
736
+ });
737
+ ```
738
+
739
+ The sitemap lists every page written with a 2xx, sorted. A page prerendered at
740
+ `/404` is left out of it and is also written to `404.html` at the root, the name
741
+ a static host serves for a path it has no file for.
742
+
743
+ SPA mode renders the pages in the browser from one shell:
744
+
745
+ ```ts
746
+ barq({
747
+ ssr: true,
748
+ start: { spa: { enabled: true, maskPath: "/", prerender: { outputPath: "/_shell.html" } } },
749
+ });
750
+ ```
751
+
752
+ `ssr` stays on: the server renders the shell and the client hydrates it.
753
+
754
+ The build renders the root route once, with nothing under it, and writes that
755
+ document. The server then renders no pages: a navigation nothing else answers
756
+ gets the shell, and server functions and route handlers answer as before.
757
+
758
+ Under `static`, a name the build hashed (everything it emitted under
759
+ `build.assetsDir`) is answered `max-age=31536000, immutable`. A file with a
760
+ stable name, and every prerendered page, gets an `ETag` and a 304 instead.
761
+
762
+ Behind a proxy that terminates TLS, tell the generated server so, or the origin
763
+ check sees `http://` where the browser said `https://` and refuses every server
764
+ function:
765
+
766
+ ```ts
767
+ barq({
768
+ ssr: true,
769
+ start: {
770
+ server: {
771
+ trustProxy: "loopback", // or true, or the proxy addresses
772
+ allowedOrigins: ["https://admin.example.com"], // beyond the server's own
773
+ },
774
+ },
775
+ });
776
+ ```
777
+
778
+ ### Functions for one side
779
+
780
+ ```ts
781
+ import { createClientOnlyFn, createIsomorphicFn, createServerOnlyFn } from "@barqjs/start";
782
+
783
+ const readConfig = createServerOnlyFn(() => process.env.API_TOKEN);
784
+ const storage = createClientOnlyFn(() => localStorage);
785
+ const now = createIsomorphicFn()
786
+ .server(() => "server")
787
+ .client(() => "browser");
788
+ ```
789
+
790
+ The compiler replaces these calls in each bundle. `createServerOnlyFn` keeps its
791
+ body in the server build and becomes a throwing stub in the browser, so a secret
792
+ cannot reach the client even as dead code. `createClientOnlyFn` is the mirror.
793
+ `createIsomorphicFn` keeps one half per bundle, and a half that is not declared
794
+ is a no-op. Uncompiled code, such as a `bun test`, gets the server half.
795
+
796
+ ### Server-only and client-only files
797
+
798
+ `db.server.ts` is for what must not leave the server, `chart.client.ts` for what
799
+ cannot run there. `vite build` fails when code from a `.server.` file is in a
800
+ browser chunk or code from a `.client.` file is in the server bundle, naming the
801
+ file and what imported it. It reads the rendered bundle, so a `.server.` import
802
+ used only inside `createServerOnlyFn`, or a module whose exports are server
803
+ functions, is not a violation. `start: { importProtection: false }` turns it off.
804
+
805
+ `import "server-only"` and `import "client-only"` mark a module the same way at
806
+ the import itself: `@barqjs/vite` fails the build where the browser bundle
807
+ imports `server-only` or the server bundle imports `client-only`, naming the
808
+ importer. Add `/// <reference types="@barqjs/vite/boundary-modules" />` for
809
+ their types.
810
+
811
+ Deployment goes through [srvx](https://github.com/h3js/srvx), so Node, Bun, Deno
812
+ and Cloudflare take the same entry.
813
+
814
+ ### Entry files are optional
815
+
816
+ `src/entry-client.tsx` and `src/entry-server.tsx` are overrides. The defaults
817
+ are two lines each and the plugin supplies them; nothing in an application names
818
+ a `virtual:` or `#`-prefixed specifier.