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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
package/dist/serve.js ADDED
@@ -0,0 +1,221 @@
1
+ import { serve } from "srvx";
2
+ import { n as handleServerFn } from "./server-DG6jb_NA.js";
3
+ // src/static.ts
4
+ /** Where the build writes it, inside the client output directory. */
5
+ const ASSET_MANIFEST_FILE = "barq-assets.json";
6
+ /** A hashed name never changes its bytes, so a year is the conventional forever. */
7
+ const HASHED_MAX_AGE = 31536e3;
8
+ /**
9
+ * Headers that describe the bytes on the wire rather than the page.
10
+ *
11
+ * `srvx/static` computes them for the response it actually sends: compressed
12
+ * or not, whole or a 304. The ones a page was RENDERED with describe an
13
+ * uncompressed body in a build's memory.
14
+ */
15
+ const REPRESENTATION = /* @__PURE__ */ new Set([
16
+ "accept-ranges",
17
+ "content-encoding",
18
+ "content-length",
19
+ "content-range",
20
+ "etag",
21
+ "last-modified"
22
+ ]);
23
+ /**
24
+ * Serve `dist/client` for the paths the build says are there.
25
+ *
26
+ * Returns a `srvx` middleware, so it composes with anything else a project
27
+ * passes in `ServerOptions.middleware` and runs before the page handler.
28
+ *
29
+ * INITIALISATION IS LAZY AND HAPPENS ONCE. `node:fs` and `srvx/static` are
30
+ * imported inside it rather than at module scope, because `@barqjs/start/serve`
31
+ * resolves on workerd too and neither exists there. After the first request the
32
+ * fast path is synchronous — the `await` is not paid per request.
33
+ */
34
+ function assetMiddleware(options = {}) {
35
+ let ready;
36
+ let loading;
37
+ const answer = (loaded, request, next) => {
38
+ if (loaded === null) return next();
39
+ if (request.method !== "GET" && request.method !== "HEAD") return next();
40
+ let { pathname } = new loaded.url(request.url);
41
+ if (pathname.includes("%")) try {
42
+ pathname = decodeURI(pathname);
43
+ } catch {
44
+ return next();
45
+ }
46
+ const page = loaded.manifest.pages[pathname];
47
+ if (page !== void 0) return loaded.servePage(page, request);
48
+ if (!loaded.files.has(pathname)) return next();
49
+ return loaded.serveFile(pathname, request, next);
50
+ };
51
+ return (request, next) => {
52
+ if (ready !== void 0) return answer(ready, request, next);
53
+ loading ??= load(options).then((loaded) => {
54
+ ready = loaded;
55
+ });
56
+ return loading.then(() => answer(ready ?? null, request, next));
57
+ };
58
+ }
59
+ /**
60
+ * The request `srvx/static` would have been sent for this FILE.
61
+ *
62
+ * It finds a file by the request's path, and two things here are found by the
63
+ * manifest instead: a page, whose path is `/about` and whose file is
64
+ * `about/index.html`, and anything under a `base`, which is in every request
65
+ * path and in no file name. `encodeURI` because `decodeURI` is what it opens
66
+ * the file by.
67
+ */
68
+ function requestFor(file, request) {
69
+ return new Request(`http://asset/${encodeURI(file)}`, {
70
+ method: request.method,
71
+ headers: request.headers
72
+ });
73
+ }
74
+ async function load(options) {
75
+ const [{ readFile }, { staticMiddleware }, { FastURL }, path, { fileURLToPath }] = await Promise.all([
76
+ import("node:fs/promises"),
77
+ import("srvx/static"),
78
+ import("srvx"),
79
+ import("node:path"),
80
+ import("node:url")
81
+ ]);
82
+ const dir = options.dir instanceof URL ? fileURLToPath(options.dir) : options.dir ?? "dist/client";
83
+ let manifest = options.manifest;
84
+ if (manifest === void 0) try {
85
+ manifest = JSON.parse(await readFile(path.join(dir, ASSET_MANIFEST_FILE), "utf8"));
86
+ } catch {
87
+ return null;
88
+ }
89
+ const hashed = manifest.hashed === void 0 ? null : new Set(manifest.hashed);
90
+ const revalidated = staticMiddleware({ dir });
91
+ const lifetime = hashed === null ? options.maxAge : options.maxAge ?? HASHED_MAX_AGE;
92
+ const longLived = lifetime === void 0 ? revalidated : staticMiddleware({
93
+ dir,
94
+ maxAge: lifetime,
95
+ immutable: options.immutable ?? hashed !== null
96
+ });
97
+ const prefix = manifest.base ?? "";
98
+ /** The page's bytes with nothing negotiated, for what `srvx/static` will not answer. */
99
+ const whole = async (page) => {
100
+ const body = await readFile(path.join(dir, page.file));
101
+ const headers = new Headers(page.headers);
102
+ if (!headers.has("content-type")) headers.set("content-type", "text/html; charset=utf-8");
103
+ return new Response(body, {
104
+ status: page.status,
105
+ headers
106
+ });
107
+ };
108
+ const declined = () => new Response(null, { status: 404 });
109
+ return {
110
+ manifest,
111
+ files: new Set(manifest.files),
112
+ url: FastURL,
113
+ /**
114
+ * A prerendered page, with the STATUS and HEADERS it was rendered as.
115
+ *
116
+ * A 200 goes through `staticMiddleware` under its file's name, so it gets
117
+ * the validator, the 304 and the encoding a hashed chunk gets. Anything
118
+ * else is read directly: `staticMiddleware` has no way to answer but 200,
119
+ * and a conditional request must not turn a 404 page into a 304.
120
+ */
121
+ servePage: async (page, request) => {
122
+ if (page.status !== 200) return whole(page);
123
+ let found = true;
124
+ const served = await revalidated(requestFor(page.file, request), () => {
125
+ found = false;
126
+ return declined();
127
+ });
128
+ if (!found) return whole(page);
129
+ for (const name in page.headers) {
130
+ const value = page.headers[name];
131
+ if (value === void 0) continue;
132
+ const key = name.toLowerCase();
133
+ if (REPRESENTATION.has(key)) continue;
134
+ if (key === "vary") served.headers.append(key, value);
135
+ else served.headers.set(key, value);
136
+ }
137
+ return served;
138
+ },
139
+ serveFile: (pathname, request, next) => {
140
+ const serve = hashed === null || hashed.has(pathname) ? longLived : revalidated;
141
+ return prefix === "" ? serve(request, next) : serve(requestFor(pathname.slice(prefix.length + 1), request), next);
142
+ }
143
+ };
144
+ }
145
+ // src/serve.ts
146
+ /**
147
+ * The production entry — runtime-agnostic.
148
+ *
149
+ * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,
150
+ * `node`, and a generic default), so one entry serves Node, Deno, Bun and
151
+ * Cloudflare without a per-runtime adapter here. The handler below is an
152
+ * ordinary `Request -> Response` function, which is the only shape all of them
153
+ * agree on.
154
+ *
155
+ * The dev half is deliberately NOT this: Vite's middleware pipeline is
156
+ * Connect-shaped and hands over a Node request/response pair, so `vite.ts`
157
+ * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.
158
+ */
159
+ /**
160
+ * One request, in the order the checks have to happen.
161
+ *
162
+ * Server functions are matched FIRST. Their URL is reserved, so a page handler
163
+ * that also matched it would be shadowing an endpoint rather than serving a
164
+ * page — and the failure that produces is a mutation quietly answered with
165
+ * HTML.
166
+ */
167
+ function createFetchHandler(options = {}) {
168
+ const page = options.fetch ?? (() => new Response("not found", { status: 404 }));
169
+ const document = options.spa;
170
+ let body;
171
+ const spaDocument = async (path, missing) => {
172
+ body ??= import("node:fs/promises").then((fs) => fs.readFile(path, "utf8"));
173
+ try {
174
+ return new Response(await body, { headers: { "content-type": "text/html; charset=utf-8" } });
175
+ } catch {
176
+ body = void 0;
177
+ return missing;
178
+ }
179
+ };
180
+ return async (request) => {
181
+ const answered = await handleServerFn(request, options);
182
+ if (answered !== null) return answered;
183
+ const response = await page(request);
184
+ if (document === void 0 || response.status !== 404) return response;
185
+ if (request.method !== "GET" && request.method !== "HEAD") return response;
186
+ if (!(request.headers.get("accept") ?? "").includes("text/html")) return response;
187
+ return spaDocument(document, response);
188
+ };
189
+ }
190
+ /**
191
+ * What a caller is told when something threw: that it failed, and nothing else.
192
+ *
193
+ * Installed because a runtime's own answer is not that. Bun outside
194
+ * `NODE_ENV=production` answers with the message, the stack and the source
195
+ * around the throw, and a message can name a table, a column or a path. The
196
+ * error goes to the log, where the operator is.
197
+ */
198
+ function failed(error) {
199
+ console.error(error);
200
+ return new Response("internal server error", { status: 500 });
201
+ }
202
+ /**
203
+ * Serve on whatever runtime this is.
204
+ *
205
+ * Mount the generated manifest before calling this — importing
206
+ * `virtual:barq-server-fns` is what puts the ids in the registry, and without
207
+ * it every call is a 404.
208
+ */
209
+ function serveBarq(options = {}) {
210
+ const { fetch: _page, allowedOrigins: _origins, maxBodySize: _body, maxFormSize: _form, reachable: _reachable, static: assets, spa: _spa, middleware, ...rest } = options;
211
+ const chain = assets === void 0 || assets === false ? middleware : [assetMiddleware(assets === true ? {} : assets), ...middleware ?? []];
212
+ return serve({
213
+ ...rest,
214
+ error: rest.error ?? failed,
215
+ middleware: chain,
216
+ fetch: createFetchHandler(options)
217
+ });
218
+ }
219
+ export { ASSET_MANIFEST_FILE, assetMiddleware, createFetchHandler, serveBarq };
220
+
221
+ //# sourceMappingURL=serve.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.js","names":[],"sources":["../src/static.ts","../src/serve.ts"],"sourcesContent":["/**\n * Serving the build's own files, with the lookup the BUILD already knows.\n *\n * A production request is overwhelmingly a MISS: an SSR page asks this layer\n * about a path that is not a file, and every static server that answers by\n * touching the filesystem pays two syscalls to say \"no\". Measured on this\n * machine by `packages/benchmark/src/static-lookup.ts`, on kitchen-sink's build:\n *\n * MISS existsSync + statSync 1.2634 us this manifest 0.2297 us\n *\n * So the manifest is a NEGATIVE index first and foremost. On a miss nothing\n * touches the disk; on a hit the work is handed to `srvx/static`, which already\n * does compression, precompressed variants, `ETag`, `Last-Modified`, ranges,\n * dotfile rules and symlink containment in 798 lines that barq should not\n * reimplement.\n *\n * WHAT THE MANIFEST CARRIES AND WHY. Not `type`, `size` or `etag`: those are\n * derivable from the file and a copy of them is a second source of truth that\n * goes stale against the bytes. What it carries is exactly the two things the\n * filesystem cannot answer — which request paths exist, and what STATUS and\n * HEADERS a prerendered page was rendered with. That second one was being\n * dropped: `PrerenderedPage` has recorded `status` and `headers` all along, and\n * nothing persisted them, so a prerendered 404 page was served as 200.\n */\n\nimport type { ServerMiddleware, ServerRequest } from \"srvx\";\n\n/** Where the build writes it, inside the client output directory. */\nexport const ASSET_MANIFEST_FILE = \"barq-assets.json\";\n\n/** A page the prerenderer wrote, and the response it was rendered as. */\nexport interface PrerenderedAsset {\n /** Relative to the client output directory. */\n readonly file: string;\n readonly status: number;\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nexport interface AssetManifest {\n /** Request path -> the prerendered page written for it. */\n readonly pages: Readonly<Record<string, PrerenderedAsset>>;\n /** Every other servable path, as request paths. */\n readonly files: readonly string[];\n /**\n * The members of `files` whose NAME changes when their bytes do.\n *\n * The build knows and a directory listing cannot say: a chunk it emitted is\n * `app-8f1c2a.js`, and `robots.txt` copied out of `public/` sits beside it\n * under a name the next deploy reuses. Only the first may be cached without\n * asking again.\n */\n readonly hashed?: readonly string[];\n /**\n * What every request path here starts with and no file on disk does: Vite's\n * `base`, without its trailing slash. Absent for a site served from `/`.\n */\n readonly base?: string;\n}\n\nexport interface StaticOptions {\n /**\n * The client output directory. Default `dist/client`.\n *\n * A `file:` URL is read as one, which is how an entry names a directory beside\n * itself: `new URL(\"../client\", import.meta.url)`. Its `.pathname` is not a\n * path, since a space in it is still `%20`.\n */\n readonly dir?: string | URL;\n /**\n * The manifest. Read from `<dir>/barq-assets.json` when omitted.\n *\n * Passing one is how a runtime with no filesystem serves a build it embedded\n * at deploy time, and how a test avoids writing files.\n */\n readonly manifest?: AssetManifest;\n /**\n * Seconds a hashed asset may be reused without asking. One year when the\n * manifest says which names are hashed, which a build's does.\n *\n * A file under a stable name is answered with a validator and no lifetime, so\n * a browser asks again and is told 304. A prerendered page keeps the\n * `cache-control` it was rendered with and is never given this one.\n *\n * A manifest that does not carry `hashed` cannot tell the two apart, so the\n * lifetime applies to every file it lists and there is none by default.\n */\n readonly maxAge?: number;\n /**\n * Adds `immutable` beside `maxAge`. On when the manifest says which names\n * are hashed, since for those it is true by construction.\n */\n readonly immutable?: boolean;\n}\n\n/** A hashed name never changes its bytes, so a year is the conventional forever. */\nconst HASHED_MAX_AGE = 60 * 60 * 24 * 365;\n\n/**\n * Headers that describe the bytes on the wire rather than the page.\n *\n * `srvx/static` computes them for the response it actually sends: compressed\n * or not, whole or a 304. The ones a page was RENDERED with describe an\n * uncompressed body in a build's memory.\n */\nconst REPRESENTATION = new Set([\n \"accept-ranges\",\n \"content-encoding\",\n \"content-length\",\n \"content-range\",\n \"etag\",\n \"last-modified\",\n]);\n\n/**\n * Just enough of `URL` to find the path.\n *\n * `FastURL` is srvx's own, and it falls back to `new URL` for anything a\n * verbatim parse would get wrong: dot segments, backslashes, control\n * characters, non-ASCII. Using it rather than `new URL` is most of what makes\n * the miss path cheap, since the lookups either side of it are a `Set.has` and\n * a property read.\n */\ntype PathOnly = new (url: string) => { readonly pathname: string };\n\n/**\n * Serve `dist/client` for the paths the build says are there.\n *\n * Returns a `srvx` middleware, so it composes with anything else a project\n * passes in `ServerOptions.middleware` and runs before the page handler.\n *\n * INITIALISATION IS LAZY AND HAPPENS ONCE. `node:fs` and `srvx/static` are\n * imported inside it rather than at module scope, because `@barqjs/start/serve`\n * resolves on workerd too and neither exists there. After the first request the\n * fast path is synchronous — the `await` is not paid per request.\n */\nexport function assetMiddleware(options: StaticOptions = {}): ServerMiddleware {\n let ready: Ready | null | undefined;\n let loading: Promise<void> | undefined;\n\n // `loaded` is a PARAMETER rather than the captured `ready`, because a closure\n // variable cannot be narrowed across the two call sites and the alternative is\n // a non-null assertion on every line of the hot path.\n const answer = (\n loaded: Ready | null,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ): Response | Promise<Response> => {\n if (loaded === null) return next();\n // A file is a file to GET and HEAD alone. A prerendered path may also be a\n // route with a `POST` handler: the page is its GET, and every other method\n // is the application's to answer.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return next();\n\n // The manifest holds NAMES, as the build read them off the disk, and a\n // request holds a URL: `release notes.txt` arrives as `release%20notes.txt`.\n // `decodeURI` because it is what `srvx/static` opens the file by, so the two\n // cannot disagree about which name a path means.\n let { pathname } = new loaded.url(request.url);\n if (pathname.includes(\"%\")) {\n try {\n pathname = decodeURI(pathname);\n } catch {\n return next();\n }\n }\n\n const page = loaded.manifest.pages[pathname];\n if (page !== undefined) return loaded.servePage(page, request);\n\n // The miss, which is every SSR request: one `Set.has` and out, with no\n // syscall behind it. This is the whole point of the manifest.\n if (!loaded.files.has(pathname)) return next();\n\n return loaded.serveFile(pathname, request, next);\n };\n\n return (request, next) => {\n if (ready !== undefined) return answer(ready, request, next);\n loading ??= load(options).then((loaded) => {\n ready = loaded;\n });\n return loading.then(() => answer(ready ?? null, request, next));\n };\n}\n\ninterface Ready {\n readonly manifest: AssetManifest;\n readonly files: ReadonlySet<string>;\n readonly url: PathOnly;\n readonly servePage: (page: PrerenderedAsset, request: ServerRequest) => Promise<Response>;\n readonly serveFile: (\n pathname: string,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ) => Response | Promise<Response>;\n}\n\n/**\n * The request `srvx/static` would have been sent for this FILE.\n *\n * It finds a file by the request's path, and two things here are found by the\n * manifest instead: a page, whose path is `/about` and whose file is\n * `about/index.html`, and anything under a `base`, which is in every request\n * path and in no file name. `encodeURI` because `decodeURI` is what it opens\n * the file by.\n */\nfunction requestFor(file: string, request: ServerRequest): ServerRequest {\n return new Request(`http://asset/${encodeURI(file)}`, {\n method: request.method,\n headers: request.headers,\n });\n}\n\nasync function load(options: StaticOptions): Promise<Ready | null> {\n const [{ readFile }, { staticMiddleware }, { FastURL }, path, { fileURLToPath }] =\n await Promise.all([\n import(\"node:fs/promises\"),\n import(\"srvx/static\"),\n import(\"srvx\"),\n import(\"node:path\"),\n import(\"node:url\"),\n ]);\n\n const dir =\n options.dir instanceof URL ? fileURLToPath(options.dir) : (options.dir ?? \"dist/client\");\n\n let manifest = options.manifest;\n if (manifest === undefined) {\n try {\n manifest = JSON.parse(\n await readFile(path.join(dir, ASSET_MANIFEST_FILE), \"utf8\"),\n ) as AssetManifest;\n } catch {\n // No manifest means no build to serve, which is a legitimate deployment:\n // a server that only answers server functions has no client directory at\n // all. Serving nothing beats guessing at the filesystem.\n return null;\n }\n }\n\n const hashed = manifest.hashed === undefined ? null : new Set(manifest.hashed);\n const revalidated = staticMiddleware({ dir });\n const lifetime = hashed === null ? options.maxAge : (options.maxAge ?? HASHED_MAX_AGE);\n const longLived =\n lifetime === undefined\n ? revalidated\n : staticMiddleware({\n dir,\n maxAge: lifetime,\n immutable: options.immutable ?? hashed !== null,\n });\n const prefix = manifest.base ?? \"\";\n\n /** The page's bytes with nothing negotiated, for what `srvx/static` will not answer. */\n const whole = async (page: PrerenderedAsset): Promise<Response> => {\n const body = await readFile(path.join(dir, page.file));\n const headers = new Headers(page.headers);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"text/html; charset=utf-8\");\n return new Response(body, { status: page.status, headers });\n };\n const declined = (): Response => new Response(null, { status: 404 });\n\n return {\n manifest,\n files: new Set(manifest.files),\n url: FastURL as unknown as PathOnly,\n /**\n * A prerendered page, with the STATUS and HEADERS it was rendered as.\n *\n * A 200 goes through `staticMiddleware` under its file's name, so it gets\n * the validator, the 304 and the encoding a hashed chunk gets. Anything\n * else is read directly: `staticMiddleware` has no way to answer but 200,\n * and a conditional request must not turn a 404 page into a 304.\n */\n servePage: async (page, request) => {\n if (page.status !== 200) return whole(page);\n let found = true;\n const served = await revalidated(requestFor(page.file, request), () => {\n found = false;\n return declined();\n });\n if (!found) return whole(page);\n for (const name in page.headers) {\n const value = page.headers[name];\n if (value === undefined) continue;\n const key = name.toLowerCase();\n if (REPRESENTATION.has(key)) continue;\n // Both are right: the page varies on what it said, and the bytes on\n // the encoding that was negotiated for them.\n if (key === \"vary\") served.headers.append(key, value);\n else served.headers.set(key, value);\n }\n return served;\n },\n serveFile: (pathname, request, next) => {\n const serve = hashed === null || hashed.has(pathname) ? longLived : revalidated;\n return prefix === \"\"\n ? serve(request, next)\n : serve(requestFor(pathname.slice(prefix.length + 1), request), next);\n },\n };\n}\n","/**\n * The production entry — runtime-agnostic.\n *\n * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,\n * `node`, and a generic default), so one entry serves Node, Deno, Bun and\n * Cloudflare without a per-runtime adapter here. The handler below is an\n * ordinary `Request -> Response` function, which is the only shape all of them\n * agree on.\n *\n * The dev half is deliberately NOT this: Vite's middleware pipeline is\n * Connect-shaped and hands over a Node request/response pair, so `vite.ts`\n * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.\n */\n\nimport { type Server, type ServerOptions, serve } from \"srvx\";\n\nimport { type HandlerOptions, handleServerFn } from \"./server.ts\";\nimport { type StaticOptions, assetMiddleware } from \"./static.ts\";\n\nexport type { AssetManifest, PrerenderedAsset, StaticOptions } from \"./static.ts\";\nexport { ASSET_MANIFEST_FILE, assetMiddleware } from \"./static.ts\";\n\nexport interface BarqServeOptions extends Omit<ServerOptions, \"fetch\">, HandlerOptions {\n /**\n * What answers everything that is not a server function — a page render, a\n * static file, an API route.\n *\n * A 404 is the default rather than an error: a server that only exposes\n * server functions is a legitimate deployment, and inventing a page handler\n * for it would be worse than saying nothing is there.\n */\n fetch?: (request: Request) => Response | Promise<Response>;\n /**\n * Serve the build's own files, in front of everything else.\n *\n * `true` serves `dist/client` through the manifest the build wrote. Omitted,\n * nothing static is served — which is right for a deployment whose assets are\n * on a CDN and for a server that only answers server functions, and wrong\n * enough to notice for anything else.\n *\n * `static.ts` explains why a manifest rather than a `stat`: the common request\n * is a MISS, and answering it without touching the disk is worth 0.5 us.\n */\n static?: boolean | StaticOptions;\n /**\n * The document to answer a page request with, for a deployment that renders\n * its pages in the browser.\n *\n * A path to the built `index.html`, or a `file:` URL of it. Consulted only\n * after everything else has declined — the assets, the server functions and\n * the route handlers all run first — so `/api/health` still answers JSON and\n * `/_barq/fn/<id>` is still reserved. Nothing else can do this job: the asset\n * middleware answers what the build WROTE, and an SPA's routes are exactly the\n * paths it did not.\n */\n spa?: string | URL;\n}\n\n/**\n * One request, in the order the checks have to happen.\n *\n * Server functions are matched FIRST. Their URL is reserved, so a page handler\n * that also matched it would be shadowing an endpoint rather than serving a\n * page — and the failure that produces is a mutation quietly answered with\n * HTML.\n */\nexport function createFetchHandler(\n options: BarqServeOptions = {},\n): (request: Request) => Promise<Response> {\n const page = options.fetch ?? (() => new Response(\"not found\", { status: 404 }));\n const document = options.spa;\n // Read once and held, per handler: two in one process have two documents.\n let body: Promise<string> | undefined;\n const spaDocument = async (path: string | URL, missing: Response): Promise<Response> => {\n // `node:fs` is imported here rather than at module scope, for the reason\n // `static.ts` gives: this module resolves on workerd too, where there is none.\n body ??= import(\"node:fs/promises\").then((fs) => fs.readFile(path, \"utf8\"));\n try {\n return new Response(await body, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n } catch {\n // The 404 the handler already produced, rather than a 500 about a file the\n // caller never asked for.\n body = undefined;\n return missing;\n }\n };\n return async (request: Request): Promise<Response> => {\n const answered = await handleServerFn(request, options);\n if (answered !== null) return answered;\n const response = await page(request);\n if (document === undefined || response.status !== 404) return response;\n // Only a navigation. A 404 for a missing asset or an XHR is an answer the\n // caller has to see, and handing it a document instead is the failure every\n // SPA fallback that matches on \"not a file\" eventually produces.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return response;\n if (!(request.headers.get(\"accept\") ?? \"\").includes(\"text/html\")) return response;\n return spaDocument(document, response);\n };\n}\n\n/**\n * What a caller is told when something threw: that it failed, and nothing else.\n *\n * Installed because a runtime's own answer is not that. Bun outside\n * `NODE_ENV=production` answers with the message, the stack and the source\n * around the throw, and a message can name a table, a column or a path. The\n * error goes to the log, where the operator is.\n */\nfunction failed(error: unknown): Response {\n console.error(error);\n return new Response(\"internal server error\", { status: 500 });\n}\n\n/**\n * Serve on whatever runtime this is.\n *\n * Mount the generated manifest before calling this — importing\n * `virtual:barq-server-fns` is what puts the ids in the registry, and without\n * it every call is a 404.\n */\nexport function serveBarq(options: BarqServeOptions = {}): Server {\n // `reachable` and `static` come out too. They were not, so both were handed\n // to `serve()` as options it has never heard of — harmless, and exactly the\n // drift that spreads once one key leaks.\n const {\n fetch: _page,\n allowedOrigins: _origins,\n maxBodySize: _body,\n maxFormSize: _form,\n reachable: _reachable,\n static: assets,\n spa: _spa,\n middleware,\n ...rest\n } = options;\n\n // FIRST in the chain, so a hashed chunk never enters the page handler. Ahead\n // of a project's own middleware too: those exist to shape application\n // responses, and an asset is not one.\n const chain =\n assets === undefined || assets === false\n ? middleware\n : [assetMiddleware(assets === true ? {} : assets), ...(middleware ?? [])];\n\n return serve({\n ...rest,\n error: rest.error ?? failed,\n middleware: chain,\n fetch: createFetchHandler(options),\n });\n}\n"],"mappings":";;;;AA4BA,MAAa,sBAAsB;;AAmEnC,MAAM,iBAAiB;;;;;;;;AASvB,MAAM,iCAAiB,IAAI,IAAI;CAC7B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AAwBD,SAAgB,gBAAgB,UAAyB,CAAC,GAAqB;CAC7E,IAAI;CACJ,IAAI;CAKJ,MAAM,UACJ,QACA,SACA,SACiC;EACjC,IAAI,WAAW,MAAM,OAAO,KAAK;EAIjC,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,OAAO,KAAK;EAMvE,IAAI,EAAE,aAAa,IAAI,OAAO,IAAI,QAAQ,GAAG;EAC7C,IAAI,SAAS,SAAS,GAAG,GACvB,IAAI;GACF,WAAW,UAAU,QAAQ;EAC/B,QAAQ;GACN,OAAO,KAAK;EACd;EAGF,MAAM,OAAO,OAAO,SAAS,MAAM;EACnC,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,UAAU,MAAM,OAAO;EAI7D,IAAI,CAAC,OAAO,MAAM,IAAI,QAAQ,GAAG,OAAO,KAAK;EAE7C,OAAO,OAAO,UAA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