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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +791 -2
  3. package/dist/client-BHyIiYxt.js +1527 -0
  4. package/dist/client-BHyIiYxt.js.map +1 -0
  5. package/dist/client-DHCV7yvQ.d.ts +440 -0
  6. package/dist/client-DHCV7yvQ.d.ts.map +1 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-qA8EyOr1.d.ts +49 -0
  10. package/dist/env-qA8EyOr1.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +44 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-Bm_-MTj6.d.ts +915 -0
  15. package/dist/index-Bm_-MTj6.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-BdVlE8qm.d.ts +576 -0
  19. package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +282 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +98 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +58 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +26 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +135 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +223 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-BV3xKmLa.js +1148 -0
  36. package/dist/server-BV3xKmLa.js.map +1 -0
  37. package/dist/server.d.ts +142 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-ChnB_xug.js +1140 -0
  41. package/dist/src-ChnB_xug.js.map +1 -0
  42. package/dist/static-fn-DgjNArBe.js +123 -0
  43. package/dist/static-fn-DgjNArBe.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +672 -0
  46. package/src/context.ts +666 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +97 -0
  50. package/src/frames-client.ts +1216 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +714 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +182 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +990 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +139 -0
@@ -0,0 +1,1140 @@
1
+ import { P as asFrame, _ as dataOf, b as urlOf, h as callOptionsOf, m as SERVER_FN_CHAIN, p as SERVER_FN, v as inlineServerFns, w as startOptions } from "./client-BHyIiYxt.js";
2
+ import { UncheckedInputError, applyValidator, flattenMiddleware, isBuiltMiddleware, runMiddleware, toValidator } from "./middleware.js";
3
+ import { commitResponseStub, createRequestEvent, createResponseStub, foldResponseStub } from "@barqjs/web/internal";
4
+ import { diagnosticsEnabled, emitDiagnostic } from "@barqjs/core/internal";
5
+ import { provideRequestEvent } from "@barqjs/server/storage";
6
+ import { createSerializationAdapter } from "@barqjs/server/codec";
7
+ //#region src/cookies.ts
8
+ /** A control character, or DEL. The RFC defines every set below by code point. */
9
+ const isControl = (code) => code <= 31 || code === 127;
10
+ /** Whether any character of `text` is one `refused` names. */
11
+ function holdsAny(text, refused) {
12
+ for (let index = 0; index < text.length; index++) if (refused(text.charCodeAt(index))) return true;
13
+ return false;
14
+ }
15
+ const codes = (characters) => new Set(Array.from(characters, (character) => character.charCodeAt(0)));
16
+ const NAME_SEPARATORS = codes(" ()<>@,;:\\\"/[]?={}");
17
+ const VALUE_SEPARATORS = codes(" \",;\\");
18
+ const SEMICOLON = 59;
19
+ /**
20
+ * A separator or a control character, neither of which a cookie NAME may hold
21
+ * (RFC 6265 §4.1.1: a name is a `token`).
22
+ */
23
+ const illegalInName = (code) => isControl(code) || NAME_SEPARATORS.has(code);
24
+ /** What a cookie VALUE may not hold (RFC 6265 §4.1.1: `cookie-octet`). */
25
+ const illegalInValue = (code) => isControl(code) || VALUE_SEPARATORS.has(code);
26
+ /** What an attribute value may not hold, since `;` ends it. */
27
+ const illegalInAttribute = (code) => isControl(code) || code === SEMICOLON;
28
+ /**
29
+ * Every cookie on a request, by name.
30
+ *
31
+ * FIRST WINS on a duplicate, which is what a browser sends when one cookie
32
+ * exists at two paths and is what every parser in the survey does. A value that
33
+ * is not valid percent-encoding comes back RAW rather than throwing: it arrived
34
+ * off the wire, a client may put anything there, and one malformed cookie must
35
+ * not take the request down.
36
+ */
37
+ function parseCookies(header) {
38
+ const out = Object.create(null);
39
+ if (header === null || header === void 0 || header === "") return out;
40
+ for (const pair of header.split(";")) {
41
+ const equals = pair.indexOf("=");
42
+ if (equals < 0) continue;
43
+ const name = pair.slice(0, equals).trim();
44
+ if (name === "" || name in out) continue;
45
+ let value = pair.slice(equals + 1).trim();
46
+ if (value.length > 1 && value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
47
+ out[name] = decode(value);
48
+ }
49
+ return out;
50
+ }
51
+ function decode(value) {
52
+ if (!value.includes("%")) return value;
53
+ try {
54
+ return decodeURIComponent(value);
55
+ } catch {
56
+ return value;
57
+ }
58
+ }
59
+ /**
60
+ * One `Set-Cookie` line.
61
+ *
62
+ * Throws on any combination a browser would drop in silence — see the header
63
+ * for which, and why a throw is the kinder answer.
64
+ */
65
+ function serializeCookie(name, value, options = {}) {
66
+ if (name === "" || holdsAny(name, illegalInName)) throw new TypeError(`[barq] ${JSON.stringify(name)} is not a valid cookie name, and a browser would drop the cookie. A name made of letters, digits, \`-\` and \`_\`, such as \`"session_id"\`, is always valid.`);
67
+ const secure = options.secure ?? false;
68
+ const path = options.path;
69
+ if (options.sameSite === "none" && !secure) throw new TypeError(`[barq] The cookie "${name}" sets \`sameSite: "none"\` without \`secure: true\`, and browsers drop a SameSite=None cookie that is not Secure (RFC 6265bis §5.4.7). Add \`secure: true\`, or use \`sameSite: "lax"\`.`);
70
+ if (options.partitioned === true && !secure) throw new TypeError(`[barq] The cookie "${name}" sets \`partitioned: true\` without \`secure: true\`, and a browser rejects a Partitioned cookie that is not Secure. Add \`secure: true\`.`);
71
+ if (name.startsWith("__Host-")) {
72
+ if (!secure || path !== "/" || options.domain !== void 0) throw new TypeError(`[barq] The cookie "${name}" uses the \`__Host-\` prefix without the options the prefix requires, so a browser would reject it (RFC 6265bis §4.1.3). Set \`secure: true\` and \`path: "/"\`, and leave \`domain\` unset.`);
73
+ } else if (name.startsWith("__Secure-") && !secure) throw new TypeError(`[barq] The cookie "${name}" uses the \`__Secure-\` prefix without \`secure: true\`, so a browser would reject it (RFC 6265bis §4.1.3). Add \`secure: true\`.`);
74
+ const encoded = (options.encode ?? encodeURIComponent)(value);
75
+ if (holdsAny(encoded, illegalInValue)) throw new TypeError(`[barq] The value of the cookie "${name}" holds a character a cookie cannot carry after the custom \`encode\` ran, such as \`;\`, a space or a control character. A browser would cut the value short. Leave \`encode\` at its default, which percent-encodes it.`);
76
+ const parts = [`${name}=${encoded}`];
77
+ if (options.maxAge !== void 0) {
78
+ if (!Number.isInteger(options.maxAge)) throw new TypeError(`[barq] The cookie "${name}" has a non-integer maxAge (${options.maxAge}). A browser ignores a fractional \`Max-Age\` instead of rounding it, so the cookie would last only for the session. Pass whole seconds, such as \`maxAge: 3600\`.`);
79
+ parts.push(`Max-Age=${options.maxAge}`);
80
+ }
81
+ if (options.domain !== void 0) {
82
+ assertAttribute(name, "domain", options.domain);
83
+ parts.push(`Domain=${options.domain}`);
84
+ }
85
+ if (path !== void 0) {
86
+ assertAttribute(name, "path", path);
87
+ parts.push(`Path=${path}`);
88
+ }
89
+ if (options.expires !== void 0) {
90
+ if (Number.isNaN(options.expires.getTime())) throw new TypeError(`[barq] The cookie "${name}" has an \`expires\` that is an invalid \`Date\`, so no expiry could be written. Pass a valid date, such as \`new Date(Date.now() + 86_400_000)\`.`);
91
+ parts.push(`Expires=${options.expires.toUTCString()}`);
92
+ }
93
+ if (options.httpOnly === true) parts.push("HttpOnly");
94
+ if (secure) parts.push("Secure");
95
+ if (options.partitioned === true) parts.push("Partitioned");
96
+ if (options.priority !== void 0) parts.push(`Priority=${capitalize(options.priority)}`);
97
+ if (options.sameSite !== void 0) parts.push(`SameSite=${capitalize(options.sameSite)}`);
98
+ return parts.join("; ");
99
+ }
100
+ function assertAttribute(cookie, attribute, value) {
101
+ if (holdsAny(value, illegalInAttribute)) throw new TypeError(`[barq] The cookie "${cookie}" has a \`${attribute}\` holding a character such as \`;\` that would terminate the attribute and let the rest be read as further cookie attributes. Pass a plain ${attribute}, and never build it from user input without validating it.`);
102
+ }
103
+ function capitalize(value) {
104
+ return value.charAt(0).toUpperCase() + value.slice(1);
105
+ }
106
+ /**
107
+ * The line that DELETES a cookie.
108
+ *
109
+ * A cookie is deleted by being set again, expired — and the `path` and `domain`
110
+ * must MATCH the ones it was set with, or the browser deletes nothing and keeps
111
+ * the original. That is why both ride through rather than being dropped: a
112
+ * `deleteCookie("sid")` against a cookie set at `path: "/app"` is a no-op, and
113
+ * a silent one.
114
+ */
115
+ function deleteCookieLine(name, options = {}) {
116
+ return serializeCookie(name, "", {
117
+ ...options,
118
+ expires: /* @__PURE__ */ new Date(0),
119
+ maxAge: 0
120
+ });
121
+ }
122
+ //#endregion
123
+ //#region src/context.ts
124
+ const REQUEST_EVENT = Symbol.for("barq.request-event");
125
+ /**
126
+ * The request event's storage, under the symbol `getRequestEvent` reads and
127
+ * `provideRequestEvent` enters, so a component asking Solid's way finds the
128
+ * request a handler entered.
129
+ *
130
+ * ONE storage per process, whichever copy of this module asks: a build
131
+ * compiles this module into its server bundle, and a host serving that bundle
132
+ * through its own `serveBarq` has imported a second copy. Each holding its own,
133
+ * the host entered the request into one and the bundle's functions read the
134
+ * other, so every server function that read a cookie answered 500.
135
+ *
136
+ * Read lazily, and nothing is constructed here: `@barqjs/start` is the
137
+ * ISOMORPHIC entry, so a browser bundle evaluates this module, and a bundler
138
+ * answers `node:async_hooks` there with an empty stub. No storage is no
139
+ * request in flight, which is what the read path reports.
140
+ */
141
+ const SHARED = { get storage() {
142
+ return globalThis[REQUEST_EVENT];
143
+ } };
144
+ /** A fresh, empty draft, one per request: Solid's `createResponseStub`. */
145
+ const createResponseDraft = createResponseStub;
146
+ /**
147
+ * Send `@barqjs/css`'s render-time rules to whichever request is running.
148
+ *
149
+ * Installed once, by the generated server entry. Outside a request — module
150
+ * scope, and the browser — there is nothing to attribute a rule to, so it falls
151
+ * back to the package's own sheet, which is where a module-scope rule belongs.
152
+ */
153
+ function collectRequestCss() {
154
+ const store = SHARED.storage?.getStore();
155
+ if (store?.lateCss !== void 0) return store.lateCss();
156
+ return store?.css === void 0 ? "" : [...store.css.values()].join("");
157
+ }
158
+ function installCssSink(setSink) {
159
+ const sink = (key, rules) => {
160
+ const store = SHARED.storage?.getStore();
161
+ if (store === void 0) return false;
162
+ store.css ??= /* @__PURE__ */ new Map();
163
+ store.css.set(key, rules);
164
+ return true;
165
+ };
166
+ sink.head = (late) => {
167
+ const store = SHARED.storage?.getStore();
168
+ if (store !== void 0) store.lateCss ??= late;
169
+ };
170
+ setSink(sink);
171
+ }
172
+ /**
173
+ * Run `body` with `request` as the ambient one, under the event
174
+ * `createRequestEvent` builds for it and `provideRequestEvent` enters.
175
+ *
176
+ * The DRAFT is the caller's to hold, because the caller is what builds the
177
+ * response and it does so after `body` has returned.
178
+ */
179
+ function withRequest(request, body, options = {}) {
180
+ const resolved = typeof options === "string" ? { refuse: options } : options;
181
+ return provideRequestEvent(createRequestEvent(request, {
182
+ refuse: resolved.refuse,
183
+ response: resolved.response ?? createResponseStub()
184
+ }), body);
185
+ }
186
+ /**
187
+ * The request this handler is running for.
188
+ *
189
+ * Throws outside one rather than returning undefined: a handler reading cookies
190
+ * off `undefined` is a bug that should surface where it happens, not resolve to
191
+ * "no session" and let the request through.
192
+ */
193
+ function getRequest() {
194
+ return context().request;
195
+ }
196
+ /**
197
+ * The request, or undefined outside one. For code that legitimately runs both ways.
198
+ *
199
+ * A refused context reads as ABSENT here rather than throwing: `peekRequest` is
200
+ * the "I may not be in a request" spelling, and a prerender is exactly that
201
+ * case. Code that must have one calls `getRequest` and gets the refusal.
202
+ */
203
+ function peekRequest() {
204
+ const found = SHARED.storage?.getStore();
205
+ return found === void 0 || found.refuse !== void 0 ? void 0 : found.request;
206
+ }
207
+ function context() {
208
+ const found = SHARED.storage?.getStore();
209
+ if (found === void 0) throw new Error("[barq] A request helper such as `getRequest()`, `getCookie()` or `setResponseHeader()` was called outside a request, so there is no request to read and no response to write to. These helpers are only available inside a request: call them from a server function, a route handler, a loader or a `beforeLoad`.");
210
+ if (found.refuse !== void 0) throw new Error(found.refuse);
211
+ return found;
212
+ }
213
+ /**
214
+ * The draft, or `undefined` outside a request.
215
+ *
216
+ * Used by the two handlers to merge on the way out, and by nothing else. A
217
+ * REFUSED context still answers here: a prerender may not read the request, but
218
+ * a `head` or a loader that sets a cache header during one is describing the
219
+ * page rather than the requester, and the prerenderer can write it to disk.
220
+ */
221
+ function peekResponseDraft() {
222
+ return SHARED.storage?.getStore()?.response;
223
+ }
224
+ /**
225
+ * Leave a chain's `sendContext` for whoever builds this request's response.
226
+ *
227
+ * Outside a request there is no response to carry it, so it is dropped: that is
228
+ * a server function called in-process, whose caller is handed the result alone.
229
+ */
230
+ function offerSendContext(sendContext) {
231
+ const found = SHARED.storage?.getStore();
232
+ if (found !== void 0) found.sendContext = sendContext;
233
+ }
234
+ /**
235
+ * Say that this mutation changed what these server functions' frames show, so
236
+ * its answer carries those regions, rendered again, beside its value: single
237
+ * flight, one round trip. A frame the page has not mounted is not rendered.
238
+ * Outside a request it does nothing, as there is no answer to carry them.
239
+ */
240
+ function invalidateFrames(...fns) {
241
+ const found = SHARED.storage?.getStore();
242
+ if (found === void 0) return;
243
+ found.invalidatedFrames ??= /* @__PURE__ */ new Set();
244
+ for (const fn of fns) found.invalidatedFrames.add(fn.meta.id);
245
+ }
246
+ /** The server functions `invalidateFrames` named in this request, or none. */
247
+ function invalidatedFrames() {
248
+ return SHARED.storage?.getStore()?.invalidatedFrames ?? EMPTY_SET;
249
+ }
250
+ const EMPTY_SET = /* @__PURE__ */ new Set();
251
+ /** Take the pending `sendContext`, leaving nothing behind for the next call. */
252
+ function takeSendContext() {
253
+ const found = SHARED.storage?.getStore();
254
+ const taken = found?.sendContext ?? {};
255
+ if (found !== void 0) found.sendContext = void 0;
256
+ return taken;
257
+ }
258
+ /**
259
+ * What this request's middleware chain has contributed, or an empty record
260
+ * outside a request. TanStack's name.
261
+ *
262
+ * Typed by what the registered global request middleware passes to
263
+ * `next({ context })`, each key optional: outside a request, or before the
264
+ * chain has reached the step that adds it, it is not there.
265
+ */
266
+ function getGlobalStartContext() {
267
+ return SHARED.storage?.getStore()?.middlewareContext ?? {};
268
+ }
269
+ /** Record what the request middleware chain is contributing, for the rest of the request. */
270
+ function setRequestMiddlewareContext(context) {
271
+ const found = SHARED.storage?.getStore();
272
+ if (found !== void 0) found.middlewareContext = context;
273
+ }
274
+ /** The sessions this request has opened. See {@link RequestContext.sessions}. */
275
+ function openSessions() {
276
+ const found = context();
277
+ found.sessions ??= /* @__PURE__ */ new Map();
278
+ return found.sessions;
279
+ }
280
+ function getRequestHeaders() {
281
+ return getRequest().headers;
282
+ }
283
+ function getRequestHeader(name) {
284
+ return getRequest().headers.get(name) ?? void 0;
285
+ }
286
+ /** The request URL, parsed. */
287
+ function getRequestUrl() {
288
+ return new URL(getRequest().url);
289
+ }
290
+ /** Refuse a hop count that names no entry, where the option is written. */
291
+ function assertForwardedForTrust(trust) {
292
+ if (typeof trust !== "object") return;
293
+ if (!Number.isInteger(trust.trustedProxies) || trust.trustedProxies < 1) throw new RangeError(`[barq] \`trustedProxies\` must be a positive integer, and it is ${trust.trustedProxies}. Set it to the number of proxies you run in front of this server: each one appends one entry to \`X-Forwarded-For\`, and the client address is counted back from the end.`);
294
+ }
295
+ /**
296
+ * The client's address, or `undefined`.
297
+ *
298
+ * `xForwardedFor` IS OFF BY DEFAULT and that is the whole design of this
299
+ * function. `X-Forwarded-For` is a header a client can send, so trusting it
300
+ * unconditionally lets any caller claim any address — and an address is exactly
301
+ * what rate limiting and audit logging key on. It is trustworthy only when a
302
+ * proxy you control overwrites it, which is a fact about the deployment that
303
+ * this process cannot discover. So it is opt-in, and the opt-in is per call.
304
+ *
305
+ * The LEFTMOST entry is taken when it is trusted, since that is the original
306
+ * client; every entry to its right was appended by a hop. {@link
307
+ * ForwardedForTrust} says when that is forgeable and what to pass instead.
308
+ */
309
+ function getRequestIP(options = {}) {
310
+ const request = getRequest();
311
+ const trust = options.xForwardedFor;
312
+ if (trust !== void 0 && trust !== false) {
313
+ assertForwardedForTrust(trust);
314
+ const entries = request.headers.get("x-forwarded-for")?.split(",") ?? [];
315
+ const address = (trust === true ? entries[0] : entries[entries.length - trust.trustedProxies])?.trim();
316
+ if (address !== void 0 && address !== "") return address;
317
+ }
318
+ const direct = request.ip;
319
+ return direct === "" ? void 0 : direct;
320
+ }
321
+ /**
322
+ * The host, from the URL — and from `X-Forwarded-Host` only when asked.
323
+ *
324
+ * Same rule as `getRequestIP`, and the consequence is sharper: a host taken
325
+ * from an untrusted header and used to build an absolute URL is a host-header
326
+ * injection, which turns a password-reset link into a link to the attacker.
327
+ */
328
+ function getRequestHost(options = {}) {
329
+ const request = getRequest();
330
+ if (options.xForwardedHost === true) {
331
+ const forwarded = request.headers.get("x-forwarded-host");
332
+ if (forwarded !== null && forwarded !== "") return forwarded;
333
+ }
334
+ return new URL(request.url).host;
335
+ }
336
+ /** `http` or `https`. `X-Forwarded-Proto` only when asked, for the reason above. */
337
+ function getRequestProtocol(options = {}) {
338
+ const request = getRequest();
339
+ if (options.xForwardedProto === true) {
340
+ const forwarded = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
341
+ if (forwarded !== void 0 && forwarded !== "") return forwarded;
342
+ }
343
+ return new URL(request.url).protocol.replace(":", "");
344
+ }
345
+ /**
346
+ * Mark the draft's response as handed to the server: Solid's
347
+ * `commitResponseStub`. A streamed page goes on rendering after this, and so
348
+ * does a streamed server function, and a header one of them writes now changes
349
+ * nothing the browser receives.
350
+ */
351
+ const markResponseSent = commitResponseStub;
352
+ /**
353
+ * The draft a write goes to, reporting the write when the response has already
354
+ * gone. `api` is the public function the caller called, so the stack the
355
+ * report carries starts at the caller rather than in here.
356
+ */
357
+ function draftFor(api, argument) {
358
+ const draft = context().response;
359
+ if (draft.committed !== true) return draft;
360
+ if (diagnosticsEnabled()) reportLateWrite(api, argument);
361
+ return createResponseStub();
362
+ }
363
+ function reportLateWrite(api, argument) {
364
+ const call = `${api.name}(${argument === void 0 ? "" : JSON.stringify(argument)})`;
365
+ const error = /* @__PURE__ */ new Error(`${call} ran after the response was sent`);
366
+ Error.captureStackTrace(error, api);
367
+ const caller = /^\s*at\s+(.*)$/m.exec(error.stack?.split("\n").slice(1).join("\n") ?? "")?.[1];
368
+ emitDiagnostic({
369
+ code: "LATE_HEADER_WRITE",
370
+ kind: "head",
371
+ severity: "warn",
372
+ message: `\`${call}\` ran ${caller === void 0 ? "" : `at ${caller} `}after the response's status and headers had been sent, so it changed nothing the browser receives. Code runs that late inside a part of the page that renders after the shell (a \`<Loading>\` boundary or a loader the shell does not wait for), or in a streamed server function after its first value. Set the status, headers and cookies while the response is still open: in a \`beforeLoad\`, a loader the route awaits, a route handler, a middleware, or a server function before it returns.`,
373
+ data: {
374
+ call,
375
+ error
376
+ }
377
+ }, null);
378
+ }
379
+ function getResponseHeaders() {
380
+ return context().response.headers;
381
+ }
382
+ function getResponseHeader(name) {
383
+ return context().response.headers.get(name) ?? void 0;
384
+ }
385
+ /**
386
+ * Set a response header. An array APPENDS each value, which is what a header
387
+ * that may legitimately repeat needs.
388
+ */
389
+ function setResponseHeader(name, value) {
390
+ const headers = draftFor(setResponseHeader, name).headers;
391
+ if (typeof value === "string") {
392
+ headers.set(name, value);
393
+ return;
394
+ }
395
+ headers.delete(name);
396
+ for (const one of value) headers.append(name, one);
397
+ }
398
+ /**
399
+ * Add a value to a response header, keeping the ones already there.
400
+ *
401
+ * For a header that is a list: `Vary`, `Link`, `Cache-Control` built up by more
402
+ * than one caller. `setResponseHeader` replaces.
403
+ */
404
+ function appendResponseHeader(name, value) {
405
+ draftFor(appendResponseHeader, name).headers.append(name, value);
406
+ }
407
+ function setResponseHeaders(headers) {
408
+ for (const [name, value] of Object.entries(headers)) setResponseHeader(name, value);
409
+ }
410
+ function removeResponseHeader(name) {
411
+ draftFor(removeResponseHeader, name).headers.delete(name);
412
+ }
413
+ /** Clear the named headers, or every header this request has drafted. */
414
+ function clearResponseHeaders(names) {
415
+ const headers = draftFor(clearResponseHeaders).headers;
416
+ if (names !== void 0) {
417
+ for (const name of names) headers.delete(name);
418
+ return;
419
+ }
420
+ const present = [];
421
+ for (const name of headers.keys()) present.push(name);
422
+ for (const name of present) headers.delete(name);
423
+ }
424
+ function getResponseStatus() {
425
+ return context().response.status ?? 200;
426
+ }
427
+ /**
428
+ * Set the status the framework's own response will carry.
429
+ *
430
+ * It does NOT override a `Response` a handler returns for itself — see
431
+ * `applyResponseDraft`, which says why.
432
+ */
433
+ function setResponseStatus(status, statusText) {
434
+ const draft = draftFor(setResponseStatus, status);
435
+ if (!Number.isInteger(status) || status < 200 || status > 599) throw new RangeError(`[barq] \`setResponseStatus(${status})\` was given a value that is not an HTTP response status. Pass an integer from 200 to 599, such as \`setResponseStatus(404)\`.`);
436
+ draft.status = status;
437
+ if (statusText !== void 0) draft.statusText = statusText;
438
+ }
439
+ /**
440
+ * Every cookie the REQUEST carried, by name.
441
+ *
442
+ * Parsed once and memoised on the context: the header cannot change for the life
443
+ * of the request, and re-splitting it per lookup made three readers three
444
+ * parses. The object is returned as it stands rather than copied, which is the
445
+ * point — copying it per call would put the allocation back.
446
+ */
447
+ function getCookies() {
448
+ const found = context();
449
+ found.cookies ??= parseCookies(found.request.headers.get("cookie"));
450
+ return found.cookies;
451
+ }
452
+ function getCookie(name) {
453
+ return getCookies()[name];
454
+ }
455
+ /**
456
+ * Set a cookie on the response.
457
+ *
458
+ * APPENDS, because several cookies are several `Set-Cookie` lines and a
459
+ * browser keeps only the last of a set. Setting the same NAME twice in one
460
+ * request is the caller's business — the last one wins in the browser, as ever.
461
+ */
462
+ function setCookie(name, value, options) {
463
+ draftFor(setCookie, name).headers.append("set-cookie", serializeCookie(name, value, rooted(options)));
464
+ }
465
+ /**
466
+ * Set a cookie in place of any line this request already drafted for its name.
467
+ *
468
+ * For a cookie one request may write more than once and of which only the last
469
+ * line means anything, which is a session: each of its lines runs to 4 KB, and
470
+ * a proxy that buffers response headers in 4 or 8 KB answers 502 to two of
471
+ * them. `setCookie` appends, which is right for everything else.
472
+ */
473
+ function replaceCookie(name, value, options) {
474
+ const headers = draftFor(replaceCookie, name).headers;
475
+ const line = serializeCookie(name, value, rooted(options));
476
+ const prefix = `${name}=`;
477
+ const kept = headers.getSetCookie().filter((other) => !other.startsWith(prefix));
478
+ headers.delete("set-cookie");
479
+ for (const other of kept) headers.append("set-cookie", other);
480
+ headers.append("set-cookie", line);
481
+ }
482
+ /**
483
+ * The options, with `path: "/"` where the caller chose none.
484
+ *
485
+ * A browser gives a cookie that names no `Path` the directory of the URL that
486
+ * set it (RFC 6265 §5.1.4). For a server function that is `/_barq/fn`, so the
487
+ * cookie would come back on other server functions and on no page at all.
488
+ * `serializeCookie` stays literal; the default belongs where the URL is known
489
+ * to be the wrong scope.
490
+ */
491
+ function rooted(options) {
492
+ return options?.path === void 0 ? {
493
+ ...options,
494
+ path: "/"
495
+ } : options;
496
+ }
497
+ /**
498
+ * Delete a cookie.
499
+ *
500
+ * `path` and `domain` MUST match the ones it was set with, or the browser
501
+ * deletes nothing and keeps the original — silently. They are options here for
502
+ * exactly that reason rather than as decoration. With no `path` it names `/`,
503
+ * which is what `setCookie` gave a cookie that was set with none.
504
+ */
505
+ function deleteCookie(name, options) {
506
+ draftFor(deleteCookie, name).headers.append("set-cookie", deleteCookieLine(name, rooted(options)));
507
+ }
508
+ /**
509
+ * Fold a draft into a response, Solid's fold for `commitEventResponse` without
510
+ * the commit: `foldResponseStub` in `@barqjs/web` says what wins and why.
511
+ *
512
+ * It does NOT override the status of a `Response` a handler returned, because
513
+ * a handler that built a whole response has said what it wants.
514
+ */
515
+ const applyResponseDraft = foldResponseStub;
516
+ /**
517
+ * The status and text a framework-built response should carry.
518
+ *
519
+ * Separate from `applyResponseDraft` because the two answer different
520
+ * questions: this is "what did the handler ask for", used where the framework
521
+ * is deciding the status itself, and that one is "what does a returned response
522
+ * already say", where the handler has decided.
523
+ */
524
+ function draftedStatus(draft, fallback) {
525
+ return {
526
+ status: draft?.status ?? fallback,
527
+ statusText: draft?.statusText
528
+ };
529
+ }
530
+ //#endregion
531
+ //#region src/rate-limit.ts
532
+ /**
533
+ * Rate limiting, as a middleware — so one closure guards a server function and
534
+ * a route handler alike.
535
+ *
536
+ * THE STORE HAS NO DEFAULT, and that is the whole design of this file.
537
+ *
538
+ * An in-memory counter is correct for exactly one process. Behind a load
539
+ * balancer with three instances it permits three times the limit, and behind an
540
+ * autoscaler it permits an unbounded multiple — while passing every test, on
541
+ * every machine, in every CI run. That is the silent failure this codebase
542
+ * refuses: a limiter that reads as working and protects nothing. Requiring the
543
+ * store makes the distributed question unavoidable at the call site, which is
544
+ * the only place it can be answered.
545
+ *
546
+ * `memoryStore()` ships beside it and is named for what it is. Use it for a
547
+ * single instance, and know that is what you have chosen.
548
+ *
549
+ * WHAT THIS IS NOT: a defence against a distributed flood. A limiter in the
550
+ * application has already paid for the TLS handshake, the routing and the
551
+ * middleware above it. It is here to stop credential stuffing, scraping and one
552
+ * client hammering an expensive handler — the things a proxy in front cannot see
553
+ * because they are shaped like ordinary traffic. Volumetric denial of service is
554
+ * the edge's problem and always was.
555
+ */
556
+ /**
557
+ * A store for ONE PROCESS. Named so the choice is visible at the call site.
558
+ *
559
+ * Correct for a single instance and wrong for every other deployment — see the
560
+ * header. It is here because "no store at all" would push everyone to write this
561
+ * same map badly, not because it is the one to reach for.
562
+ *
563
+ * Expired entries are swept by a `hit` rather than on a timer: a timer keeps
564
+ * the process alive on Node and has to be unref'd. A key is one caller and most
565
+ * callers are never seen again (a scan, a client rotating through an IPv6
566
+ * prefix), so an entry dropped only when its own key came back would stay for
567
+ * the life of the process and the map would grow with every address ever seen.
568
+ *
569
+ * The sweep runs at most once per the longest window in use, so an entry that
570
+ * has expired is gone by the second sweep after it was made, and the map holds
571
+ * what the last two such windows saw rather than everything since boot.
572
+ */
573
+ function memoryStore() {
574
+ const windows = /* @__PURE__ */ new Map();
575
+ let longest = 0;
576
+ let sweepAt = 0;
577
+ return { hit(key, windowMs) {
578
+ const now = Date.now();
579
+ if (windowMs > longest) longest = windowMs;
580
+ if (now >= sweepAt) {
581
+ for (const [seen, window] of windows) if (window.resetAt <= now) windows.delete(seen);
582
+ sweepAt = now + longest;
583
+ }
584
+ const found = windows.get(key);
585
+ if (found === void 0 || found.resetAt <= now) {
586
+ const resetAt = now + windowMs;
587
+ windows.set(key, {
588
+ count: 1,
589
+ resetAt
590
+ });
591
+ return {
592
+ count: 1,
593
+ resetAt
594
+ };
595
+ }
596
+ found.count += 1;
597
+ return {
598
+ count: found.count,
599
+ resetAt: found.resetAt
600
+ };
601
+ } };
602
+ }
603
+ /**
604
+ * Key a limit by client address.
605
+ *
606
+ * `xForwardedFor` IS OFF BY DEFAULT and turning it on is a claim about the
607
+ * deployment: `X-Forwarded-For` is a header a CLIENT can send, so trusting it
608
+ * where no proxy overwrites it lets any caller pick their own bucket and the
609
+ * limit stops existing. See `getRequestIP`.
610
+ *
611
+ * `true` reads the LEFTMOST entry, which is the client only when the edge proxy
612
+ * overwrites the header. Behind a proxy that appends, pass
613
+ * `{ trustedProxies: n }` for the `n` proxies you run: it reads the entry the
614
+ * outermost of them wrote and ignores anything a caller put in front of it.
615
+ *
616
+ * A request with no address at all keys as `"unknown"`, which pools every such
617
+ * caller into one bucket — strict rather than exempt, because the alternative is
618
+ * a bucket an attacker can opt into by arranging to have no address.
619
+ */
620
+ function byIP(options = {}) {
621
+ assertForwardedForTrust(options.xForwardedFor);
622
+ return () => getRequestIP(options) ?? "unknown";
623
+ }
624
+ function tooMany(info) {
625
+ const seconds = Math.max(1, Math.ceil((info.resetAt - Date.now()) / 1e3));
626
+ return new Response("too many requests", {
627
+ status: 429,
628
+ headers: {
629
+ "retry-after": String(seconds),
630
+ "ratelimit-limit": String(info.limit),
631
+ "ratelimit-remaining": "0",
632
+ "ratelimit-reset": String(seconds)
633
+ }
634
+ });
635
+ }
636
+ /**
637
+ * The middleware.
638
+ *
639
+ * It runs BEFORE the handler and before validation, which is the whole point:
640
+ * refusing after the body has been parsed is a refusal that already did the
641
+ * work. That ordering is `serverRpc`'s and the route dispatch's, and it is why
642
+ * this is a middleware rather than something a handler calls.
643
+ *
644
+ * A STORE THAT THROWS FAILS OPEN, deliberately and loudly. If Redis is down,
645
+ * refusing every request turns a limiter into the outage — so the request
646
+ * proceeds and the failure is reported. That is the right trade for a limiter
647
+ * and the wrong one for an authorization check, which is why this is not one.
648
+ */
649
+ function rateLimit(options) {
650
+ const { limit, windowMs, key, store, onLimit = tooMany } = options;
651
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`[barq] \`rateLimit({ limit })\` must be a positive integer, and it is ${limit}. Pass how many requests one key may make per window, such as \`limit: 10\`.`);
652
+ if (!Number.isFinite(windowMs) || windowMs <= 0) throw new RangeError(`[barq] \`rateLimit({ windowMs })\` must be a positive number of milliseconds, and it is ${windowMs}. Pass the window length, such as \`windowMs: 60_000\`.`);
653
+ return async (next) => {
654
+ let info;
655
+ try {
656
+ const bucket = await key();
657
+ if (bucket === null) return next();
658
+ info = await store.hit(bucket, windowMs);
659
+ } catch (error) {
660
+ console.error("[barq] The rate-limit `store` or `key` threw, so this request was let through without being counted. The error:", error);
661
+ return next();
662
+ }
663
+ if (info.count > limit) throw onLimit({
664
+ ...info,
665
+ limit
666
+ });
667
+ return next();
668
+ };
669
+ }
670
+ //#endregion
671
+ //#region src/session.ts
672
+ /**
673
+ * Sealed-cookie sessions, on WebCrypto and nothing else.
674
+ *
675
+ * The session lives in the cookie, encrypted and authenticated, so there is no
676
+ * store to run and no sticky routing to arrange. That is h3's design and
677
+ * therefore TanStack's, and the interface
678
+ * below is theirs — `{ id, data, update, clear }` from `useSession({ password
679
+ * })` — so the shape a reader already knows is the shape here.
680
+ *
681
+ * THE SEALING IS NOT THEIRS, and the divergence is deliberate. h3 uses iron,
682
+ * which is AES-256-CBC for confidentiality plus a separate HMAC-SHA256 for
683
+ * integrity, composed by hand. barq uses AES-GCM, which is AEAD: one primitive,
684
+ * authenticated by construction, with no encrypt-then-MAC composition to get
685
+ * wrong and no separate integrity key to derive. It is in WebCrypto, which Node,
686
+ * Bun, Deno and workerd all have, so it costs no dependency. The consequence is
687
+ * stated rather than hidden: a cookie sealed by h3 does not open here and one
688
+ * sealed here does not open there.
689
+ *
690
+ * WHAT A SEALED COOKIE IS AND IS NOT. It is tamper-proof and unreadable by the
691
+ * client. It is NOT revocable — a cookie already issued stays valid until it
692
+ * expires, because nothing on the server is consulted to open it. That is the
693
+ * trade the whole design makes, and an application that needs revocation needs a
694
+ * store; `maxAge` bounds the damage and is enforced on unseal, not merely on the
695
+ * cookie, so a client that keeps replaying an expired token gets nothing.
696
+ */
697
+ const DEFAULT_NAME = "barq-session";
698
+ const DEFAULT_MAX_AGE = 604800;
699
+ /** Below this a password is not a key, whatever the KDF does with it. */
700
+ const MINIMUM_PASSWORD = 32;
701
+ /** Recognises our own envelope, and refuses another version rather than guessing. */
702
+ const VERSION = "b2";
703
+ /**
704
+ * The envelope that authenticates no cookie name. Opened, never written.
705
+ *
706
+ * Refusing it would sign every visitor out on the deploy that stopped sealing
707
+ * it, and the price of not doing that is stated: a `b1` value opens under ANY
708
+ * cookie name sharing the password until its sealed timestamp passes `maxAge`.
709
+ */
710
+ const NAMELESS_VERSION = "b1";
711
+ /** Leads the additional data, so another layout of it is never read as this one. */
712
+ const NAME_BINDING = 2;
713
+ const IV_BYTES = 12;
714
+ const SALT_BYTES = 16;
715
+ /** Domain separation for the KDF — see `deriveKey`. */
716
+ const HKDF_INFO = new TextEncoder().encode("barq.session.v1");
717
+ /**
718
+ * What a browser will actually store.
719
+ *
720
+ * RFC 6265 §6.1 requires at least 4096 bytes per cookie, and every browser
721
+ * treats that as the limit — over it the cookie is DROPPED, silently, which
722
+ * looks exactly like a user who is not signed in. A session that quietly stops
723
+ * working once a field grows is the worst failure this file could have, so the
724
+ * seal refuses instead and says what to do.
725
+ */
726
+ const MAX_COOKIE_BYTES = 4096;
727
+ function base64url(bytes) {
728
+ let binary = "";
729
+ for (const byte of bytes) binary += String.fromCharCode(byte);
730
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
731
+ }
732
+ function fromBase64url(value) {
733
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/");
734
+ const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, "="));
735
+ const bytes = new Uint8Array(binary.length);
736
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
737
+ return bytes;
738
+ }
739
+ /**
740
+ * The key, derived per SALT rather than used raw.
741
+ *
742
+ * HKDF AND NOT PBKDF2, and the reason is correctness AND a denial of service.
743
+ *
744
+ * PBKDF2 exists to STRETCH a low-entropy secret — a human password — so that
745
+ * guessing it costs an attacker real time. This input is not that: `password` is
746
+ * refused below 32 characters and is documented as a key. Stretching something
747
+ * already high-entropy buys nothing, and HKDF is the KDF for exactly this case.
748
+ *
749
+ * The cost of getting it wrong was MEASURED on this machine: PBKDF2 at 100,000
750
+ * iterations is 7.93 ms and HKDF is 0.014 ms — 566x — per REQUEST, on every
751
+ * request that touches a session. Worse, it is per request an ATTACKER makes:
752
+ * the salt comes out of the cookie, so an unauthenticated client sending garbage
753
+ * cookies chooses how much CPU each packet costs. Eight milliseconds a packet is
754
+ * an amplifier, and HKDF removes it rather than bounding it.
755
+ *
756
+ * A fresh salt per seal still keeps two seals of the same data under the same
757
+ * password from sharing a key, so the ciphertexts stay incomparable.
758
+ */
759
+ async function deriveKey(password, salt) {
760
+ const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "HKDF", false, ["deriveKey"]);
761
+ return crypto.subtle.deriveKey({
762
+ name: "HKDF",
763
+ salt,
764
+ info: HKDF_INFO,
765
+ hash: "SHA-256"
766
+ }, material, {
767
+ name: "AES-GCM",
768
+ length: 256
769
+ }, false, ["encrypt", "decrypt"]);
770
+ }
771
+ /**
772
+ * Keys this process has derived AND seen authenticate, by password, then salt.
773
+ *
774
+ * A signed-in visitor sends one cookie on every request, so its salt and its
775
+ * key repeat. WebCrypto answers on another thread, and measured on this machine
776
+ * the derivation is 42 us of the 73 us an unseal costs; held, a repeat visit
777
+ * pays for the decryption alone.
778
+ *
779
+ * Only a key that OPENED something is kept, or one this process sealed with. A
780
+ * caller sending garbage cookies therefore adds nothing here and evicts no one,
781
+ * which is what would otherwise make a cache of attacker-chosen salts a way to
782
+ * push real visitors out of it.
783
+ */
784
+ const DERIVED = /* @__PURE__ */ new Map();
785
+ /** Per password. The oldest goes first, and a key that is used is the newest. */
786
+ const DERIVED_KEYS = 1e3;
787
+ function keep(password, salt, key) {
788
+ let keys = DERIVED.get(password);
789
+ if (keys === void 0) {
790
+ keys = /* @__PURE__ */ new Map();
791
+ DERIVED.set(password, keys);
792
+ }
793
+ keys.delete(salt);
794
+ keys.set(salt, key);
795
+ if (keys.size <= DERIVED_KEYS) return;
796
+ const oldest = keys.keys().next().value;
797
+ if (oldest !== void 0) keys.delete(oldest);
798
+ }
799
+ /**
800
+ * What the tag covers beside the ciphertext: the cookie the session was sealed
801
+ * FOR.
802
+ *
803
+ * One password commonly seals more than one cookie, and a tag that covers the
804
+ * payload alone makes the value issued as `barq-session` a valid
805
+ * `barq-session-admin` for anyone who renames it.
806
+ */
807
+ function nameBinding(config) {
808
+ const name = new TextEncoder().encode(config.name ?? DEFAULT_NAME);
809
+ const binding = new Uint8Array(name.length + 1);
810
+ binding[0] = NAME_BINDING;
811
+ binding.set(name, 1);
812
+ return binding;
813
+ }
814
+ function assertPassword(password) {
815
+ if (password.length < MINIMUM_PASSWORD) throw new TypeError(`[barq] A session \`password\` must be at least ${MINIMUM_PASSWORD} characters, and this one is ${password.length}. It is the key that encrypts the cookie, so a short one can be guessed. Generate one with \`crypto.randomUUID() + crypto.randomUUID()\` and read it from an environment variable.`);
816
+ }
817
+ /** Encrypt and sign a session. Exported for code that seals outside a request. */
818
+ async function sealSession(config, session) {
819
+ assertPassword(config.password);
820
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
821
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
822
+ const key = await deriveKey(config.password, salt);
823
+ const plaintext = new TextEncoder().encode(JSON.stringify(session));
824
+ const salted = base64url(salt);
825
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({
826
+ name: "AES-GCM",
827
+ iv,
828
+ additionalData: nameBinding(config)
829
+ }, key, plaintext));
830
+ const value = [
831
+ VERSION,
832
+ salted,
833
+ base64url(iv),
834
+ base64url(sealed)
835
+ ].join(".");
836
+ const size = (config.name ?? DEFAULT_NAME).length + value.length;
837
+ if (size > MAX_COOKIE_BYTES) throw new RangeError(`[barq] This session is ${size} bytes once encrypted, counting the cookie name, and a browser drops any cookie over ${MAX_COOKIE_BYTES} bytes without an error. The user would appear signed out. Keep only an id in the session and the rest in a store on the server.`);
838
+ keep(config.password, salted, key);
839
+ return value;
840
+ }
841
+ /**
842
+ * Decrypt and verify, or `null`.
843
+ *
844
+ * `null` for EVERY failure — a wrong password, a tampered ciphertext, an expired
845
+ * timestamp, a envelope from a future version — and never a throw. A session
846
+ * that will not open is not an error the request should fail on; it is a visitor
847
+ * who is not signed in, and the two must be indistinguishable to the caller so
848
+ * that a forged cookie cannot be told apart from an absent one.
849
+ */
850
+ async function unsealSession(config, sealed) {
851
+ assertPassword(config.password);
852
+ const parts = sealed.split(".");
853
+ if (parts.length !== 4) return null;
854
+ const bound = parts[0] === VERSION;
855
+ if (!bound && parts[0] !== NAMELESS_VERSION) return null;
856
+ try {
857
+ const key = DERIVED.get(config.password)?.get(parts[1]) ?? await deriveKey(config.password, fromBase64url(parts[1]));
858
+ const plaintext = await crypto.subtle.decrypt(bound ? {
859
+ name: "AES-GCM",
860
+ iv: fromBase64url(parts[2]),
861
+ additionalData: nameBinding(config)
862
+ } : {
863
+ name: "AES-GCM",
864
+ iv: fromBase64url(parts[2])
865
+ }, key, fromBase64url(parts[3]));
866
+ keep(config.password, parts[1], key);
867
+ const session = JSON.parse(new TextDecoder().decode(plaintext));
868
+ if (typeof session.id !== "string" || typeof session.createdAt !== "number") return null;
869
+ const maxAge = config.maxAge ?? DEFAULT_MAX_AGE;
870
+ if (Date.now() - session.createdAt > maxAge * 1e3) return null;
871
+ if (config.isRevoked !== void 0 && await config.isRevoked(session.id)) return null;
872
+ return session;
873
+ } catch {
874
+ return null;
875
+ }
876
+ }
877
+ function cookieOptions(config) {
878
+ return {
879
+ httpOnly: true,
880
+ secure: true,
881
+ sameSite: "lax",
882
+ path: "/",
883
+ maxAge: config.maxAge ?? DEFAULT_MAX_AGE,
884
+ ...config.cookie,
885
+ encode: (value) => value
886
+ };
887
+ }
888
+ /**
889
+ * The session for this request, opening the cookie if there is one.
890
+ *
891
+ * Always answers a manager, never `null`: a visitor with no session has an empty
892
+ * one, which is the same thing from the application's side and removes the
893
+ * branch that is easy to get backwards.
894
+ *
895
+ * NOTHING IS WRITTEN until `update` is called. Reading a session must not
896
+ * re-issue its cookie, or every page render would refresh an expiry the user did
897
+ * not earn — and on a page that also sets `Cache-Control: public` that
898
+ * `Set-Cookie` is a cache poisoning waiting to happen.
899
+ */
900
+ async function useSession(config) {
901
+ assertPassword(config.password);
902
+ const name = config.name ?? DEFAULT_NAME;
903
+ getRequest();
904
+ const sessions = openSessions();
905
+ let opening = sessions.get(name);
906
+ if (opening === void 0) {
907
+ opening = open(config, getCookie(name));
908
+ sessions.set(name, opening);
909
+ }
910
+ const session = await opening;
911
+ const write = (change) => {
912
+ const written = session.writing.then(async () => {
913
+ session.current = await change(session.current);
914
+ return manage();
915
+ });
916
+ session.writing = written.catch(() => void 0);
917
+ return written;
918
+ };
919
+ const manage = () => ({
920
+ id: session.current.id,
921
+ createdAt: session.current.createdAt,
922
+ data: session.current.data,
923
+ update: (patch) => write(async (current) => {
924
+ const next = typeof patch === "function" ? patch(current.data) : patch;
925
+ const merged = {
926
+ ...current,
927
+ data: {
928
+ ...current.data,
929
+ ...next
930
+ }
931
+ };
932
+ replaceCookie(name, await sealSession(config, merged), cookieOptions(config));
933
+ return merged;
934
+ }),
935
+ clear: () => write(async () => {
936
+ replaceCookie(name, "", {
937
+ ...cookieOptions(config),
938
+ maxAge: 0,
939
+ expires: /* @__PURE__ */ new Date(0)
940
+ });
941
+ return {
942
+ id: crypto.randomUUID(),
943
+ createdAt: Date.now(),
944
+ data: {}
945
+ };
946
+ })
947
+ });
948
+ return manage();
949
+ }
950
+ async function open(config, cookie) {
951
+ return {
952
+ current: (cookie === void 0 ? null : await unsealSession(config, cookie)) ?? {
953
+ id: crypto.randomUUID(),
954
+ createdAt: Date.now(),
955
+ data: {}
956
+ },
957
+ writing: Promise.resolve()
958
+ };
959
+ }
960
+ /** The session's data, for code that only reads. */
961
+ async function getSession(config) {
962
+ const manager = await useSession(config);
963
+ return {
964
+ id: manager.id,
965
+ createdAt: manager.createdAt,
966
+ data: manager.data
967
+ };
968
+ }
969
+ /** Merge into the session and re-seal it. */
970
+ async function updateSession(config, patch) {
971
+ return (await useSession(config)).update(patch);
972
+ }
973
+ /** Drop the session and expire its cookie. */
974
+ async function clearSession(config) {
975
+ await (await useSession(config)).clear();
976
+ }
977
+ //#endregion
978
+ //#region src/timing.ts
979
+ function serverTiming() {
980
+ const entries = [];
981
+ let from = performance.now();
982
+ return {
983
+ phase(name, description) {
984
+ const now = performance.now();
985
+ entries.push(`${name};dur=${(now - from).toFixed(1)};desc=${JSON.stringify(description)}`);
986
+ from = now;
987
+ },
988
+ header: () => entries.join(", ")
989
+ };
990
+ }
991
+ //#endregion
992
+ //#region src/index.ts
993
+ /** TanStack's `json`: a JSON `Response`, which a handler returns as its answer. */
994
+ function json(payload, init) {
995
+ return Response.json(payload, init);
996
+ }
997
+ async function checkInput(built, raw, chainValidates = false) {
998
+ if (built.validator === null) {
999
+ if (raw !== void 0 && !chainValidates) throw new UncheckedInputError();
1000
+ return raw;
1001
+ }
1002
+ return applyValidator(built.validator, raw);
1003
+ }
1004
+ /**
1005
+ * Author a server function. The value this returns is replaced by the compiler
1006
+ * on both sides, so what it does when compiled by nothing is only the
1007
+ * uncompiled-development path: it runs the handler in-process.
1008
+ */
1009
+ function createServerFn(options = {}) {
1010
+ const method = options.method ?? "GET";
1011
+ if (method !== "POST" && method !== "GET") throw new TypeError(`[barq] \`createServerFn({ method: ${JSON.stringify(method)} })\` is not supported: a server function answers GET or POST. Use a route's \`server.handlers\` for any other method.`);
1012
+ return builderAt({
1013
+ validator: null,
1014
+ middleware: [],
1015
+ method
1016
+ });
1017
+ }
1018
+ /**
1019
+ * A NEW BUILDER PER STEP, as `createMiddleware` is: one that mutated a shared
1020
+ * record would let a base kept in a variable and finished twice hand the first
1021
+ * function the second one's handler, validator and chain.
1022
+ */
1023
+ function builderAt(staged) {
1024
+ function validated(schema) {
1025
+ return builderAt({
1026
+ ...staged,
1027
+ validator: toValidator(schema)
1028
+ });
1029
+ }
1030
+ return {
1031
+ middleware: (chain) => builderAt({
1032
+ ...staged,
1033
+ middleware: [...staged.middleware, ...inlineServerFns(chain)]
1034
+ }),
1035
+ validator: validated,
1036
+ inputValidator: validated,
1037
+ handler: (fn) => serverRpc(staged.method === "GET" ? {
1038
+ id: "",
1039
+ method: "GET"
1040
+ } : { id: "" }, {
1041
+ validator: staged.validator,
1042
+ middleware: staged.middleware,
1043
+ handler: fn
1044
+ })
1045
+ };
1046
+ }
1047
+ /**
1048
+ * The server half. The compiler emits this in a module compiled for the server,
1049
+ * with the real handler and the id it assigned.
1050
+ *
1051
+ * `In` is what a caller passes and `Data` what the handler is handed; the
1052
+ * validator is what turns one into the other, at runtime.
1053
+ */
1054
+ function serverRpc(meta, built) {
1055
+ let composed = null;
1056
+ const composition = () => {
1057
+ const global = startOptions().functionMiddleware;
1058
+ if (composed !== null && composed.from === global) return composed;
1059
+ const chain = flattenMiddleware([...global ?? [], ...built.middleware]);
1060
+ composed = {
1061
+ from: global,
1062
+ chain,
1063
+ validates: chain.some((step) => isBuiltMiddleware(step) && step.options.validator !== void 0)
1064
+ };
1065
+ return composed;
1066
+ };
1067
+ const call = async (options, clientContext) => {
1068
+ const input = dataOf(options);
1069
+ const { chain, validates: chainValidates } = composition();
1070
+ const context = { ...getGlobalStartContext() };
1071
+ const sendContext = {};
1072
+ const signal = callOptionsOf(options)?.signal ?? peekRequest()?.signal ?? new AbortController().signal;
1073
+ const method = meta.method ?? "POST";
1074
+ const result = await runMiddleware(chain, "server", {
1075
+ data: input,
1076
+ meta,
1077
+ method,
1078
+ signal,
1079
+ context,
1080
+ clientContext,
1081
+ sendContext,
1082
+ run: async (data) => built.handler({
1083
+ data: await checkInput(built, data, chainValidates),
1084
+ context,
1085
+ signal,
1086
+ method,
1087
+ serverFnMeta: { id: meta.id }
1088
+ })
1089
+ });
1090
+ offerSendContext(sendContext);
1091
+ if (result instanceof ReadableStream) return valuesOf(result);
1092
+ return asFrame(meta.id, input, result);
1093
+ };
1094
+ const fn = Object.assign(call, {
1095
+ [SERVER_FN]: true,
1096
+ [SERVER_FN_CHAIN]: built.middleware,
1097
+ meta,
1098
+ serverFnMeta: meta,
1099
+ method: meta.method ?? "POST",
1100
+ built,
1101
+ url: ""
1102
+ });
1103
+ Object.defineProperty(fn, "url", {
1104
+ enumerable: true,
1105
+ get: () => urlOf(meta.id)
1106
+ });
1107
+ return fn;
1108
+ }
1109
+ /**
1110
+ * The middleware chain a server function carries, by REFERENCE.
1111
+ *
1112
+ * `serverRpc` attaches `built` to the function object, so the chain is the real
1113
+ * array of closures rather than something re-derived. That matters: a build
1114
+ * cannot read a chain out of source. `.middleware([m])`, `.middleware([...c])`
1115
+ * and `.middleware(c.filter(Boolean))` are all runtime expressions, and
1116
+ * `Middleware` is an anonymous closure with no build-visible identity — so the
1117
+ * only sound comparison is `===` against the same closure the route declared.
1118
+ *
1119
+ * Empty for a client stub, which carries no chain because it carries no handler.
1120
+ */
1121
+ function middlewareOf(fn) {
1122
+ return fn.built?.middleware ?? [];
1123
+ }
1124
+ /** A stream's values, releasing it when the reader leaves early. */
1125
+ async function* valuesOf(stream) {
1126
+ const reader = stream.getReader();
1127
+ try {
1128
+ for (;;) {
1129
+ const { done, value } = await reader.read();
1130
+ if (done) return;
1131
+ yield value;
1132
+ }
1133
+ } finally {
1134
+ reader.cancel().catch(() => {});
1135
+ }
1136
+ }
1137
+ //#endregion
1138
+ export { serializeCookie as $, getRequestHost as A, markResponseSent as B, draftedStatus as C, getRequest as D, getGlobalStartContext as E, getResponseHeaders as F, setRequestMiddlewareContext as G, peekResponseDraft as H, getResponseStatus as I, setResponseStatus as J, setResponseHeader as K, installCssSink as L, getRequestProtocol as M, getRequestUrl as N, getRequestHeader as O, getResponseHeader as P, parseCookies as Q, invalidateFrames as R, deleteCookie as S, getCookies as T, removeResponseHeader as U, peekRequest as V, setCookie as W, withRequest as X, takeSendContext as Y, deleteCookieLine as Z, appendResponseHeader as _, middlewareOf as a, collectRequestCss as b, clearSession as c, unsealSession as d, updateSession as f, rateLimit as g, memoryStore as h, json as i, getRequestIP as j, getRequestHeaders as k, getSession as l, byIP as m, createSerializationAdapter as n, serverRpc as o, useSession as p, setResponseHeaders as q, createServerFn as r, serverTiming as s, checkInput as t, sealSession as u, applyResponseDraft as v, getCookie as w, createResponseDraft as x, clearResponseHeaders as y, invalidatedFrames as z };
1139
+
1140
+ //# sourceMappingURL=src-ChnB_xug.js.map