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