@barqjs/start 0.0.0-stage → 0.2.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +791 -2
- package/dist/client-BHyIiYxt.js +1527 -0
- package/dist/client-BHyIiYxt.js.map +1 -0
- package/dist/client-DHCV7yvQ.d.ts +440 -0
- package/dist/client-DHCV7yvQ.d.ts.map +1 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +4 -0
- package/dist/env-qA8EyOr1.d.ts +49 -0
- package/dist/env-qA8EyOr1.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +44 -0
- package/dist/env.js.map +1 -0
- package/dist/index-Bm_-MTj6.d.ts +915 -0
- package/dist/index-Bm_-MTj6.d.ts.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +6 -0
- package/dist/middleware-BdVlE8qm.d.ts +576 -0
- package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +282 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +98 -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 +58 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +26 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +135 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +223 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-BV3xKmLa.js +1148 -0
- package/dist/server-BV3xKmLa.js.map +1 -0
- package/dist/server.d.ts +142 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-ChnB_xug.js +1140 -0
- package/dist/src-ChnB_xug.js.map +1 -0
- package/dist/static-fn-DgjNArBe.js +123 -0
- package/dist/static-fn-DgjNArBe.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +672 -0
- package/src/context.ts +666 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +97 -0
- package/src/frames-client.ts +1216 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +714 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +182 -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 +990 -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 +139 -0
package/src/cookies.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cookies, parsed and serialized here rather than taken from a package.
|
|
3
|
+
*
|
|
4
|
+
* It is a hundred lines and the traps are all known, so a dependency buys
|
|
5
|
+
* nothing this file does not — but the traps are REAL, and every one of them is
|
|
6
|
+
* a rule a browser enforces SILENTLY. A cookie a browser drops looks exactly
|
|
7
|
+
* like a cookie the server never set, so each rule below is a THROW rather than
|
|
8
|
+
* a correction: being told the attribute combination is impossible beats
|
|
9
|
+
* debugging a login that works on the server and not in Chrome.
|
|
10
|
+
*
|
|
11
|
+
* The rules, and where they come from:
|
|
12
|
+
*
|
|
13
|
+
* - `SameSite=None` REQUIRES `Secure`. Chrome 80 made this a hard drop
|
|
14
|
+
* (RFC 6265bis §5.4.7); without it the cookie is not stored at all.
|
|
15
|
+
* - `Partitioned` REQUIRES `Secure` (CHIPS), and is rejected without it.
|
|
16
|
+
* - `__Host-` requires `Secure`, `Path=/`, and NO `Domain` (RFC 6265bis
|
|
17
|
+
* §4.1.3). `__Secure-` requires `Secure`.
|
|
18
|
+
* - `Max-Age` must be an INTEGER. A fractional one is ignored, which silently
|
|
19
|
+
* turns a dated cookie into a session one.
|
|
20
|
+
* - `Expires` is an IMF-fixdate, which is what `Date.toUTCString()` produces
|
|
21
|
+
* and what nothing else does.
|
|
22
|
+
* - A cookie NAME may not hold a separator or a control character (RFC 6265
|
|
23
|
+
* §4.1.1), and a VALUE is percent-encoded by default — a raw `;` in one
|
|
24
|
+
* truncates the cookie where the browser splits it.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Attributes a `Set-Cookie` may carry. */
|
|
28
|
+
export interface CookieOptions {
|
|
29
|
+
readonly domain?: string;
|
|
30
|
+
readonly expires?: Date;
|
|
31
|
+
readonly httpOnly?: boolean;
|
|
32
|
+
/** Seconds. Must be an integer — a browser ignores anything else. */
|
|
33
|
+
readonly maxAge?: number;
|
|
34
|
+
/** CHIPS. Browsers that do not know it ignore it. */
|
|
35
|
+
readonly partitioned?: boolean;
|
|
36
|
+
readonly path?: string;
|
|
37
|
+
readonly priority?: "low" | "medium" | "high";
|
|
38
|
+
readonly sameSite?: "strict" | "lax" | "none";
|
|
39
|
+
readonly secure?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* How the VALUE is encoded. `encodeURIComponent` by default, because a raw
|
|
42
|
+
* `;` or `,` truncates the cookie where the browser splits it. Pass the
|
|
43
|
+
* identity function for a value already in a cookie-safe alphabet — a
|
|
44
|
+
* base64url session token, say — to keep it readable in devtools.
|
|
45
|
+
*/
|
|
46
|
+
readonly encode?: (value: string) => string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A control character, or DEL. The RFC defines every set below by code point. */
|
|
50
|
+
const isControl = (code: number): boolean => code <= 0x1f || code === 0x7f;
|
|
51
|
+
|
|
52
|
+
/** Whether any character of `text` is one `refused` names. */
|
|
53
|
+
function holdsAny(text: string, refused: (code: number) => boolean): boolean {
|
|
54
|
+
for (let index = 0; index < text.length; index++) {
|
|
55
|
+
if (refused(text.charCodeAt(index))) return true;
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const codes = (characters: string): ReadonlySet<number> =>
|
|
61
|
+
new Set(Array.from(characters, (character) => character.charCodeAt(0)));
|
|
62
|
+
|
|
63
|
+
const NAME_SEPARATORS = codes(' ()<>@,;:\\"/[]?={}');
|
|
64
|
+
const VALUE_SEPARATORS = codes(' ",;\\');
|
|
65
|
+
const SEMICOLON = 0x3b;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A separator or a control character, neither of which a cookie NAME may hold
|
|
69
|
+
* (RFC 6265 §4.1.1: a name is a `token`).
|
|
70
|
+
*/
|
|
71
|
+
const illegalInName = (code: number): boolean => isControl(code) || NAME_SEPARATORS.has(code);
|
|
72
|
+
|
|
73
|
+
/** What a cookie VALUE may not hold (RFC 6265 §4.1.1: `cookie-octet`). */
|
|
74
|
+
const illegalInValue = (code: number): boolean => isControl(code) || VALUE_SEPARATORS.has(code);
|
|
75
|
+
|
|
76
|
+
/** What an attribute value may not hold, since `;` ends it. */
|
|
77
|
+
const illegalInAttribute = (code: number): boolean => isControl(code) || code === SEMICOLON;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Every cookie on a request, by name.
|
|
81
|
+
*
|
|
82
|
+
* FIRST WINS on a duplicate, which is what a browser sends when one cookie
|
|
83
|
+
* exists at two paths and is what every parser in the survey does. A value that
|
|
84
|
+
* is not valid percent-encoding comes back RAW rather than throwing: it arrived
|
|
85
|
+
* off the wire, a client may put anything there, and one malformed cookie must
|
|
86
|
+
* not take the request down.
|
|
87
|
+
*/
|
|
88
|
+
export function parseCookies(header: string | null | undefined): Record<string, string> {
|
|
89
|
+
const out: Record<string, string> = Object.create(null) as Record<string, string>;
|
|
90
|
+
if (header === null || header === undefined || header === "") return out;
|
|
91
|
+
|
|
92
|
+
for (const pair of header.split(";")) {
|
|
93
|
+
const equals = pair.indexOf("=");
|
|
94
|
+
if (equals < 0) continue;
|
|
95
|
+
const name = pair.slice(0, equals).trim();
|
|
96
|
+
if (name === "" || name in out) continue;
|
|
97
|
+
let value = pair.slice(equals + 1).trim();
|
|
98
|
+
// A quoted-string value keeps its quotes on the wire and loses them here.
|
|
99
|
+
if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) {
|
|
100
|
+
value = value.slice(1, -1);
|
|
101
|
+
}
|
|
102
|
+
out[name] = decode(value);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function decode(value: string): string {
|
|
108
|
+
if (!value.includes("%")) return value;
|
|
109
|
+
try {
|
|
110
|
+
return decodeURIComponent(value);
|
|
111
|
+
} catch {
|
|
112
|
+
// Malformed percent-encoding from a client is not this server's error.
|
|
113
|
+
return value;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* One `Set-Cookie` line.
|
|
119
|
+
*
|
|
120
|
+
* Throws on any combination a browser would drop in silence — see the header
|
|
121
|
+
* for which, and why a throw is the kinder answer.
|
|
122
|
+
*/
|
|
123
|
+
export function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {
|
|
124
|
+
if (name === "" || holdsAny(name, illegalInName)) {
|
|
125
|
+
throw new TypeError(
|
|
126
|
+
`[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.`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const secure = options.secure ?? false;
|
|
131
|
+
const path = options.path;
|
|
132
|
+
|
|
133
|
+
if (options.sameSite === "none" && !secure) {
|
|
134
|
+
throw new TypeError(
|
|
135
|
+
`[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). ` +
|
|
136
|
+
'Add `secure: true`, or use `sameSite: "lax"`.',
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
if (options.partitioned === true && !secure) {
|
|
140
|
+
throw new TypeError(
|
|
141
|
+
`[barq] The cookie "${name}" sets \`partitioned: true\` without \`secure: true\`, and a browser rejects a Partitioned cookie that is not Secure. ` +
|
|
142
|
+
"Add `secure: true`.",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
if (name.startsWith("__Host-")) {
|
|
146
|
+
if (!secure || path !== "/" || options.domain !== undefined) {
|
|
147
|
+
throw new TypeError(
|
|
148
|
+
`[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). ` +
|
|
149
|
+
'Set `secure: true` and `path: "/"`, and leave `domain` unset.',
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
} else if (name.startsWith("__Secure-") && !secure) {
|
|
153
|
+
throw new TypeError(
|
|
154
|
+
`[barq] The cookie "${name}" uses the \`__Secure-\` prefix without \`secure: true\`, so a browser would reject it (RFC 6265bis §4.1.3). ` +
|
|
155
|
+
"Add `secure: true`.",
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const encoded = (options.encode ?? encodeURIComponent)(value);
|
|
160
|
+
if (holdsAny(encoded, illegalInValue)) {
|
|
161
|
+
throw new TypeError(
|
|
162
|
+
`[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. ` +
|
|
163
|
+
"A browser would cut the value short. Leave `encode` at its default, which percent-encodes it.",
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const parts = [`${name}=${encoded}`];
|
|
168
|
+
|
|
169
|
+
if (options.maxAge !== undefined) {
|
|
170
|
+
if (!Number.isInteger(options.maxAge)) {
|
|
171
|
+
throw new TypeError(
|
|
172
|
+
`[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. ` +
|
|
173
|
+
"Pass whole seconds, such as `maxAge: 3600`.",
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
parts.push(`Max-Age=${options.maxAge}`);
|
|
177
|
+
}
|
|
178
|
+
if (options.domain !== undefined) {
|
|
179
|
+
assertAttribute(name, "domain", options.domain);
|
|
180
|
+
parts.push(`Domain=${options.domain}`);
|
|
181
|
+
}
|
|
182
|
+
if (path !== undefined) {
|
|
183
|
+
assertAttribute(name, "path", path);
|
|
184
|
+
parts.push(`Path=${path}`);
|
|
185
|
+
}
|
|
186
|
+
if (options.expires !== undefined) {
|
|
187
|
+
if (Number.isNaN(options.expires.getTime())) {
|
|
188
|
+
throw new TypeError(
|
|
189
|
+
`[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)\`.`,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
// IMF-fixdate, the only format RFC 6265 §5.1.1 requires a browser to parse
|
|
193
|
+
// and the only one `toUTCString` produces.
|
|
194
|
+
parts.push(`Expires=${options.expires.toUTCString()}`);
|
|
195
|
+
}
|
|
196
|
+
if (options.httpOnly === true) parts.push("HttpOnly");
|
|
197
|
+
if (secure) parts.push("Secure");
|
|
198
|
+
if (options.partitioned === true) parts.push("Partitioned");
|
|
199
|
+
if (options.priority !== undefined) parts.push(`Priority=${capitalize(options.priority)}`);
|
|
200
|
+
if (options.sameSite !== undefined) parts.push(`SameSite=${capitalize(options.sameSite)}`);
|
|
201
|
+
|
|
202
|
+
return parts.join("; ");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function assertAttribute(cookie: string, attribute: string, value: string): void {
|
|
206
|
+
if (holdsAny(value, illegalInAttribute)) {
|
|
207
|
+
throw new TypeError(
|
|
208
|
+
`[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. ` +
|
|
209
|
+
`Pass a plain ${attribute}, and never build it from user input without validating it.`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function capitalize(value: string): string {
|
|
215
|
+
return value.charAt(0).toUpperCase() + value.slice(1);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The line that DELETES a cookie.
|
|
220
|
+
*
|
|
221
|
+
* A cookie is deleted by being set again, expired — and the `path` and `domain`
|
|
222
|
+
* must MATCH the ones it was set with, or the browser deletes nothing and keeps
|
|
223
|
+
* the original. That is why both ride through rather than being dropped: a
|
|
224
|
+
* `deleteCookie("sid")` against a cookie set at `path: "/app"` is a no-op, and
|
|
225
|
+
* a silent one.
|
|
226
|
+
*/
|
|
227
|
+
export function deleteCookieLine(name: string, options: CookieOptions = {}): string {
|
|
228
|
+
return serializeCookie(name, "", { ...options, expires: new Date(0), maxAge: 0 });
|
|
229
|
+
}
|
package/src/env.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Functions whose body belongs to ONE side, resolved by the compiler.
|
|
3
|
+
*
|
|
4
|
+
* A codebase with a server and a browser in it has three shapes that keep
|
|
5
|
+
* recurring: something the server does and the browser does differently,
|
|
6
|
+
* something only the server may do, and something only the browser can. Written
|
|
7
|
+
* by hand each of them is a `typeof window === "undefined"` branch, and every
|
|
8
|
+
* one of those ships BOTH bodies to both bundles — the server's database call
|
|
9
|
+
* sits in the browser's JavaScript, unreachable and readable.
|
|
10
|
+
*
|
|
11
|
+
* The compiler replaces these calls outright, so the half that does not belong
|
|
12
|
+
* is absent by construction rather than unreachable. What is left here is the
|
|
13
|
+
* UNCOMPILED path: a bun test, a script run with no plugin, a package's own
|
|
14
|
+
* suite. It answers as a server would, because that is the only environment
|
|
15
|
+
* anything uncompiled runs in.
|
|
16
|
+
*
|
|
17
|
+
* ITS OWN MODULE, and nothing here imports anything. A client build that keeps
|
|
18
|
+
* the import must not reach the package index, which re-exports `context.ts`
|
|
19
|
+
* and `node:async_hooks` with it — the leak `middleware.ts` records at length.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export type IsomorphicFn<Args extends readonly unknown[] = [], Out = undefined> = (
|
|
23
|
+
...args: Args
|
|
24
|
+
) => Out;
|
|
25
|
+
|
|
26
|
+
export interface IsomorphicBuilder<
|
|
27
|
+
Args extends readonly unknown[] = [],
|
|
28
|
+
Out = undefined,
|
|
29
|
+
> extends IsomorphicFn<Args, Out> {
|
|
30
|
+
server<A extends readonly unknown[], R>(fn: (...args: A) => R): IsomorphicBuilder<A, R>;
|
|
31
|
+
client<A extends readonly unknown[], R>(fn: (...args: A) => R): IsomorphicBuilder<A, R>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* One name, two bodies, one of which survives the compile.
|
|
36
|
+
*
|
|
37
|
+
* `createIsomorphicFn().server(readFile).client(fetchIt)` is `readFile` in the
|
|
38
|
+
* server bundle and `fetchIt` in the client one. A half that is not declared
|
|
39
|
+
* becomes a no-op rather than a throw: an isomorphic function is one an author
|
|
40
|
+
* expects to call from anywhere, and refusing where they did not write a body
|
|
41
|
+
* would make every call site test the environment again.
|
|
42
|
+
*/
|
|
43
|
+
export function createIsomorphicFn(): IsomorphicBuilder {
|
|
44
|
+
return build(() => undefined as never, false);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* `served` is whether THIS chain has declared a server half. It travels with
|
|
49
|
+
* the chain: kept in one place for the module, the first isomorphic function
|
|
50
|
+
* anywhere set it for good, and every `.client(b)` written after that answered
|
|
51
|
+
* `undefined` where it is documented to answer `b`.
|
|
52
|
+
*/
|
|
53
|
+
function build<Args extends readonly unknown[], Out>(
|
|
54
|
+
current: (...args: Args) => Out,
|
|
55
|
+
served: boolean,
|
|
56
|
+
): IsomorphicBuilder<Args, Out> {
|
|
57
|
+
// The SERVER half wins if both are declared, because nothing uncompiled runs
|
|
58
|
+
// anywhere else. Theirs keeps the server implementation for the same reason
|
|
59
|
+
// and says so.
|
|
60
|
+
const chain = Object.assign(current, {
|
|
61
|
+
server: (fn: (...args: never[]) => unknown) => build(fn as never, true),
|
|
62
|
+
// `.server(a).client(b)` uncompiled is `a`, and `.client(b)` alone is `b`.
|
|
63
|
+
client: (fn: (...args: never[]) => unknown) => (served ? chain : build(fn as never, false)),
|
|
64
|
+
}) as unknown as IsomorphicBuilder<Args, Out>;
|
|
65
|
+
return chain;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A function the CLIENT bundle does not get a body for.
|
|
70
|
+
*
|
|
71
|
+
* The compiler leaves the body in the server build and replaces the call with a
|
|
72
|
+
* throwing stub in the client one, so reading a secret or opening a database
|
|
73
|
+
* connection cannot reach the browser even as dead code.
|
|
74
|
+
*/
|
|
75
|
+
export function createServerOnlyFn<Args extends readonly unknown[], Out>(
|
|
76
|
+
fn: (...args: Args) => Out,
|
|
77
|
+
): (...args: Args) => Out {
|
|
78
|
+
return fn;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The mirror: the body reaches the browser and the server gets a throw. */
|
|
82
|
+
export function createClientOnlyFn<Args extends readonly unknown[], Out>(
|
|
83
|
+
fn: (...args: Args) => Out,
|
|
84
|
+
): (...args: Args) => Out {
|
|
85
|
+
return fn;
|
|
86
|
+
}
|
package/src/fn-error.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a server function's failure reaches its caller in the browser. Its own
|
|
3
|
+
* module, so every module that answers a call can raise it and none of them
|
|
4
|
+
* has to import the stub to do so.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** What a handler threw, as a development server tells its caller. */
|
|
8
|
+
export interface ServerFnThrown {
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly message: string;
|
|
11
|
+
/** Mapped to the source files by the development server. */
|
|
12
|
+
readonly stack?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** One thing wrong with a call's input, and the path to the field it is about. */
|
|
16
|
+
export interface ServerFnIssue {
|
|
17
|
+
readonly message: string;
|
|
18
|
+
readonly path?: readonly (string | number)[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** What a failed call's JSON body may carry. */
|
|
22
|
+
export interface FailedAnswer {
|
|
23
|
+
readonly message?: string;
|
|
24
|
+
readonly issues?: readonly ServerFnIssue[];
|
|
25
|
+
readonly thrown?: ServerFnThrown;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A server function answered with a failure.
|
|
30
|
+
*
|
|
31
|
+
* THE MESSAGE IS NOT THE HANDLER'S, and that is deliberate rather than
|
|
32
|
+
* unfinished. `server.ts` refuses to put a handler's error text on the wire
|
|
33
|
+
* because it can name a table, a column or a filesystem path, and none of that
|
|
34
|
+
* is the caller's business — TanStack serialises the whole error object to the
|
|
35
|
+
* client instead. What a caller legitimately needs is the STATUS, so it is here
|
|
36
|
+
* as a field rather than something to parse back out of a string.
|
|
37
|
+
*/
|
|
38
|
+
export class ServerFnError extends Error {
|
|
39
|
+
readonly status: number;
|
|
40
|
+
/**
|
|
41
|
+
* What was wrong with the input, for a 400 the validator refused: one entry
|
|
42
|
+
* per issue, with the path to the field it is about. Sent in every build,
|
|
43
|
+
* because it describes the caller's own input.
|
|
44
|
+
*/
|
|
45
|
+
readonly issues?: readonly ServerFnIssue[];
|
|
46
|
+
/**
|
|
47
|
+
* What the handler threw: its name, message and source-mapped stack. Only a
|
|
48
|
+
* development server sends it; in production this is `undefined`, so handle
|
|
49
|
+
* a failure by its `status` rather than by this.
|
|
50
|
+
*/
|
|
51
|
+
readonly thrown?: ServerFnThrown;
|
|
52
|
+
/**
|
|
53
|
+
* The answer itself, unread.
|
|
54
|
+
*
|
|
55
|
+
* The server's own refusals land here: a 400 for input, a 403 for an origin,
|
|
56
|
+
* a 404, a 405, a 413. A `Response` a middleware or a handler THREW is not
|
|
57
|
+
* wrapped at all; the call rejects with it. A handler's own failure has
|
|
58
|
+
* nothing here worth reading: the server answers those with one fixed line,
|
|
59
|
+
* for the reason above.
|
|
60
|
+
*/
|
|
61
|
+
readonly response?: Response;
|
|
62
|
+
constructor(id: string, status: number, response?: Response, answer?: FailedAnswer) {
|
|
63
|
+
super(failureMessage(id, status, answer));
|
|
64
|
+
this.name = "ServerFnError";
|
|
65
|
+
this.status = status;
|
|
66
|
+
this.response = response;
|
|
67
|
+
if (answer?.issues !== undefined) this.issues = answer.issues;
|
|
68
|
+
if (answer?.thrown !== undefined) this.thrown = answer.thrown;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function failureMessage(id: string, status: number, answer: FailedAnswer | undefined): string {
|
|
73
|
+
const issues = answer?.issues;
|
|
74
|
+
if (issues !== undefined && issues.length > 0) {
|
|
75
|
+
const listed = issues
|
|
76
|
+
.map((issue) =>
|
|
77
|
+
issue.path === undefined ? issue.message : `\`${issue.path.join(".")}\`: ${issue.message}`,
|
|
78
|
+
)
|
|
79
|
+
.join("; ");
|
|
80
|
+
return (
|
|
81
|
+
`The server function \`${id}\` refused its input (${status}): ${listed}. ` +
|
|
82
|
+
"`error.issues` holds each issue with the path to its field."
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const thrown = answer?.thrown;
|
|
86
|
+
if (thrown !== undefined) {
|
|
87
|
+
return (
|
|
88
|
+
`The server function \`${id}\` threw \`${thrown.name}: ${thrown.message}\` and answered ${status}. ` +
|
|
89
|
+
"The server's stack is in `error.thrown.stack` and in the development overlay. A production " +
|
|
90
|
+
"server sends only the status, so handle a failure by `error.status`."
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
return (
|
|
94
|
+
`The server function \`${id}\` answered ${status}. A handler's own error text is never sent to the browser, so read it in the server's log. ` +
|
|
95
|
+
"`error.response` holds the server's answer."
|
|
96
|
+
);
|
|
97
|
+
}
|