@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.
- package/LICENSE +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
package/src/static-fn.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static server functions: answered once, at prerender time, and read back as
|
|
3
|
+
* files.
|
|
4
|
+
*
|
|
5
|
+
* `staticFunctionMiddleware` is TanStack's. While the build prerenders, its
|
|
6
|
+
* server half writes each call's answer to `/_barq/static/<key>.json` in the
|
|
7
|
+
* client output; in the browser its client half asks for that file first and
|
|
8
|
+
* calls the server only when there is none. A site prerendered whole can then
|
|
9
|
+
* answer these calls from a static host with no server at all.
|
|
10
|
+
*
|
|
11
|
+
* Nothing here imports anything that is not safe in a browser: the client stub
|
|
12
|
+
* names this middleware, so the whole module reaches the client bundle. The
|
|
13
|
+
* writer that touches the disk belongs to the prerenderer and is handed over
|
|
14
|
+
* through {@link installStaticWriter}.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { decodeWire, encodeWire } from "@barqjs/server/codec";
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
type BuiltMiddleware,
|
|
21
|
+
type FreshMiddleware,
|
|
22
|
+
type WithClient,
|
|
23
|
+
type WithServer,
|
|
24
|
+
createMiddleware,
|
|
25
|
+
} from "./middleware.ts";
|
|
26
|
+
|
|
27
|
+
/** Where a static answer is served from, under the client output. */
|
|
28
|
+
export const STATIC_PREFIX = "/_barq/static/";
|
|
29
|
+
|
|
30
|
+
/** What a static answer file holds. */
|
|
31
|
+
export interface StaticAnswer {
|
|
32
|
+
readonly result: unknown;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What the prerenderer hands over to receive each answer: the file's key, the
|
|
37
|
+
* function and input it was derived from, and the file's contents.
|
|
38
|
+
*/
|
|
39
|
+
export type StaticWriter = (key: string, identity: string, answer: string) => Promise<void>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One writer per process, whichever copy of this module asks: the prerenderer
|
|
43
|
+
* imports the server bundle, which carries a copy of its own, and installs the
|
|
44
|
+
* writer from outside it.
|
|
45
|
+
*/
|
|
46
|
+
const SHARED = ((globalThis as Record<symbol, unknown>)[Symbol.for("barq.start.static-writer")] ??=
|
|
47
|
+
{ writer: null }) as { writer: StaticWriter | null };
|
|
48
|
+
|
|
49
|
+
/** Install the prerenderer's writer, or remove it with `null`. Not for application use. */
|
|
50
|
+
export function installStaticWriter(writer: StaticWriter | null): void {
|
|
51
|
+
SHARED.writer = writer;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The input as one string that does not depend on how the caller ordered its
|
|
56
|
+
* keys: `{ a, b }` and `{ b, a }` are the same call and must find the same
|
|
57
|
+
* file.
|
|
58
|
+
*/
|
|
59
|
+
export function canonicalInput(input: unknown): string {
|
|
60
|
+
return JSON.stringify(encodeWire(sorted(input)));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function sorted(value: unknown): unknown {
|
|
64
|
+
if (Array.isArray(value)) return value.map(sorted);
|
|
65
|
+
if (typeof value !== "object" || value === null) return value;
|
|
66
|
+
const prototype: unknown = Object.getPrototypeOf(value);
|
|
67
|
+
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
68
|
+
const out: Record<string, unknown> = {};
|
|
69
|
+
for (const key of Object.keys(value).toSorted()) {
|
|
70
|
+
out[key] = sorted((value as Record<string, unknown>)[key]);
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The file name for one function and one input.
|
|
77
|
+
*
|
|
78
|
+
* Two independent 53-bit hashes, so a name is 106 bits wide: a collision would
|
|
79
|
+
* hand one input's answer to another, and the prerenderer refuses one outright
|
|
80
|
+
* if it ever sees it. Not a cryptographic hash, because nothing here is secret
|
|
81
|
+
* and `crypto.subtle` exists only in a secure context, which a page served over
|
|
82
|
+
* plain HTTP is not.
|
|
83
|
+
*/
|
|
84
|
+
export function staticKey(id: string, input: string): string {
|
|
85
|
+
const text = `${id}\n${input}`;
|
|
86
|
+
return (
|
|
87
|
+
hash53(text, 0x9e3779b9).toString(16).padStart(14, "0") +
|
|
88
|
+
hash53(text, 0x85ebca6b).toString(16).padStart(14, "0")
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function hash53(text: string, seed: number): number {
|
|
93
|
+
let h1 = 0xdeadbeef ^ seed;
|
|
94
|
+
let h2 = 0x41c6ce57 ^ seed;
|
|
95
|
+
for (let index = 0; index < text.length; index++) {
|
|
96
|
+
const code = text.charCodeAt(index);
|
|
97
|
+
h1 = Math.imul(h1 ^ code, 2654435761);
|
|
98
|
+
h2 = Math.imul(h2 ^ code, 1597334677);
|
|
99
|
+
}
|
|
100
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
101
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
102
|
+
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Where the answer for one call is, as a URL. */
|
|
106
|
+
export function staticUrl(id: string, input: unknown): string {
|
|
107
|
+
return `${STATIC_PREFIX}${staticKey(id, canonicalInput(input))}.json`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Whether an answer can be written to a file and read back as the same value. */
|
|
111
|
+
function cacheable(answer: unknown): boolean {
|
|
112
|
+
// A client half answering `undefined` without calling `next()` is refused as
|
|
113
|
+
// a middleware that forgot to, so a result of nothing goes to the server.
|
|
114
|
+
if (answer === undefined) return false;
|
|
115
|
+
if (answer instanceof Response || answer instanceof ReadableStream) return false;
|
|
116
|
+
return !(
|
|
117
|
+
typeof answer === "object" &&
|
|
118
|
+
answer !== null &&
|
|
119
|
+
typeof (answer as Partial<AsyncIterable<unknown>>)[Symbol.asyncIterator] === "function"
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const MISSING = Symbol("missing");
|
|
124
|
+
|
|
125
|
+
/** The file's answer, or {@link MISSING} when there is no file to read. */
|
|
126
|
+
async function readStatic(id: string, input: unknown): Promise<unknown> {
|
|
127
|
+
let response: Response;
|
|
128
|
+
try {
|
|
129
|
+
response = await fetch(staticUrl(id, input), { headers: { accept: "application/json" } });
|
|
130
|
+
} catch {
|
|
131
|
+
return MISSING;
|
|
132
|
+
}
|
|
133
|
+
// A dev server or a host with an SPA fallback answers a missing file with a
|
|
134
|
+
// page, so the type is what says the file exists.
|
|
135
|
+
if (!response.ok || !(response.headers.get("content-type") ?? "").includes("json")) {
|
|
136
|
+
return MISSING;
|
|
137
|
+
}
|
|
138
|
+
return decodeWire<StaticAnswer>(await response.json()).result;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Make a server function static: answered at prerender time, read from a file
|
|
143
|
+
* afterwards.
|
|
144
|
+
*
|
|
145
|
+
* List it LAST: the key is the input as this middleware sees it, which is the
|
|
146
|
+
* input the caller passed only when nothing before it has validated or
|
|
147
|
+
* reshaped it. An input no prerendered page called with has no file, and the
|
|
148
|
+
* call goes to the server as any other would.
|
|
149
|
+
*
|
|
150
|
+
* Only the RESULT is stored. What a server middleware sends back with
|
|
151
|
+
* `sendContext` is not, and a `Response` or a stream is never written.
|
|
152
|
+
*/
|
|
153
|
+
export const staticFunctionMiddleware: BuiltMiddleware<
|
|
154
|
+
WithServer<WithClient<FreshMiddleware, Promise<{} | null>>, Promise<unknown>>
|
|
155
|
+
> = /* @__PURE__ */ createMiddleware({ type: "function" })
|
|
156
|
+
.client(async ({ next, data, serverFnMeta }) => {
|
|
157
|
+
if (serverFnMeta === undefined || serverFnMeta.id === "" || data instanceof FormData) {
|
|
158
|
+
return next();
|
|
159
|
+
}
|
|
160
|
+
const found = await readStatic(serverFnMeta.id, data);
|
|
161
|
+
return found === MISSING || found === undefined ? next() : found;
|
|
162
|
+
})
|
|
163
|
+
.server(async ({ next, data, serverFnMeta }) => {
|
|
164
|
+
const answer: unknown = await next();
|
|
165
|
+
const writer = SHARED.writer;
|
|
166
|
+
if (
|
|
167
|
+
writer !== null &&
|
|
168
|
+
serverFnMeta !== undefined &&
|
|
169
|
+
serverFnMeta.id !== "" &&
|
|
170
|
+
!(data instanceof FormData) &&
|
|
171
|
+
cacheable(answer)
|
|
172
|
+
) {
|
|
173
|
+
const input = canonicalInput(data);
|
|
174
|
+
await writer(
|
|
175
|
+
staticKey(serverFnMeta.id, input),
|
|
176
|
+
`${serverFnMeta.id}\n${input}`,
|
|
177
|
+
JSON.stringify(encodeWire({ result: answer } satisfies StaticAnswer)),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return answer;
|
|
181
|
+
});
|
package/src/static.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serving the build's own files, with the lookup the BUILD already knows.
|
|
3
|
+
*
|
|
4
|
+
* A production request is overwhelmingly a MISS: an SSR page asks this layer
|
|
5
|
+
* about a path that is not a file, and every static server that answers by
|
|
6
|
+
* touching the filesystem pays two syscalls to say "no". Measured on this
|
|
7
|
+
* machine by `packages/benchmark/src/static-lookup.ts`, on kitchen-sink's build:
|
|
8
|
+
*
|
|
9
|
+
* MISS existsSync + statSync 1.2634 us this manifest 0.2297 us
|
|
10
|
+
*
|
|
11
|
+
* So the manifest is a NEGATIVE index first and foremost. On a miss nothing
|
|
12
|
+
* touches the disk; on a hit the work is handed to `srvx/static`, which already
|
|
13
|
+
* does compression, precompressed variants, `ETag`, `Last-Modified`, ranges,
|
|
14
|
+
* dotfile rules and symlink containment in 798 lines that barq should not
|
|
15
|
+
* reimplement.
|
|
16
|
+
*
|
|
17
|
+
* WHAT THE MANIFEST CARRIES AND WHY. Not `type`, `size` or `etag`: those are
|
|
18
|
+
* derivable from the file and a copy of them is a second source of truth that
|
|
19
|
+
* goes stale against the bytes. What it carries is exactly the two things the
|
|
20
|
+
* filesystem cannot answer — which request paths exist, and what STATUS and
|
|
21
|
+
* HEADERS a prerendered page was rendered with. That second one was being
|
|
22
|
+
* dropped: `PrerenderedPage` has recorded `status` and `headers` all along, and
|
|
23
|
+
* nothing persisted them, so a prerendered 404 page was served as 200.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { ServerMiddleware, ServerRequest } from "srvx";
|
|
27
|
+
|
|
28
|
+
/** Where the build writes it, inside the client output directory. */
|
|
29
|
+
export const ASSET_MANIFEST_FILE = "barq-assets.json";
|
|
30
|
+
|
|
31
|
+
/** A page the prerenderer wrote, and the response it was rendered as. */
|
|
32
|
+
export interface PrerenderedAsset {
|
|
33
|
+
/** Relative to the client output directory. */
|
|
34
|
+
readonly file: string;
|
|
35
|
+
readonly status: number;
|
|
36
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface AssetManifest {
|
|
40
|
+
/** Request path -> the prerendered page written for it. */
|
|
41
|
+
readonly pages: Readonly<Record<string, PrerenderedAsset>>;
|
|
42
|
+
/** Every other servable path, as request paths. */
|
|
43
|
+
readonly files: readonly string[];
|
|
44
|
+
/**
|
|
45
|
+
* The members of `files` whose NAME changes when their bytes do.
|
|
46
|
+
*
|
|
47
|
+
* The build knows and a directory listing cannot say: a chunk it emitted is
|
|
48
|
+
* `app-8f1c2a.js`, and `robots.txt` copied out of `public/` sits beside it
|
|
49
|
+
* under a name the next deploy reuses. Only the first may be cached without
|
|
50
|
+
* asking again.
|
|
51
|
+
*/
|
|
52
|
+
readonly hashed?: readonly string[];
|
|
53
|
+
/**
|
|
54
|
+
* What every request path here starts with and no file on disk does: Vite's
|
|
55
|
+
* `base`, without its trailing slash. Absent for a site served from `/`.
|
|
56
|
+
*/
|
|
57
|
+
readonly base?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface StaticOptions {
|
|
61
|
+
/**
|
|
62
|
+
* The client output directory. Default `dist/client`.
|
|
63
|
+
*
|
|
64
|
+
* A `file:` URL is read as one, which is how an entry names a directory beside
|
|
65
|
+
* itself: `new URL("../client", import.meta.url)`. Its `.pathname` is not a
|
|
66
|
+
* path, since a space in it is still `%20`.
|
|
67
|
+
*/
|
|
68
|
+
readonly dir?: string | URL;
|
|
69
|
+
/**
|
|
70
|
+
* The manifest. Read from `<dir>/barq-assets.json` when omitted.
|
|
71
|
+
*
|
|
72
|
+
* Passing one is how a runtime with no filesystem serves a build it embedded
|
|
73
|
+
* at deploy time, and how a test avoids writing files.
|
|
74
|
+
*/
|
|
75
|
+
readonly manifest?: AssetManifest;
|
|
76
|
+
/**
|
|
77
|
+
* Seconds a hashed asset may be reused without asking. One year when the
|
|
78
|
+
* manifest says which names are hashed, which a build's does.
|
|
79
|
+
*
|
|
80
|
+
* A file under a stable name is answered with a validator and no lifetime, so
|
|
81
|
+
* a browser asks again and is told 304. A prerendered page keeps the
|
|
82
|
+
* `cache-control` it was rendered with and is never given this one.
|
|
83
|
+
*
|
|
84
|
+
* A manifest that does not carry `hashed` cannot tell the two apart, so the
|
|
85
|
+
* lifetime applies to every file it lists and there is none by default.
|
|
86
|
+
*/
|
|
87
|
+
readonly maxAge?: number;
|
|
88
|
+
/**
|
|
89
|
+
* Adds `immutable` beside `maxAge`. On when the manifest says which names
|
|
90
|
+
* are hashed, since for those it is true by construction.
|
|
91
|
+
*/
|
|
92
|
+
readonly immutable?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A hashed name never changes its bytes, so a year is the conventional forever. */
|
|
96
|
+
const HASHED_MAX_AGE = 60 * 60 * 24 * 365;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Headers that describe the bytes on the wire rather than the page.
|
|
100
|
+
*
|
|
101
|
+
* `srvx/static` computes them for the response it actually sends: compressed
|
|
102
|
+
* or not, whole or a 304. The ones a page was RENDERED with describe an
|
|
103
|
+
* uncompressed body in a build's memory.
|
|
104
|
+
*/
|
|
105
|
+
const REPRESENTATION = new Set([
|
|
106
|
+
"accept-ranges",
|
|
107
|
+
"content-encoding",
|
|
108
|
+
"content-length",
|
|
109
|
+
"content-range",
|
|
110
|
+
"etag",
|
|
111
|
+
"last-modified",
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Just enough of `URL` to find the path.
|
|
116
|
+
*
|
|
117
|
+
* `FastURL` is srvx's own, and it falls back to `new URL` for anything a
|
|
118
|
+
* verbatim parse would get wrong: dot segments, backslashes, control
|
|
119
|
+
* characters, non-ASCII. Using it rather than `new URL` is most of what makes
|
|
120
|
+
* the miss path cheap, since the lookups either side of it are a `Set.has` and
|
|
121
|
+
* a property read.
|
|
122
|
+
*/
|
|
123
|
+
type PathOnly = new (url: string) => { readonly pathname: string };
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Serve `dist/client` for the paths the build says are there.
|
|
127
|
+
*
|
|
128
|
+
* Returns a `srvx` middleware, so it composes with anything else a project
|
|
129
|
+
* passes in `ServerOptions.middleware` and runs before the page handler.
|
|
130
|
+
*
|
|
131
|
+
* INITIALISATION IS LAZY AND HAPPENS ONCE. `node:fs` and `srvx/static` are
|
|
132
|
+
* imported inside it rather than at module scope, because `@barqjs/start/serve`
|
|
133
|
+
* resolves on workerd too and neither exists there. After the first request the
|
|
134
|
+
* fast path is synchronous — the `await` is not paid per request.
|
|
135
|
+
*/
|
|
136
|
+
export function assetMiddleware(options: StaticOptions = {}): ServerMiddleware {
|
|
137
|
+
let ready: Ready | null | undefined;
|
|
138
|
+
let loading: Promise<void> | undefined;
|
|
139
|
+
|
|
140
|
+
// `loaded` is a PARAMETER rather than the captured `ready`, because a closure
|
|
141
|
+
// variable cannot be narrowed across the two call sites and the alternative is
|
|
142
|
+
// a non-null assertion on every line of the hot path.
|
|
143
|
+
const answer = (
|
|
144
|
+
loaded: Ready | null,
|
|
145
|
+
request: ServerRequest,
|
|
146
|
+
next: () => Response | Promise<Response>,
|
|
147
|
+
): Response | Promise<Response> => {
|
|
148
|
+
if (loaded === null) return next();
|
|
149
|
+
// A file is a file to GET and HEAD alone. A prerendered path may also be a
|
|
150
|
+
// route with a `POST` handler: the page is its GET, and every other method
|
|
151
|
+
// is the application's to answer.
|
|
152
|
+
if (request.method !== "GET" && request.method !== "HEAD") return next();
|
|
153
|
+
|
|
154
|
+
// The manifest holds NAMES, as the build read them off the disk, and a
|
|
155
|
+
// request holds a URL: `release notes.txt` arrives as `release%20notes.txt`.
|
|
156
|
+
// `decodeURI` because it is what `srvx/static` opens the file by, so the two
|
|
157
|
+
// cannot disagree about which name a path means.
|
|
158
|
+
let { pathname } = new loaded.url(request.url);
|
|
159
|
+
if (pathname.includes("%")) {
|
|
160
|
+
try {
|
|
161
|
+
pathname = decodeURI(pathname);
|
|
162
|
+
} catch {
|
|
163
|
+
return next();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const page = loaded.manifest.pages[pathname];
|
|
168
|
+
if (page !== undefined) return loaded.servePage(page, request);
|
|
169
|
+
|
|
170
|
+
// The miss, which is every SSR request: one `Set.has` and out, with no
|
|
171
|
+
// syscall behind it. This is the whole point of the manifest.
|
|
172
|
+
if (!loaded.files.has(pathname)) return next();
|
|
173
|
+
|
|
174
|
+
return loaded.serveFile(pathname, request, next);
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
return (request, next) => {
|
|
178
|
+
if (ready !== undefined) return answer(ready, request, next);
|
|
179
|
+
loading ??= load(options).then((loaded) => {
|
|
180
|
+
ready = loaded;
|
|
181
|
+
});
|
|
182
|
+
return loading.then(() => answer(ready ?? null, request, next));
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface Ready {
|
|
187
|
+
readonly manifest: AssetManifest;
|
|
188
|
+
readonly files: ReadonlySet<string>;
|
|
189
|
+
readonly url: PathOnly;
|
|
190
|
+
readonly servePage: (page: PrerenderedAsset, request: ServerRequest) => Promise<Response>;
|
|
191
|
+
readonly serveFile: (
|
|
192
|
+
pathname: string,
|
|
193
|
+
request: ServerRequest,
|
|
194
|
+
next: () => Response | Promise<Response>,
|
|
195
|
+
) => Response | Promise<Response>;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The request `srvx/static` would have been sent for this FILE.
|
|
200
|
+
*
|
|
201
|
+
* It finds a file by the request's path, and two things here are found by the
|
|
202
|
+
* manifest instead: a page, whose path is `/about` and whose file is
|
|
203
|
+
* `about/index.html`, and anything under a `base`, which is in every request
|
|
204
|
+
* path and in no file name. `encodeURI` because `decodeURI` is what it opens
|
|
205
|
+
* the file by.
|
|
206
|
+
*/
|
|
207
|
+
function requestFor(file: string, request: ServerRequest): ServerRequest {
|
|
208
|
+
return new Request(`http://asset/${encodeURI(file)}`, {
|
|
209
|
+
method: request.method,
|
|
210
|
+
headers: request.headers,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function load(options: StaticOptions): Promise<Ready | null> {
|
|
215
|
+
const [{ readFile }, { staticMiddleware }, { FastURL }, path, { fileURLToPath }] =
|
|
216
|
+
await Promise.all([
|
|
217
|
+
import("node:fs/promises"),
|
|
218
|
+
import("srvx/static"),
|
|
219
|
+
import("srvx"),
|
|
220
|
+
import("node:path"),
|
|
221
|
+
import("node:url"),
|
|
222
|
+
]);
|
|
223
|
+
|
|
224
|
+
const dir =
|
|
225
|
+
options.dir instanceof URL ? fileURLToPath(options.dir) : (options.dir ?? "dist/client");
|
|
226
|
+
|
|
227
|
+
let manifest = options.manifest;
|
|
228
|
+
if (manifest === undefined) {
|
|
229
|
+
try {
|
|
230
|
+
manifest = JSON.parse(
|
|
231
|
+
await readFile(path.join(dir, ASSET_MANIFEST_FILE), "utf8"),
|
|
232
|
+
) as AssetManifest;
|
|
233
|
+
} catch {
|
|
234
|
+
// No manifest means no build to serve, which is a legitimate deployment:
|
|
235
|
+
// a server that only answers server functions has no client directory at
|
|
236
|
+
// all. Serving nothing beats guessing at the filesystem.
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const hashed = manifest.hashed === undefined ? null : new Set(manifest.hashed);
|
|
242
|
+
const revalidated = staticMiddleware({ dir });
|
|
243
|
+
const lifetime = hashed === null ? options.maxAge : (options.maxAge ?? HASHED_MAX_AGE);
|
|
244
|
+
const longLived =
|
|
245
|
+
lifetime === undefined
|
|
246
|
+
? revalidated
|
|
247
|
+
: staticMiddleware({
|
|
248
|
+
dir,
|
|
249
|
+
maxAge: lifetime,
|
|
250
|
+
immutable: options.immutable ?? hashed !== null,
|
|
251
|
+
});
|
|
252
|
+
const prefix = manifest.base ?? "";
|
|
253
|
+
|
|
254
|
+
/** The page's bytes with nothing negotiated, for what `srvx/static` will not answer. */
|
|
255
|
+
const whole = async (page: PrerenderedAsset): Promise<Response> => {
|
|
256
|
+
const body = await readFile(path.join(dir, page.file));
|
|
257
|
+
const headers = new Headers(page.headers);
|
|
258
|
+
if (!headers.has("content-type")) headers.set("content-type", "text/html; charset=utf-8");
|
|
259
|
+
return new Response(body, { status: page.status, headers });
|
|
260
|
+
};
|
|
261
|
+
const declined = (): Response => new Response(null, { status: 404 });
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
manifest,
|
|
265
|
+
files: new Set(manifest.files),
|
|
266
|
+
url: FastURL as unknown as PathOnly,
|
|
267
|
+
/**
|
|
268
|
+
* A prerendered page, with the STATUS and HEADERS it was rendered as.
|
|
269
|
+
*
|
|
270
|
+
* A 200 goes through `staticMiddleware` under its file's name, so it gets
|
|
271
|
+
* the validator, the 304 and the encoding a hashed chunk gets. Anything
|
|
272
|
+
* else is read directly: `staticMiddleware` has no way to answer but 200,
|
|
273
|
+
* and a conditional request must not turn a 404 page into a 304.
|
|
274
|
+
*/
|
|
275
|
+
servePage: async (page, request) => {
|
|
276
|
+
if (page.status !== 200) return whole(page);
|
|
277
|
+
let found = true;
|
|
278
|
+
const served = await revalidated(requestFor(page.file, request), () => {
|
|
279
|
+
found = false;
|
|
280
|
+
return declined();
|
|
281
|
+
});
|
|
282
|
+
if (!found) return whole(page);
|
|
283
|
+
for (const name in page.headers) {
|
|
284
|
+
const value = page.headers[name];
|
|
285
|
+
if (value === undefined) continue;
|
|
286
|
+
const key = name.toLowerCase();
|
|
287
|
+
if (REPRESENTATION.has(key)) continue;
|
|
288
|
+
// Both are right: the page varies on what it said, and the bytes on
|
|
289
|
+
// the encoding that was negotiated for them.
|
|
290
|
+
if (key === "vary") served.headers.append(key, value);
|
|
291
|
+
else served.headers.set(key, value);
|
|
292
|
+
}
|
|
293
|
+
return served;
|
|
294
|
+
},
|
|
295
|
+
serveFile: (pathname, request, next) => {
|
|
296
|
+
const serve = hashed === null || hashed.has(pathname) ? longLived : revalidated;
|
|
297
|
+
return prefix === ""
|
|
298
|
+
? serve(request, next)
|
|
299
|
+
: serve(requestFor(pathname.slice(prefix.length + 1), request), next);
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}
|
package/src/stubs.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stubs a page has made, and how `live` calls one: a module of its own so
|
|
3
|
+
* the frames client finds a stub by id without importing the stub's module.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** What the registry holds: a callable stub that knows its id. */
|
|
7
|
+
export type Stub = ((options?: unknown) => Promise<unknown>) & {
|
|
8
|
+
readonly meta: { readonly id: string };
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** A call at the live address: where the last connection left off, and how to end this one. */
|
|
12
|
+
export interface LiveRequest {
|
|
13
|
+
readonly lastEventId: string | null;
|
|
14
|
+
readonly signal: AbortSignal;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** How `live` calls a stub at the live address, its client middleware around the fetch. */
|
|
18
|
+
export const LIVE_CALL: unique symbol = Symbol.for("barq.server-fn.live");
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Every stub this page has made, by id: what a frame the page carries asks for
|
|
22
|
+
* its connection through when it was called through `live` on the server.
|
|
23
|
+
*/
|
|
24
|
+
const STUBS = new Map<string, Stub>();
|
|
25
|
+
|
|
26
|
+
export function registerStub(id: string, stub: Stub): void {
|
|
27
|
+
STUBS.set(id, stub);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function clientStub(id: string): Stub | undefined {
|
|
31
|
+
return STUBS.get(id);
|
|
32
|
+
}
|
package/src/timing.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Server-Timing` entries for the development server: how long a page's
|
|
3
|
+
* `beforeLoad`, its awaited loaders and its render took, and how long a server
|
|
4
|
+
* function ran. The browser's network panel shows them under Timing.
|
|
5
|
+
*
|
|
6
|
+
* Callers gate on `isDev`, a literal `false` in a production build, so none of
|
|
7
|
+
* this reaches a production response.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** A clock that starts now and reads off one `Server-Timing` entry per phase. */
|
|
11
|
+
export interface ServerTiming {
|
|
12
|
+
/** Close the phase that began at the last call (or at the start) under `name`. */
|
|
13
|
+
phase(name: string, description: string): void;
|
|
14
|
+
/** The header value, or `""` when nothing was measured. */
|
|
15
|
+
header(): string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function serverTiming(): ServerTiming {
|
|
19
|
+
const entries: string[] = [];
|
|
20
|
+
let from = performance.now();
|
|
21
|
+
return {
|
|
22
|
+
phase(name, description) {
|
|
23
|
+
const now = performance.now();
|
|
24
|
+
entries.push(`${name};dur=${(now - from).toFixed(1)};desc=${JSON.stringify(description)}`);
|
|
25
|
+
from = now;
|
|
26
|
+
},
|
|
27
|
+
header: () => entries.join(", "),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What can cross the wire, as types: the check `createServerFn` runs on a
|
|
3
|
+
* handler's result and a validator's input, so a value the codec would refuse
|
|
4
|
+
* at runtime is a type error where it is written.
|
|
5
|
+
*
|
|
6
|
+
* The codec is seroval with `RegExp` refused and errors redacted
|
|
7
|
+
* (`@barqjs/server/codec`). It carries primitives, `bigint`, `undefined`,
|
|
8
|
+
* `Date`, `Error`, `Map`, `Set`, `Promise`, typed arrays, `ArrayBuffer`, arrays
|
|
9
|
+
* and plain objects, and throws on a function, a symbol, a `RegExp`, a `URL`, a
|
|
10
|
+
* `Blob` and an instance of a class it was not given an adapter for.
|
|
11
|
+
*
|
|
12
|
+
* A class instance whose type has no methods is structurally a plain object,
|
|
13
|
+
* and no type can tell the two apart, so that one is caught at runtime only.
|
|
14
|
+
* The same is true of a class a `createSerializationAdapter` carries: its type
|
|
15
|
+
* has methods, so it is a type error here, and `strict: { output: false }` is
|
|
16
|
+
* how a function that returns one says the adapter is there.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
type Leaf =
|
|
20
|
+
| string
|
|
21
|
+
| number
|
|
22
|
+
| boolean
|
|
23
|
+
| bigint
|
|
24
|
+
| null
|
|
25
|
+
| undefined
|
|
26
|
+
| void
|
|
27
|
+
| Date
|
|
28
|
+
| Error
|
|
29
|
+
| ArrayBuffer
|
|
30
|
+
| ArrayBufferView;
|
|
31
|
+
|
|
32
|
+
/** Classes the codec refuses whose types would otherwise be read member by member. */
|
|
33
|
+
type Refused =
|
|
34
|
+
| readonly [RegExp, "a RegExp"]
|
|
35
|
+
| readonly [URL, "a URL"]
|
|
36
|
+
| readonly [URLSearchParams, "a URLSearchParams"]
|
|
37
|
+
| readonly [Blob, "a Blob"]
|
|
38
|
+
| readonly [Headers, "a Headers"]
|
|
39
|
+
| readonly [Request, "a Request"]
|
|
40
|
+
| readonly [Response, "a Response, which crosses only as the whole result"]
|
|
41
|
+
| readonly [ReadableStream, "a stream, which crosses only as the whole result"]
|
|
42
|
+
| readonly [WeakMap<object, unknown>, "a WeakMap"]
|
|
43
|
+
| readonly [WeakSet<object>, "a WeakSet"];
|
|
44
|
+
|
|
45
|
+
type RefusedName<Value> = Refused extends infer Each
|
|
46
|
+
? Each extends readonly [infer Class, infer Name]
|
|
47
|
+
? Value extends Class
|
|
48
|
+
? Name
|
|
49
|
+
: never
|
|
50
|
+
: never
|
|
51
|
+
: never;
|
|
52
|
+
|
|
53
|
+
/** Deep enough for any payload written by hand; a recursive type stops here rather than looping. */
|
|
54
|
+
type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Every place in `Value` the codec cannot carry, as a sentence naming where,
|
|
58
|
+
* or `never` when there is none.
|
|
59
|
+
*/
|
|
60
|
+
export type WireProblem<Value, Path extends string = "the value", Left extends number = 10> = [
|
|
61
|
+
Left,
|
|
62
|
+
] extends [never]
|
|
63
|
+
? never
|
|
64
|
+
: 0 extends 1 & Value
|
|
65
|
+
? never
|
|
66
|
+
: unknown extends Value
|
|
67
|
+
? never
|
|
68
|
+
: Value extends Leaf
|
|
69
|
+
? never
|
|
70
|
+
: Value extends symbol
|
|
71
|
+
? `${Path} is a symbol`
|
|
72
|
+
: Value extends (...args: never[]) => unknown
|
|
73
|
+
? `${Path} is a function`
|
|
74
|
+
: [RefusedName<Value>] extends [never]
|
|
75
|
+
? Value extends Promise<infer Settled>
|
|
76
|
+
? WireProblem<Settled, Path, Depth[Left]>
|
|
77
|
+
: Value extends ReadonlyMap<infer Key, infer Item>
|
|
78
|
+
? | WireProblem<Key, `${Path}'s keys`, Depth[Left]>
|
|
79
|
+
| WireProblem<Item, `${Path}'s values`, Depth[Left]>
|
|
80
|
+
: Value extends ReadonlySet<infer Item>
|
|
81
|
+
? WireProblem<Item, `${Path}'s members`, Depth[Left]>
|
|
82
|
+
: Value extends readonly unknown[]
|
|
83
|
+
? WireProblem<Value[number], `${Path}[number]`, Depth[Left]>
|
|
84
|
+
: Value extends object
|
|
85
|
+
? {
|
|
86
|
+
[Key in keyof Value]-?: WireProblem<
|
|
87
|
+
Value[Key],
|
|
88
|
+
`${Path}.${Key & string}`,
|
|
89
|
+
Depth[Left]
|
|
90
|
+
>;
|
|
91
|
+
}[keyof Value]
|
|
92
|
+
: never
|
|
93
|
+
: `${Path} is ${RefusedName<Value>}`;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A handler's result: a `Response` or a stream as the whole of it, a
|
|
97
|
+
* component, which crosses as a frame of its markup, or a value the codec
|
|
98
|
+
* carries. A stream's values are checked like any other.
|
|
99
|
+
*/
|
|
100
|
+
export type ResultProblem<Result> = 0 extends 1 & Result
|
|
101
|
+
? never
|
|
102
|
+
: Result extends Response
|
|
103
|
+
? never
|
|
104
|
+
: Result extends (props: never) => unknown
|
|
105
|
+
? never
|
|
106
|
+
: Result extends ReadableStream<infer Value>
|
|
107
|
+
? WireProblem<Value, "each value it streams">
|
|
108
|
+
: Result extends AsyncIterable<infer Value>
|
|
109
|
+
? WireProblem<Value, "each value it yields">
|
|
110
|
+
: WireProblem<Result, "the result">;
|
|
111
|
+
|
|
112
|
+
/** A validator's input: a value the codec carries, or a form where a form can be sent. */
|
|
113
|
+
export type InputProblem<Input, Method> = 0 extends 1 & Input
|
|
114
|
+
? never
|
|
115
|
+
: Input extends FormData
|
|
116
|
+
? Method extends "POST"
|
|
117
|
+
? never
|
|
118
|
+
: "the input is a form, and a GET has no body to carry one"
|
|
119
|
+
: WireProblem<Input, "the input">;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* What a checked type must also be: anything, when there is no problem, and a
|
|
123
|
+
* type naming the problem, which nothing is, when there is one. The name is
|
|
124
|
+
* what the type error shows.
|
|
125
|
+
*/
|
|
126
|
+
export type Crossable<Problem> = [Problem] extends [never]
|
|
127
|
+
? unknown
|
|
128
|
+
: { readonly "cannot cross the wire": Problem };
|
|
129
|
+
|
|
130
|
+
/** `strict`, as `createServerFn` takes it. */
|
|
131
|
+
export type Strictness = boolean | { readonly input?: boolean; readonly output?: boolean };
|
|
132
|
+
|
|
133
|
+
/** Whether a side is checked: on unless `strict` or its side says `false`. */
|
|
134
|
+
export type StrictOn<Strict, Side extends "input" | "output"> = Strict extends false
|
|
135
|
+
? false
|
|
136
|
+
: Strict extends { readonly [Key in Side]: false }
|
|
137
|
+
? false
|
|
138
|
+
: true;
|