@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
|
@@ -0,0 +1,925 @@
|
|
|
1
|
+
import { RequestEventLocals, ResponseStub } from "@barqjs/web";
|
|
2
|
+
import { commitResponseStub } from "@barqjs/web/internal";
|
|
3
|
+
import { E as OpenContext, F as StandardInput, I as StandardOutput, R as StandardSchemaLike, T as NoContribution, V as Validator, d as Empty, g as Middleware, h as Merged, n as Carries, r as ChainContribution, s as Contribution } from "./middleware-B-tI8QHQ.js";
|
|
4
|
+
import { AnySerializationAdapter, AnySerializationAdapter as AnySerializationAdapter$1, SerializationAdapter, createSerializationAdapter } from "@barqjs/server/codec";
|
|
5
|
+
import { D as ServerFnMethod, E as ServerFnMeta, O as Streamed, S as ServerFn, i as ChainStep, t as AnyServerFn } from "./client-DidH0F2e.js";
|
|
6
|
+
/**
|
|
7
|
+
* Cookies, parsed and serialized here rather than taken from a package.
|
|
8
|
+
*
|
|
9
|
+
* It is a hundred lines and the traps are all known, so a dependency buys
|
|
10
|
+
* nothing this file does not — but the traps are REAL, and every one of them is
|
|
11
|
+
* a rule a browser enforces SILENTLY. A cookie a browser drops looks exactly
|
|
12
|
+
* like a cookie the server never set, so each rule below is a THROW rather than
|
|
13
|
+
* a correction: being told the attribute combination is impossible beats
|
|
14
|
+
* debugging a login that works on the server and not in Chrome.
|
|
15
|
+
*
|
|
16
|
+
* The rules, and where they come from:
|
|
17
|
+
*
|
|
18
|
+
* - `SameSite=None` REQUIRES `Secure`. Chrome 80 made this a hard drop
|
|
19
|
+
* (RFC 6265bis §5.4.7); without it the cookie is not stored at all.
|
|
20
|
+
* - `Partitioned` REQUIRES `Secure` (CHIPS), and is rejected without it.
|
|
21
|
+
* - `__Host-` requires `Secure`, `Path=/`, and NO `Domain` (RFC 6265bis
|
|
22
|
+
* §4.1.3). `__Secure-` requires `Secure`.
|
|
23
|
+
* - `Max-Age` must be an INTEGER. A fractional one is ignored, which silently
|
|
24
|
+
* turns a dated cookie into a session one.
|
|
25
|
+
* - `Expires` is an IMF-fixdate, which is what `Date.toUTCString()` produces
|
|
26
|
+
* and what nothing else does.
|
|
27
|
+
* - A cookie NAME may not hold a separator or a control character (RFC 6265
|
|
28
|
+
* §4.1.1), and a VALUE is percent-encoded by default — a raw `;` in one
|
|
29
|
+
* truncates the cookie where the browser splits it.
|
|
30
|
+
*/
|
|
31
|
+
/** Attributes a `Set-Cookie` may carry. */
|
|
32
|
+
interface CookieOptions {
|
|
33
|
+
readonly domain?: string;
|
|
34
|
+
readonly expires?: Date;
|
|
35
|
+
readonly httpOnly?: boolean;
|
|
36
|
+
/** Seconds. Must be an integer — a browser ignores anything else. */
|
|
37
|
+
readonly maxAge?: number;
|
|
38
|
+
/** CHIPS. Browsers that do not know it ignore it. */
|
|
39
|
+
readonly partitioned?: boolean;
|
|
40
|
+
readonly path?: string;
|
|
41
|
+
readonly priority?: "low" | "medium" | "high";
|
|
42
|
+
readonly sameSite?: "strict" | "lax" | "none";
|
|
43
|
+
readonly secure?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* How the VALUE is encoded. `encodeURIComponent` by default, because a raw
|
|
46
|
+
* `;` or `,` truncates the cookie where the browser splits it. Pass the
|
|
47
|
+
* identity function for a value already in a cookie-safe alphabet — a
|
|
48
|
+
* base64url session token, say — to keep it readable in devtools.
|
|
49
|
+
*/
|
|
50
|
+
readonly encode?: (value: string) => string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Every cookie on a request, by name.
|
|
54
|
+
*
|
|
55
|
+
* FIRST WINS on a duplicate, which is what a browser sends when one cookie
|
|
56
|
+
* exists at two paths and is what every parser in the survey does. A value that
|
|
57
|
+
* is not valid percent-encoding comes back RAW rather than throwing: it arrived
|
|
58
|
+
* off the wire, a client may put anything there, and one malformed cookie must
|
|
59
|
+
* not take the request down.
|
|
60
|
+
*/
|
|
61
|
+
declare function parseCookies(header: string | null | undefined): Record<string, string>;
|
|
62
|
+
/**
|
|
63
|
+
* One `Set-Cookie` line.
|
|
64
|
+
*
|
|
65
|
+
* Throws on any combination a browser would drop in silence — see the header
|
|
66
|
+
* for which, and why a throw is the kinder answer.
|
|
67
|
+
*/
|
|
68
|
+
declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
|
|
69
|
+
/**
|
|
70
|
+
* The line that DELETES a cookie.
|
|
71
|
+
*
|
|
72
|
+
* A cookie is deleted by being set again, expired — and the `path` and `domain`
|
|
73
|
+
* must MATCH the ones it was set with, or the browser deletes nothing and keeps
|
|
74
|
+
* the original. That is why both ride through rather than being dropped: a
|
|
75
|
+
* `deleteCookie("sid")` against a cookie set at `path: "/app"` is a no-op, and
|
|
76
|
+
* a silent one.
|
|
77
|
+
*/
|
|
78
|
+
declare function deleteCookieLine(name: string, options?: CookieOptions): string;
|
|
79
|
+
/** What a session holds. An application narrows it with the type argument. */
|
|
80
|
+
type SessionData = Record<string, unknown>;
|
|
81
|
+
interface Session<T extends SessionData = SessionData> {
|
|
82
|
+
/** Stable for the life of the session. Useful as a log correlation key. */
|
|
83
|
+
readonly id: string;
|
|
84
|
+
/** When it was first sealed, as a millisecond timestamp. */
|
|
85
|
+
readonly createdAt: number;
|
|
86
|
+
readonly data: Partial<T>;
|
|
87
|
+
}
|
|
88
|
+
interface SessionManager<T extends SessionData = SessionData> {
|
|
89
|
+
readonly id: string;
|
|
90
|
+
/** When the session was first sealed, as a millisecond timestamp. */
|
|
91
|
+
readonly createdAt: number;
|
|
92
|
+
readonly data: Partial<T>;
|
|
93
|
+
/** Merge and re-seal. A function receives the current data. */
|
|
94
|
+
update(patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined)): Promise<SessionManager<T>>;
|
|
95
|
+
/** Drop it and expire the cookie. */
|
|
96
|
+
clear(): Promise<SessionManager<T>>;
|
|
97
|
+
}
|
|
98
|
+
interface SessionConfig {
|
|
99
|
+
/**
|
|
100
|
+
* The key the cookie is sealed with. At least 32 characters.
|
|
101
|
+
*
|
|
102
|
+
* It is a SECRET and belongs in the environment, never in source. Rotating it
|
|
103
|
+
* invalidates every live session, which is the intended way to log everyone
|
|
104
|
+
* out.
|
|
105
|
+
*/
|
|
106
|
+
readonly password: string;
|
|
107
|
+
/** Cookie name. Default `barq-session`. */
|
|
108
|
+
readonly name?: string;
|
|
109
|
+
/**
|
|
110
|
+
* How long a sealed cookie stays valid, in seconds. Default 7 days.
|
|
111
|
+
*
|
|
112
|
+
* Enforced on UNSEAL as well as on the cookie, because the cookie's own expiry
|
|
113
|
+
* is a request the client is free to ignore — the timestamp inside the sealed
|
|
114
|
+
* payload is the one that cannot be edited.
|
|
115
|
+
*/
|
|
116
|
+
readonly maxAge?: number;
|
|
117
|
+
/**
|
|
118
|
+
* Cookie attributes. The defaults are the strict ones — `httpOnly`, `secure`,
|
|
119
|
+
* `sameSite: "lax"`, `path: "/"` — because a session cookie readable from
|
|
120
|
+
* script is a session cookie an XSS takes.
|
|
121
|
+
*/
|
|
122
|
+
readonly cookie?: CookieOptions;
|
|
123
|
+
/**
|
|
124
|
+
* Has this session been revoked? Asked on every unseal.
|
|
125
|
+
*
|
|
126
|
+
* THE ONE THING A SEALED COOKIE CANNOT DO BY ITSELF. Nothing on the server is
|
|
127
|
+
* consulted to open one, so "log out everywhere" and "ban this account now"
|
|
128
|
+
* are otherwise impossible — an issued cookie is valid until it expires, and
|
|
129
|
+
* that is the trade the whole design makes.
|
|
130
|
+
*
|
|
131
|
+
* This is the smallest seam that closes it. The fast path stays stateless:
|
|
132
|
+
* without the hook there is no lookup, and with it an application keeps only a
|
|
133
|
+
* set of revoked IDS until they expire, which `maxAge` bounds. That is a much
|
|
134
|
+
* smaller thing to store than a session per user, and it is only ever written
|
|
135
|
+
* when somebody signs out or is banned.
|
|
136
|
+
*
|
|
137
|
+
* A REVOKED SESSION READS AS ABSENT, like every other reason a cookie will not
|
|
138
|
+
* open — see `unsealSession`. Throwing here would tell a caller the difference
|
|
139
|
+
* between "forged" and "revoked", which is an oracle.
|
|
140
|
+
*
|
|
141
|
+
* It is asked AFTER the cookie is authenticated, so an unauthenticated client
|
|
142
|
+
* cannot make the application do a lookup by sending a garbage cookie.
|
|
143
|
+
*/
|
|
144
|
+
readonly isRevoked?: (id: string) => boolean | Promise<boolean>;
|
|
145
|
+
}
|
|
146
|
+
interface Sealed {
|
|
147
|
+
readonly id: string;
|
|
148
|
+
readonly createdAt: number;
|
|
149
|
+
readonly data: SessionData;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* A session as one request holds it: what the cookie said, then every `update`
|
|
153
|
+
* and `clear` since.
|
|
154
|
+
*/
|
|
155
|
+
interface OpenSession {
|
|
156
|
+
current: Sealed;
|
|
157
|
+
/** Settles when the write in flight has, whichever way it went. */
|
|
158
|
+
writing: Promise<unknown>;
|
|
159
|
+
}
|
|
160
|
+
/** Encrypt and sign a session. Exported for code that seals outside a request. */
|
|
161
|
+
declare function sealSession(config: SessionConfig, session: Sealed): Promise<string>;
|
|
162
|
+
/**
|
|
163
|
+
* Decrypt and verify, or `null`.
|
|
164
|
+
*
|
|
165
|
+
* `null` for EVERY failure — a wrong password, a tampered ciphertext, an expired
|
|
166
|
+
* timestamp, a envelope from a future version — and never a throw. A session
|
|
167
|
+
* that will not open is not an error the request should fail on; it is a visitor
|
|
168
|
+
* who is not signed in, and the two must be indistinguishable to the caller so
|
|
169
|
+
* that a forged cookie cannot be told apart from an absent one.
|
|
170
|
+
*/
|
|
171
|
+
declare function unsealSession(config: SessionConfig, sealed: string): Promise<Sealed | null>;
|
|
172
|
+
/**
|
|
173
|
+
* The session for this request, opening the cookie if there is one.
|
|
174
|
+
*
|
|
175
|
+
* Always answers a manager, never `null`: a visitor with no session has an empty
|
|
176
|
+
* one, which is the same thing from the application's side and removes the
|
|
177
|
+
* branch that is easy to get backwards.
|
|
178
|
+
*
|
|
179
|
+
* NOTHING IS WRITTEN until `update` is called. Reading a session must not
|
|
180
|
+
* re-issue its cookie, or every page render would refresh an expiry the user did
|
|
181
|
+
* not earn — and on a page that also sets `Cache-Control: public` that
|
|
182
|
+
* `Set-Cookie` is a cache poisoning waiting to happen.
|
|
183
|
+
*/
|
|
184
|
+
declare function useSession<T extends SessionData = SessionData>(config: SessionConfig): Promise<SessionManager<T>>;
|
|
185
|
+
/** The session's data, for code that only reads. */
|
|
186
|
+
declare function getSession<T extends SessionData = SessionData>(config: SessionConfig): Promise<Session<T>>;
|
|
187
|
+
/** Merge into the session and re-seal it. */
|
|
188
|
+
declare function updateSession<T extends SessionData = SessionData>(config: SessionConfig, patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined)): Promise<SessionManager<T>>;
|
|
189
|
+
/** Drop the session and expire its cookie. */
|
|
190
|
+
declare function clearSession(config: SessionConfig): Promise<void>;
|
|
191
|
+
interface StartOptions {
|
|
192
|
+
/** Runs for every request the server answers: a page, a route handler, a server function. */
|
|
193
|
+
readonly requestMiddleware?: readonly Middleware[];
|
|
194
|
+
/** Runs for every server function, ahead of the function's own chain. */
|
|
195
|
+
readonly functionMiddleware?: readonly Middleware[];
|
|
196
|
+
/**
|
|
197
|
+
* How a type only the application knows crosses the wire, in a server
|
|
198
|
+
* function's input and result and in the page's seed. Installed when the
|
|
199
|
+
* options are first read, which both sides do before they encode anything.
|
|
200
|
+
*/
|
|
201
|
+
readonly serializationAdapters?: readonly AnySerializationAdapter$1[];
|
|
202
|
+
/**
|
|
203
|
+
* What a route that says nothing about `ssr` does, for every route: `true`,
|
|
204
|
+
* `false` (rendered in the browser alone) or `"data-only"` (loaders run on
|
|
205
|
+
* the server, the component in the browser). Wins over the router's own
|
|
206
|
+
* `defaultSsr`, as TanStack's does.
|
|
207
|
+
*/
|
|
208
|
+
readonly defaultSsr?: boolean | "data-only";
|
|
209
|
+
readonly serverFns?: {
|
|
210
|
+
/**
|
|
211
|
+
* The `fetch` every call goes out through, in place of the global one. A
|
|
212
|
+
* client middleware's `next({ fetch })` and the call's own `fetch` win
|
|
213
|
+
* over it.
|
|
214
|
+
*/
|
|
215
|
+
readonly fetch?: typeof fetch;
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
interface StartInstance<Options extends StartOptions = StartOptions> {
|
|
219
|
+
getOptions(): Options;
|
|
220
|
+
}
|
|
221
|
+
declare const UNREGISTERED: unique symbol;
|
|
222
|
+
/**
|
|
223
|
+
* Where an application tells the types about its `src/start.ts`:
|
|
224
|
+
*
|
|
225
|
+
* ```ts
|
|
226
|
+
* declare module "@barqjs/start" {
|
|
227
|
+
* interface Register {
|
|
228
|
+
* start: typeof startInstance;
|
|
229
|
+
* }
|
|
230
|
+
* }
|
|
231
|
+
* ```
|
|
232
|
+
*
|
|
233
|
+
* With that, what the global middleware passes to `next({ context })` is typed
|
|
234
|
+
* in every server function's `context` and in `getGlobalStartContext()`.
|
|
235
|
+
* Without it they are untyped, never wrong. The member below exists so the
|
|
236
|
+
* interface is not the empty object type before anything augments it.
|
|
237
|
+
*/
|
|
238
|
+
interface Register {
|
|
239
|
+
readonly [UNREGISTERED]?: never;
|
|
240
|
+
}
|
|
241
|
+
type RegisteredInstance = Register extends {
|
|
242
|
+
readonly start: infer Instance;
|
|
243
|
+
} ? Instance : StartInstance;
|
|
244
|
+
/** What an instance's request middleware adds, for the whole request. */
|
|
245
|
+
type RequestContextOf<Instance> = Instance extends StartInstance<infer Options> ? ChainContribution<NonNullable<Options["requestMiddleware"]>>["context"] : Empty;
|
|
246
|
+
/** What an instance's middleware hands every server function: request, then function. */
|
|
247
|
+
type FunctionContextOf<Instance> = Instance extends StartInstance<infer Options> ? RequestContextOf<Instance> & ChainContribution<NonNullable<Options["functionMiddleware"]>>["context"] : Empty;
|
|
248
|
+
/** What the registered global request middleware adds, for the whole request. */
|
|
249
|
+
type GlobalRequestContext = RequestContextOf<RegisteredInstance>;
|
|
250
|
+
/** What every server function's `context` starts from. */
|
|
251
|
+
type GlobalFunctionContext = FunctionContextOf<RegisteredInstance>;
|
|
252
|
+
/**
|
|
253
|
+
* Declare the application's global middleware.
|
|
254
|
+
*
|
|
255
|
+
* The function is called once, the first time anything asks, so a middleware
|
|
256
|
+
* module that imports this one back is fully evaluated by then.
|
|
257
|
+
*/
|
|
258
|
+
declare function createStart<const Options extends StartOptions>(options: () => Options): StartInstance<Options>;
|
|
259
|
+
/** What the application declared, or nothing. */
|
|
260
|
+
declare function startOptions(): StartOptions;
|
|
261
|
+
/** Test seam. Not for application use. */
|
|
262
|
+
declare function clearStart(): void;
|
|
263
|
+
/**
|
|
264
|
+
* Headers and a status a handler asked for, merged into whatever is returned:
|
|
265
|
+
* the request event's response head, Solid's `ResponseStub`, under the name
|
|
266
|
+
* this package's helpers have always given it.
|
|
267
|
+
*/
|
|
268
|
+
type ResponseDraft = ResponseStub;
|
|
269
|
+
interface RequestContext {
|
|
270
|
+
request: Request;
|
|
271
|
+
/** What the handler has asked the response to carry. */
|
|
272
|
+
response: ResponseDraft;
|
|
273
|
+
/** Solid's `RequestEvent.locals`: what middleware hangs on the request. */
|
|
274
|
+
locals: RequestEventLocals;
|
|
275
|
+
/**
|
|
276
|
+
* The request's cookies, parsed ONCE.
|
|
277
|
+
*
|
|
278
|
+
* `getCookie` went through `parseCookies` every call, so a middleware that
|
|
279
|
+
* reads a session, a handler that reads a preference and a loader that reads a
|
|
280
|
+
* locale re-split the same header three times. The header is immutable for the
|
|
281
|
+
* life of the request, so the parse is too.
|
|
282
|
+
*/
|
|
283
|
+
cookies?: Record<string, string>;
|
|
284
|
+
/**
|
|
285
|
+
* Rules `@barqjs/css` registered while rendering THIS request.
|
|
286
|
+
*
|
|
287
|
+
* A server imports the application once and serves forever, so a module-scope
|
|
288
|
+
* rule belongs to every request and a rule a component body registers belongs
|
|
289
|
+
* to one. Kept here rather than in the css package because this is what knows
|
|
290
|
+
* which request is current — two in flight at once cannot take each other's.
|
|
291
|
+
*/
|
|
292
|
+
css?: Map<string, string>;
|
|
293
|
+
/**
|
|
294
|
+
* Reads every rule registered after THIS request's head sheet was serialised.
|
|
295
|
+
*
|
|
296
|
+
* What the page is owed once it has a head, in place of {@link css}: a rule
|
|
297
|
+
* ANOTHER request registered after this one's head is one this render can
|
|
298
|
+
* still use, as a class a module already holds, and it registers nothing
|
|
299
|
+
* when it does. So the line is the head and not who registered what.
|
|
300
|
+
*/
|
|
301
|
+
lateCss?: () => string;
|
|
302
|
+
/**
|
|
303
|
+
* What a server function's chain asked to send back, held for the request
|
|
304
|
+
* handler to put on the response.
|
|
305
|
+
*
|
|
306
|
+
* Here and not in a module-level variable for the reason this file opens
|
|
307
|
+
* with: two requests whose handlers settle in the same tick would each read
|
|
308
|
+
* whichever chain wrote last, and that is one caller's `sendContext` on
|
|
309
|
+
* another caller's response.
|
|
310
|
+
*/
|
|
311
|
+
sendContext?: Record<string, unknown>;
|
|
312
|
+
/** The server functions whose frames this request's mutation changed. */
|
|
313
|
+
invalidatedFrames?: Set<string>;
|
|
314
|
+
/**
|
|
315
|
+
* The sessions this request has opened, by cookie name.
|
|
316
|
+
*
|
|
317
|
+
* The request's cookie is what the browser HAD. A second `useSession` that
|
|
318
|
+
* read it again would start from before the first one's `update`, and its own
|
|
319
|
+
* `update` would then seal a session without that change over the top of it.
|
|
320
|
+
*/
|
|
321
|
+
sessions?: Map<string, Promise<OpenSession>>;
|
|
322
|
+
/**
|
|
323
|
+
* What the request middleware chain contributed with `next({ context })`.
|
|
324
|
+
*
|
|
325
|
+
* A server function's own chain starts from it, and a route handler is
|
|
326
|
+
* handed it, so a global middleware that resolved a session says so once.
|
|
327
|
+
*/
|
|
328
|
+
middlewareContext?: Record<string, unknown>;
|
|
329
|
+
/**
|
|
330
|
+
* Why this request must not be read, when it must not be.
|
|
331
|
+
*
|
|
332
|
+
* A PRERENDER holds a `Request` a build minted, so `getRequest()` would
|
|
333
|
+
* answer with a build machine's headers and a cookie jar that is empty for
|
|
334
|
+
* everyone. SvelteKit guards `url.search` alone and lets `cookies.get` and
|
|
335
|
+
* `request.headers` return null in silence; its own tracker records that as
|
|
336
|
+
* multi-day debugging. Refusing is the honest answer, and the message names
|
|
337
|
+
* what to do instead.
|
|
338
|
+
*/
|
|
339
|
+
refuse?: string;
|
|
340
|
+
}
|
|
341
|
+
/** A fresh, empty draft, one per request: Solid's `createResponseStub`. */
|
|
342
|
+
declare const createResponseDraft: () => ResponseDraft;
|
|
343
|
+
/**
|
|
344
|
+
* Send `@barqjs/css`'s render-time rules to whichever request is running.
|
|
345
|
+
*
|
|
346
|
+
* Installed once, by the generated server entry. Outside a request — module
|
|
347
|
+
* scope, and the browser — there is nothing to attribute a rule to, so it falls
|
|
348
|
+
* back to the package's own sheet, which is where a module-scope rule belongs.
|
|
349
|
+
*/
|
|
350
|
+
declare function collectRequestCss(): string;
|
|
351
|
+
/**
|
|
352
|
+
* The compiled module stylesheets a page made of `routes` reaches, in the order
|
|
353
|
+
* the page's modules run, when a dev server answered that, and `undefined`
|
|
354
|
+
* where none did: a build links its stylesheets instead of inlining them.
|
|
355
|
+
*
|
|
356
|
+
* A dev server imports the application once and renders every page from the
|
|
357
|
+
* one registry, so without this a page's head carried the rules of every module
|
|
358
|
+
* any earlier request had reached. `@barqjs/vite` installs the answer, read off
|
|
359
|
+
* its module graph in the order a build links the same modules' stylesheets.
|
|
360
|
+
*/
|
|
361
|
+
declare function devStylesheets(routes: readonly string[]): Promise<DevStylesheets | undefined> | undefined;
|
|
362
|
+
/** `@barqjs/css`'s `CssScope`, restated so this package does not import that one. */
|
|
363
|
+
interface DevStylesheets {
|
|
364
|
+
readonly keys: readonly string[];
|
|
365
|
+
readonly modules: ReadonlySet<string>;
|
|
366
|
+
}
|
|
367
|
+
/** `@barqjs/css`'s `CssSink`, restated so this package does not import that one. */
|
|
368
|
+
interface CssSink {
|
|
369
|
+
(key: string, rules: string): boolean;
|
|
370
|
+
head?(late: () => string): void;
|
|
371
|
+
owns?(key: string): boolean;
|
|
372
|
+
}
|
|
373
|
+
declare function installCssSink(setSink: (sink: CssSink) => void): void;
|
|
374
|
+
/**
|
|
375
|
+
* Run `body` with `request` as the ambient one, under the event
|
|
376
|
+
* `createRequestEvent` builds for it and `provideRequestEvent` enters.
|
|
377
|
+
*
|
|
378
|
+
* The DRAFT is the caller's to hold, because the caller is what builds the
|
|
379
|
+
* response and it does so after `body` has returned.
|
|
380
|
+
*/
|
|
381
|
+
declare function withRequest<T>(request: Request, body: () => T, options?: {
|
|
382
|
+
readonly refuse?: string;
|
|
383
|
+
readonly response?: ResponseDraft;
|
|
384
|
+
} | string): T;
|
|
385
|
+
/**
|
|
386
|
+
* The request this handler is running for.
|
|
387
|
+
*
|
|
388
|
+
* Throws outside one rather than returning undefined: a handler reading cookies
|
|
389
|
+
* off `undefined` is a bug that should surface where it happens, not resolve to
|
|
390
|
+
* "no session" and let the request through.
|
|
391
|
+
*/
|
|
392
|
+
declare function getRequest(): Request;
|
|
393
|
+
/**
|
|
394
|
+
* The request, or undefined outside one. For code that legitimately runs both ways.
|
|
395
|
+
*
|
|
396
|
+
* A refused context reads as ABSENT here rather than throwing: `peekRequest` is
|
|
397
|
+
* the "I may not be in a request" spelling, and a prerender is exactly that
|
|
398
|
+
* case. Code that must have one calls `getRequest` and gets the refusal.
|
|
399
|
+
*/
|
|
400
|
+
declare function peekRequest(): Request | undefined;
|
|
401
|
+
/**
|
|
402
|
+
* The draft, or `undefined` outside a request.
|
|
403
|
+
*
|
|
404
|
+
* Used by the two handlers to merge on the way out, and by nothing else. A
|
|
405
|
+
* REFUSED context still answers here: a prerender may not read the request, but
|
|
406
|
+
* a `head` or a loader that sets a cache header during one is describing the
|
|
407
|
+
* page rather than the requester, and the prerenderer can write it to disk.
|
|
408
|
+
*/
|
|
409
|
+
declare function peekResponseDraft(): ResponseDraft | undefined;
|
|
410
|
+
/**
|
|
411
|
+
* Say that this mutation changed what these server functions' frames show, so
|
|
412
|
+
* its answer carries those regions, rendered again, beside its value: single
|
|
413
|
+
* flight, one round trip. A frame the page has not mounted is not rendered.
|
|
414
|
+
* Outside a request it does nothing, as there is no answer to carry them.
|
|
415
|
+
*/
|
|
416
|
+
declare function invalidateFrames(...fns: readonly {
|
|
417
|
+
readonly meta: {
|
|
418
|
+
readonly id: string;
|
|
419
|
+
};
|
|
420
|
+
}[]): void;
|
|
421
|
+
/** Take the pending `sendContext`, leaving nothing behind for the next call. */
|
|
422
|
+
declare function takeSendContext(): Record<string, unknown>;
|
|
423
|
+
/**
|
|
424
|
+
* What this request's middleware chain has contributed, or an empty record
|
|
425
|
+
* outside a request. TanStack's name.
|
|
426
|
+
*
|
|
427
|
+
* Typed by what the registered global request middleware passes to
|
|
428
|
+
* `next({ context })`, each key optional: outside a request, or before the
|
|
429
|
+
* chain has reached the step that adds it, it is not there.
|
|
430
|
+
*/
|
|
431
|
+
declare function getGlobalStartContext(): OpenContext<Partial<GlobalRequestContext>>;
|
|
432
|
+
/** Record what the request middleware chain is contributing, for the rest of the request. */
|
|
433
|
+
declare function setRequestMiddlewareContext(context: Record<string, unknown>): void;
|
|
434
|
+
declare function getRequestHeaders(): Headers;
|
|
435
|
+
declare function getRequestHeader(name: string): string | undefined;
|
|
436
|
+
/** The request URL, parsed. */
|
|
437
|
+
declare function getRequestUrl(): URL;
|
|
438
|
+
/**
|
|
439
|
+
* How far `X-Forwarded-For` is believed.
|
|
440
|
+
*
|
|
441
|
+
* `true` takes the LEFTMOST entry, and is safe only when the edge proxy
|
|
442
|
+
* OVERWRITES the header. A proxy that appends, which is what most do, leaves
|
|
443
|
+
* whatever the client sent at the front: `X-Forwarded-For: 203.0.113.9` on the
|
|
444
|
+
* request arrives as `203.0.113.9, <real address>`, and the leftmost entry is
|
|
445
|
+
* the one the caller typed.
|
|
446
|
+
*
|
|
447
|
+
* `{ trustedProxies: n }` counts from the RIGHT instead: the entry the nth
|
|
448
|
+
* proxy in front of this process wrote, which is the address that proxy saw.
|
|
449
|
+
* Entries to its left were there before any trusted hop touched the header, so
|
|
450
|
+
* a forged prefix is never read. A header with fewer than `n` entries did not
|
|
451
|
+
* come through that chain and is ignored whole.
|
|
452
|
+
*/
|
|
453
|
+
type ForwardedForTrust = boolean | {
|
|
454
|
+
readonly trustedProxies: number;
|
|
455
|
+
};
|
|
456
|
+
/**
|
|
457
|
+
* The client's address, or `undefined`.
|
|
458
|
+
*
|
|
459
|
+
* `xForwardedFor` IS OFF BY DEFAULT and that is the whole design of this
|
|
460
|
+
* function. `X-Forwarded-For` is a header a client can send, so trusting it
|
|
461
|
+
* unconditionally lets any caller claim any address — and an address is exactly
|
|
462
|
+
* what rate limiting and audit logging key on. It is trustworthy only when a
|
|
463
|
+
* proxy you control overwrites it, which is a fact about the deployment that
|
|
464
|
+
* this process cannot discover. So it is opt-in, and the opt-in is per call.
|
|
465
|
+
*
|
|
466
|
+
* The LEFTMOST entry is taken when it is trusted, since that is the original
|
|
467
|
+
* client; every entry to its right was appended by a hop. {@link
|
|
468
|
+
* ForwardedForTrust} says when that is forgeable and what to pass instead.
|
|
469
|
+
*/
|
|
470
|
+
declare function getRequestIP(options?: {
|
|
471
|
+
readonly xForwardedFor?: ForwardedForTrust;
|
|
472
|
+
}): string | undefined;
|
|
473
|
+
/**
|
|
474
|
+
* The host, from the URL — and from `X-Forwarded-Host` only when asked.
|
|
475
|
+
*
|
|
476
|
+
* Same rule as `getRequestIP`, and the consequence is sharper: a host taken
|
|
477
|
+
* from an untrusted header and used to build an absolute URL is a host-header
|
|
478
|
+
* injection, which turns a password-reset link into a link to the attacker.
|
|
479
|
+
*/
|
|
480
|
+
declare function getRequestHost(options?: {
|
|
481
|
+
readonly xForwardedHost?: boolean;
|
|
482
|
+
}): string;
|
|
483
|
+
/** `http` or `https`. `X-Forwarded-Proto` only when asked, for the reason above. */
|
|
484
|
+
declare function getRequestProtocol(options?: {
|
|
485
|
+
readonly xForwardedProto?: boolean;
|
|
486
|
+
}): string;
|
|
487
|
+
/**
|
|
488
|
+
* Mark the draft's response as handed to the server: Solid's
|
|
489
|
+
* `commitResponseStub`. A streamed page goes on rendering after this, and so
|
|
490
|
+
* does a streamed server function, and a header one of them writes now changes
|
|
491
|
+
* nothing the browser receives.
|
|
492
|
+
*/
|
|
493
|
+
declare const markResponseSent: typeof commitResponseStub;
|
|
494
|
+
declare function getResponseHeaders(): Headers;
|
|
495
|
+
declare function getResponseHeader(name: string): string | undefined;
|
|
496
|
+
/**
|
|
497
|
+
* Set a response header. An array APPENDS each value, which is what a header
|
|
498
|
+
* that may legitimately repeat needs.
|
|
499
|
+
*/
|
|
500
|
+
declare function setResponseHeader(name: string, value: string | readonly string[]): void;
|
|
501
|
+
/**
|
|
502
|
+
* Add a value to a response header, keeping the ones already there.
|
|
503
|
+
*
|
|
504
|
+
* For a header that is a list: `Vary`, `Link`, `Cache-Control` built up by more
|
|
505
|
+
* than one caller. `setResponseHeader` replaces.
|
|
506
|
+
*/
|
|
507
|
+
declare function appendResponseHeader(name: string, value: string): void;
|
|
508
|
+
declare function setResponseHeaders(headers: Record<string, string>): void;
|
|
509
|
+
declare function removeResponseHeader(name: string): void;
|
|
510
|
+
/** Clear the named headers, or every header this request has drafted. */
|
|
511
|
+
declare function clearResponseHeaders(names?: readonly string[]): void;
|
|
512
|
+
declare function getResponseStatus(): number;
|
|
513
|
+
/**
|
|
514
|
+
* Set the status the framework's own response will carry.
|
|
515
|
+
*
|
|
516
|
+
* It does NOT override a `Response` a handler returns for itself — see
|
|
517
|
+
* `applyResponseDraft`, which says why.
|
|
518
|
+
*/
|
|
519
|
+
declare function setResponseStatus(status: number, statusText?: string): void;
|
|
520
|
+
/**
|
|
521
|
+
* Every cookie the REQUEST carried, by name.
|
|
522
|
+
*
|
|
523
|
+
* Parsed once and memoised on the context: the header cannot change for the life
|
|
524
|
+
* of the request, and re-splitting it per lookup made three readers three
|
|
525
|
+
* parses. The object is returned as it stands rather than copied, which is the
|
|
526
|
+
* point — copying it per call would put the allocation back.
|
|
527
|
+
*/
|
|
528
|
+
declare function getCookies(): Record<string, string>;
|
|
529
|
+
declare function getCookie(name: string): string | undefined;
|
|
530
|
+
/**
|
|
531
|
+
* Set a cookie on the response.
|
|
532
|
+
*
|
|
533
|
+
* APPENDS, because several cookies are several `Set-Cookie` lines and a
|
|
534
|
+
* browser keeps only the last of a set. Setting the same NAME twice in one
|
|
535
|
+
* request is the caller's business — the last one wins in the browser, as ever.
|
|
536
|
+
*/
|
|
537
|
+
declare function setCookie(name: string, value: string, options?: CookieOptions): void;
|
|
538
|
+
/**
|
|
539
|
+
* Delete a cookie.
|
|
540
|
+
*
|
|
541
|
+
* `path` and `domain` MUST match the ones it was set with, or the browser
|
|
542
|
+
* deletes nothing and keeps the original — silently. They are options here for
|
|
543
|
+
* exactly that reason rather than as decoration. With no `path` it names `/`,
|
|
544
|
+
* which is what `setCookie` gave a cookie that was set with none.
|
|
545
|
+
*/
|
|
546
|
+
declare function deleteCookie(name: string, options?: CookieOptions): void;
|
|
547
|
+
/**
|
|
548
|
+
* Fold a draft into a response, Solid's fold for `commitEventResponse` without
|
|
549
|
+
* the commit: `foldResponseStub` in `@barqjs/web` says what wins and why.
|
|
550
|
+
*
|
|
551
|
+
* It does NOT override the status of a `Response` a handler returned, because
|
|
552
|
+
* a handler that built a whole response has said what it wants.
|
|
553
|
+
*/
|
|
554
|
+
declare const applyResponseDraft: (response: Response, draft: ResponseDraft | undefined) => Response;
|
|
555
|
+
/**
|
|
556
|
+
* The status and text a framework-built response should carry.
|
|
557
|
+
*
|
|
558
|
+
* Separate from `applyResponseDraft` because the two answer different
|
|
559
|
+
* questions: this is "what did the handler ask for", used where the framework
|
|
560
|
+
* is deciding the status itself, and that one is "what does a returned response
|
|
561
|
+
* already say", where the handler has decided.
|
|
562
|
+
*/
|
|
563
|
+
declare function draftedStatus(draft: ResponseDraft | undefined, fallback: number): {
|
|
564
|
+
status: number;
|
|
565
|
+
statusText?: string;
|
|
566
|
+
};
|
|
567
|
+
/** One key's usage, as the store hands it back. */
|
|
568
|
+
interface RateLimitCount {
|
|
569
|
+
/** How many requests this key has made in the current window. */
|
|
570
|
+
readonly count: number;
|
|
571
|
+
/** When the current window ends, as a millisecond timestamp. */
|
|
572
|
+
readonly resetAt: number;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Where the counts live.
|
|
576
|
+
*
|
|
577
|
+
* ONE METHOD, and it is atomic by contract: `hit` must increment and return the
|
|
578
|
+
* new value in a single step. A `get` then `set` pair is a race — two requests
|
|
579
|
+
* read the same count and both write it — and a limiter that loses increments
|
|
580
|
+
* under load is one that stops working exactly when it is needed. Redis does
|
|
581
|
+
* this with `INCR` plus `PEXPIRE`; the memory store below does it by being
|
|
582
|
+
* single-threaded.
|
|
583
|
+
*/
|
|
584
|
+
interface RateLimitStore {
|
|
585
|
+
hit(key: string, windowMs: number): RateLimitCount | Promise<RateLimitCount>;
|
|
586
|
+
}
|
|
587
|
+
interface RateLimitOptions {
|
|
588
|
+
/** How many requests a key may make per window. */
|
|
589
|
+
readonly limit: number;
|
|
590
|
+
/** The window, in milliseconds. */
|
|
591
|
+
readonly windowMs: number;
|
|
592
|
+
/**
|
|
593
|
+
* What counts as one caller.
|
|
594
|
+
*
|
|
595
|
+
* There is no default, for the same reason the store has none: keying by IP is
|
|
596
|
+
* right for a public endpoint and wrong for an authenticated one behind a
|
|
597
|
+
* corporate NAT, where it limits a whole building as though it were one user.
|
|
598
|
+
* Key by user id where there is one, and by IP only where there is not.
|
|
599
|
+
*
|
|
600
|
+
* Returning `null` EXEMPTS the request — an internal caller, a health check.
|
|
601
|
+
*/
|
|
602
|
+
readonly key: () => string | null | Promise<string | null>;
|
|
603
|
+
readonly store: RateLimitStore;
|
|
604
|
+
/**
|
|
605
|
+
* What to answer when the limit is reached. A 429 with `Retry-After` by
|
|
606
|
+
* default, which is what a well-behaved client backs off on.
|
|
607
|
+
*/
|
|
608
|
+
readonly onLimit?: (info: RateLimitCount & {
|
|
609
|
+
readonly limit: number;
|
|
610
|
+
}) => Response;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* A store for ONE PROCESS. Named so the choice is visible at the call site.
|
|
614
|
+
*
|
|
615
|
+
* Correct for a single instance and wrong for every other deployment — see the
|
|
616
|
+
* header. It is here because "no store at all" would push everyone to write this
|
|
617
|
+
* same map badly, not because it is the one to reach for.
|
|
618
|
+
*
|
|
619
|
+
* Expired entries are swept by a `hit` rather than on a timer: a timer keeps
|
|
620
|
+
* the process alive on Node and has to be unref'd. A key is one caller and most
|
|
621
|
+
* callers are never seen again (a scan, a client rotating through an IPv6
|
|
622
|
+
* prefix), so an entry dropped only when its own key came back would stay for
|
|
623
|
+
* the life of the process and the map would grow with every address ever seen.
|
|
624
|
+
*
|
|
625
|
+
* The sweep runs at most once per the longest window in use, so an entry that
|
|
626
|
+
* has expired is gone by the second sweep after it was made, and the map holds
|
|
627
|
+
* what the last two such windows saw rather than everything since boot.
|
|
628
|
+
*/
|
|
629
|
+
declare function memoryStore(): RateLimitStore;
|
|
630
|
+
/**
|
|
631
|
+
* Key a limit by client address.
|
|
632
|
+
*
|
|
633
|
+
* `xForwardedFor` IS OFF BY DEFAULT and turning it on is a claim about the
|
|
634
|
+
* deployment: `X-Forwarded-For` is a header a CLIENT can send, so trusting it
|
|
635
|
+
* where no proxy overwrites it lets any caller pick their own bucket and the
|
|
636
|
+
* limit stops existing. See `getRequestIP`.
|
|
637
|
+
*
|
|
638
|
+
* `true` reads the LEFTMOST entry, which is the client only when the edge proxy
|
|
639
|
+
* overwrites the header. Behind a proxy that appends, pass
|
|
640
|
+
* `{ trustedProxies: n }` for the `n` proxies you run: it reads the entry the
|
|
641
|
+
* outermost of them wrote and ignores anything a caller put in front of it.
|
|
642
|
+
*
|
|
643
|
+
* A request with no address at all keys as `"unknown"`, which pools every such
|
|
644
|
+
* caller into one bucket — strict rather than exempt, because the alternative is
|
|
645
|
+
* a bucket an attacker can opt into by arranging to have no address.
|
|
646
|
+
*/
|
|
647
|
+
declare function byIP(options?: {
|
|
648
|
+
readonly xForwardedFor?: ForwardedForTrust;
|
|
649
|
+
}): () => string;
|
|
650
|
+
/**
|
|
651
|
+
* The middleware.
|
|
652
|
+
*
|
|
653
|
+
* It runs BEFORE the handler and before validation, which is the whole point:
|
|
654
|
+
* refusing after the body has been parsed is a refusal that already did the
|
|
655
|
+
* work. That ordering is `serverRpc`'s and the route dispatch's, and it is why
|
|
656
|
+
* this is a middleware rather than something a handler calls.
|
|
657
|
+
*
|
|
658
|
+
* A STORE THAT THROWS FAILS OPEN, deliberately and loudly. If Redis is down,
|
|
659
|
+
* refusing every request turns a limiter into the outage — so the request
|
|
660
|
+
* proceeds and the failure is reported. That is the right trade for a limiter
|
|
661
|
+
* and the wrong one for an authorization check, which is why this is not one.
|
|
662
|
+
*/
|
|
663
|
+
declare function rateLimit(options: RateLimitOptions): Middleware;
|
|
664
|
+
/**
|
|
665
|
+
* `Server-Timing` entries for the development server: how long a page's
|
|
666
|
+
* `beforeLoad`, its awaited loaders and its render took, and how long a server
|
|
667
|
+
* function ran. The browser's network panel shows them under Timing.
|
|
668
|
+
*
|
|
669
|
+
* Callers gate on `isDev`, a literal `false` in a production build, so none of
|
|
670
|
+
* this reaches a production response.
|
|
671
|
+
*/
|
|
672
|
+
/** A clock that starts now and reads off one `Server-Timing` entry per phase. */
|
|
673
|
+
interface ServerTiming {
|
|
674
|
+
/** Close the phase that began at the last call (or at the start) under `name`. */
|
|
675
|
+
phase(name: string, description: string): void;
|
|
676
|
+
/** The header value, or `""` when nothing was measured. */
|
|
677
|
+
header(): string;
|
|
678
|
+
}
|
|
679
|
+
declare function serverTiming(): ServerTiming;
|
|
680
|
+
/**
|
|
681
|
+
* What can cross the wire, as types: the check `createServerFn` runs on a
|
|
682
|
+
* handler's result and a validator's input, so a value the codec would refuse
|
|
683
|
+
* at runtime is a type error where it is written.
|
|
684
|
+
*
|
|
685
|
+
* The codec is seroval with `RegExp` refused and errors redacted
|
|
686
|
+
* (`@barqjs/server/codec`). It carries primitives, `bigint`, `undefined`,
|
|
687
|
+
* `Date`, `Error`, `Map`, `Set`, `Promise`, typed arrays, `ArrayBuffer`, arrays
|
|
688
|
+
* and plain objects, and throws on a function, a symbol, a `RegExp`, a `URL`, a
|
|
689
|
+
* `Blob` and an instance of a class it was not given an adapter for.
|
|
690
|
+
*
|
|
691
|
+
* A class instance whose type has no methods is structurally a plain object,
|
|
692
|
+
* and no type can tell the two apart, so that one is caught at runtime only.
|
|
693
|
+
* The same is true of a class a `createSerializationAdapter` carries: its type
|
|
694
|
+
* has methods, so it is a type error here, and `strict: { output: false }` is
|
|
695
|
+
* how a function that returns one says the adapter is there.
|
|
696
|
+
*/
|
|
697
|
+
type Leaf = string | number | boolean | bigint | null | undefined | void | Date | Error | ArrayBuffer | ArrayBufferView;
|
|
698
|
+
/** Classes the codec refuses whose types would otherwise be read member by member. */
|
|
699
|
+
type Refused = readonly [RegExp, "a RegExp"] | readonly [URL, "a URL"] | readonly [URLSearchParams, "a URLSearchParams"] | readonly [Blob, "a Blob"] | readonly [Headers, "a Headers"] | readonly [Request, "a Request"] | readonly [Response, "a Response, which crosses only as the whole result"] | readonly [ReadableStream, "a stream, which crosses only as the whole result"] | readonly [WeakMap<object, unknown>, "a WeakMap"] | readonly [WeakSet<object>, "a WeakSet"];
|
|
700
|
+
type RefusedName<Value> = Refused extends (infer Each) ? Each extends readonly [infer Class, infer Name] ? Value extends Class ? Name : never : never : never;
|
|
701
|
+
/** Deep enough for any payload written by hand; a recursive type stops here rather than looping. */
|
|
702
|
+
type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
703
|
+
/**
|
|
704
|
+
* Every place in `Value` the codec cannot carry, as a sentence naming where,
|
|
705
|
+
* or `never` when there is none.
|
|
706
|
+
*/
|
|
707
|
+
type WireProblem<Value, Path extends string = "the value", Left extends number = 10> = [Left] extends [never] ? never : 0 extends 1 & Value ? never : unknown extends Value ? never : Value extends Leaf ? never : Value extends symbol ? `${Path} is a symbol` : Value extends ((...args: never[]) => unknown) ? `${Path} is a function` : [RefusedName<Value>] extends [never] ? Value extends Promise<infer Settled> ? WireProblem<Settled, Path, Depth[Left]> : Value extends ReadonlyMap<infer Key, infer Item> ? WireProblem<Key, `${Path}'s keys`, Depth[Left]> | WireProblem<Item, `${Path}'s values`, Depth[Left]> : Value extends ReadonlySet<infer Item> ? WireProblem<Item, `${Path}'s members`, Depth[Left]> : Value extends readonly unknown[] ? WireProblem<Value[number], `${Path}[number]`, Depth[Left]> : Value extends object ? { [Key in keyof Value]-?: WireProblem<Value[Key], `${Path}.${Key & string}`, Depth[Left]>; }[keyof Value] : never : `${Path} is ${RefusedName<Value>}`;
|
|
708
|
+
/**
|
|
709
|
+
* A handler's result: a `Response` or a stream as the whole of it, a
|
|
710
|
+
* component, which crosses as a frame of its markup, or a value the codec
|
|
711
|
+
* carries. A stream's values are checked like any other.
|
|
712
|
+
*/
|
|
713
|
+
type ResultProblem<Result> = 0 extends 1 & Result ? never : Result extends Response ? never : Result extends ((props: never) => unknown) ? never : Result extends ReadableStream<infer Value> ? WireProblem<Value, "each value it streams"> : Result extends AsyncIterable<infer Value> ? WireProblem<Value, "each value it yields"> : WireProblem<Result, "the result">;
|
|
714
|
+
/** A validator's input: a value the codec carries, or a form where a form can be sent. */
|
|
715
|
+
type InputProblem<Input, Method> = 0 extends 1 & Input ? never : Input extends FormData ? Method extends "POST" ? never : "the input is a form, and a GET has no body to carry one" : WireProblem<Input, "the input">;
|
|
716
|
+
/**
|
|
717
|
+
* What a checked type must also be: anything, when there is no problem, and a
|
|
718
|
+
* type naming the problem, which nothing is, when there is one. The name is
|
|
719
|
+
* what the type error shows.
|
|
720
|
+
*/
|
|
721
|
+
type Crossable<Problem> = [Problem] extends [never] ? unknown : {
|
|
722
|
+
readonly "cannot cross the wire": Problem;
|
|
723
|
+
};
|
|
724
|
+
/** `strict`, as `createServerFn` takes it. */
|
|
725
|
+
type Strictness = boolean | {
|
|
726
|
+
readonly input?: boolean;
|
|
727
|
+
readonly output?: boolean;
|
|
728
|
+
};
|
|
729
|
+
/** Whether a side is checked: on unless `strict` or its side says `false`. */
|
|
730
|
+
type StrictOn<Strict, Side extends "input" | "output"> = Strict extends false ? false : Strict extends { readonly [Key in Side]: false; } ? false : true;
|
|
731
|
+
/** TanStack's `json`: a JSON `Response`, which a handler returns as its answer. */
|
|
732
|
+
declare function json(payload: unknown, init?: ResponseInit): Response;
|
|
733
|
+
declare function checkInput(built: {
|
|
734
|
+
readonly validator: Validator<unknown> | null;
|
|
735
|
+
}, raw: unknown,
|
|
736
|
+
/**
|
|
737
|
+
* Whether a MIDDLEWARE in the chain declared a validator.
|
|
738
|
+
*
|
|
739
|
+
* The refusal below asks "does anything expect input?", and before middleware
|
|
740
|
+
* validators existed the function's own was the only thing that could answer.
|
|
741
|
+
* A chain that validates has opened the channel just as surely, so refusing
|
|
742
|
+
* here would make `.validator(schema)` on a middleware unusable by any
|
|
743
|
+
* function that declares none of its own — which is the whole point of
|
|
744
|
+
* putting one there.
|
|
745
|
+
*/
|
|
746
|
+
chainValidates?: boolean): Promise<unknown>;
|
|
747
|
+
/**
|
|
748
|
+
* What a handler is handed, which is TanStack's shape:
|
|
749
|
+
* `.handler(async ({ data }) => …)`.
|
|
750
|
+
*
|
|
751
|
+
* `context` is what the middleware chain contributed, merged outermost-first,
|
|
752
|
+
* and typed by what each middleware passed to `next({ context })`.
|
|
753
|
+
* `signal` aborts with the request, so a handler can hand it to `fetch` and a
|
|
754
|
+
* client that navigates away stops paying for the work.
|
|
755
|
+
*/
|
|
756
|
+
interface HandlerContext<In, Context extends object = Empty> {
|
|
757
|
+
readonly data: In;
|
|
758
|
+
readonly context: OpenContext<Context>;
|
|
759
|
+
readonly signal: AbortSignal;
|
|
760
|
+
/** The method this function answers. */
|
|
761
|
+
readonly method: ServerFnMethod;
|
|
762
|
+
/** Which function is running, by the id it is mounted at. Empty when it is not mounted. */
|
|
763
|
+
readonly serverFnMeta: {
|
|
764
|
+
readonly id: string;
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
interface Built<Data, Out, Context extends object = Empty> {
|
|
768
|
+
validator: Validator<unknown> | null;
|
|
769
|
+
middleware: readonly Middleware[];
|
|
770
|
+
handler: (context: HandlerContext<Data, Context>) => Out | Promise<Out>;
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Where a server function's builder is: its chain, its own validator, its
|
|
774
|
+
* method, and whether what crosses the wire is checked.
|
|
775
|
+
*/
|
|
776
|
+
interface ServerFnState {
|
|
777
|
+
readonly chain: Contribution;
|
|
778
|
+
readonly own: Contribution;
|
|
779
|
+
readonly method: ServerFnMethod;
|
|
780
|
+
readonly strict: Strictness;
|
|
781
|
+
}
|
|
782
|
+
interface FreshServerFn<Method extends ServerFnMethod, Strict extends Strictness = true> extends ServerFnState {
|
|
783
|
+
readonly chain: NoContribution;
|
|
784
|
+
readonly own: NoContribution;
|
|
785
|
+
readonly method: Method;
|
|
786
|
+
readonly strict: Strict;
|
|
787
|
+
}
|
|
788
|
+
interface FnWithChain<State extends ServerFnState, Chain> extends ServerFnState {
|
|
789
|
+
readonly chain: Merged<State["chain"], ChainContribution<Chain>>;
|
|
790
|
+
readonly own: State["own"];
|
|
791
|
+
readonly method: State["method"];
|
|
792
|
+
readonly strict: State["strict"];
|
|
793
|
+
}
|
|
794
|
+
interface Validates<In, Out> extends Contribution {
|
|
795
|
+
readonly context: Empty;
|
|
796
|
+
readonly sent: Empty;
|
|
797
|
+
readonly clientContext: Empty;
|
|
798
|
+
readonly input: In;
|
|
799
|
+
readonly output: Out;
|
|
800
|
+
readonly validates: true;
|
|
801
|
+
}
|
|
802
|
+
interface FnWithValidator<State extends ServerFnState, In, Out> extends ServerFnState {
|
|
803
|
+
readonly chain: State["chain"];
|
|
804
|
+
readonly own: Validates<In, Out>;
|
|
805
|
+
readonly method: State["method"];
|
|
806
|
+
readonly strict: State["strict"];
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* What a validator's input must also be: anything, unless it holds something
|
|
810
|
+
* the codec cannot carry, when it must be a type naming that, which nothing is.
|
|
811
|
+
*/
|
|
812
|
+
type InputCheck<State extends ServerFnState, In> = StrictOn<State["strict"], "input"> extends true ? Crossable<InputProblem<In, State["method"]>> : unknown;
|
|
813
|
+
/** The same, for what a handler returns. */
|
|
814
|
+
type ResultCheck<State extends ServerFnState, Result> = StrictOn<State["strict"], "output"> extends true ? Crossable<ResultProblem<Result>> : unknown;
|
|
815
|
+
/**
|
|
816
|
+
* What the caller passes: the input of the first validator that runs, which is
|
|
817
|
+
* a middleware's when the chain validates. `undefined` when nothing validates,
|
|
818
|
+
* since a function that declares no validator accepts no argument.
|
|
819
|
+
*/
|
|
820
|
+
type CallerInput<State extends ServerFnState> = State["chain"]["validates"] extends true ? State["chain"]["input"] : State["own"]["validates"] extends true ? State["own"]["input"] : undefined;
|
|
821
|
+
/** What the handler is handed: the last validator's output. */
|
|
822
|
+
type HandlerData<State extends ServerFnState> = State["own"]["validates"] extends true ? State["own"]["output"] : State["chain"]["validates"] extends true ? State["chain"]["output"] : undefined;
|
|
823
|
+
/** What the handler's `context` holds: the global middleware's, then its own chain's. */
|
|
824
|
+
type HandlerContextOf<State extends ServerFnState> = GlobalFunctionContext & State["chain"]["context"];
|
|
825
|
+
/**
|
|
826
|
+
* The three-state discriminator, which is SvelteKit's idea and the best value
|
|
827
|
+
* in the survey: no validator means any argument is a 400, and opening the
|
|
828
|
+
* channel costs a schema or the literal `'unchecked'`.
|
|
829
|
+
*
|
|
830
|
+
* Every step is typed: the schema decides what a caller passes and what the
|
|
831
|
+
* handler is handed, and each middleware's `next({ context })` decides what the
|
|
832
|
+
* handler's `context` holds.
|
|
833
|
+
*/
|
|
834
|
+
interface ServerFnBuilder<State extends ServerFnState = ServerFnState> {
|
|
835
|
+
/**
|
|
836
|
+
* Middleware that runs before the handler, after any listed before. A server
|
|
837
|
+
* function in the list stands for the middleware it declared: its guards
|
|
838
|
+
* run here, its handler does not.
|
|
839
|
+
*/
|
|
840
|
+
middleware<const Chain extends readonly ChainStep[]>(chain: Chain): ServerFnBuilder<FnWithChain<State, Chain>>;
|
|
841
|
+
/**
|
|
842
|
+
* Open the input channel: a Standard Schema, a function that returns the
|
|
843
|
+
* validated value or throws, an object with a `parse`, or `"unchecked"`.
|
|
844
|
+
* What a caller passes is the schema's input, and what it produces is the
|
|
845
|
+
* type of `data` in the handler. The schema form is tried first: an arktype
|
|
846
|
+
* type is callable as well, and read as a function its input would be lost.
|
|
847
|
+
*/
|
|
848
|
+
validator<Schema extends StandardSchemaLike>(schema: Schema & InputCheck<State, StandardInput<Schema>>): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
|
|
849
|
+
validator<In, Out>(validate: ((input: In) => Out) & InputCheck<State, In>): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
|
|
850
|
+
validator<In, Out>(schema: {
|
|
851
|
+
readonly parse: (input: In) => Out;
|
|
852
|
+
} & InputCheck<State, In>): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
|
|
853
|
+
validator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
|
|
854
|
+
/** `validator` under the name TanStack's release candidates used. */
|
|
855
|
+
inputValidator<Schema extends StandardSchemaLike>(schema: Schema & InputCheck<State, StandardInput<Schema>>): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
|
|
856
|
+
inputValidator<In, Out>(validate: ((input: In) => Out) & InputCheck<State, In>): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
|
|
857
|
+
inputValidator<In, Out>(schema: {
|
|
858
|
+
readonly parse: (input: In) => Out;
|
|
859
|
+
} & InputCheck<State, In>): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;
|
|
860
|
+
inputValidator(unchecked: "unchecked"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;
|
|
861
|
+
/**
|
|
862
|
+
* The body. What it returns must cross the wire: a function, a symbol, or an
|
|
863
|
+
* instance of a class the codec refuses is a type error here, naming where
|
|
864
|
+
* it is. `createServerFn({ strict: false })` turns the check off.
|
|
865
|
+
*/
|
|
866
|
+
handler<Result>(fn: ((context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>) => Result | Promise<Result>) & ResultCheck<State, Result>): ServerFn<CallerInput<State>, Streamed<Awaited<Result>>, State["method"]> & Carries<State["chain"]>;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* What `createServerFn` accepts.
|
|
870
|
+
*
|
|
871
|
+
* `method` is TanStack's, with TanStack's default: `GET`. A function that
|
|
872
|
+
* writes declares `POST`, which is also the only method a form can reach. A
|
|
873
|
+
* link still cannot reach a `GET` one: every call carries the
|
|
874
|
+
* {@link RPC_CALLER} header, which nothing but script can set, and the server
|
|
875
|
+
* refuses a `GET` without it.
|
|
876
|
+
*/
|
|
877
|
+
interface ServerFnOptions<Method extends ServerFnMethod = ServerFnMethod, Strict extends Strictness = Strictness> {
|
|
878
|
+
readonly method?: Method;
|
|
879
|
+
/**
|
|
880
|
+
* Whether the types refuse an input or a result the codec cannot carry. On
|
|
881
|
+
* by default; `false` turns both off, `{ input: false }` or
|
|
882
|
+
* `{ output: false }` one side. The codec still refuses at runtime what it
|
|
883
|
+
* cannot carry: this only says the author knows, as for a class a
|
|
884
|
+
* `createSerializationAdapter` carries.
|
|
885
|
+
*/
|
|
886
|
+
readonly strict?: Strict;
|
|
887
|
+
/**
|
|
888
|
+
* The answer is the same for every caller with the same arguments, so a
|
|
889
|
+
* `live` call shares one rendering with every other connection asking the
|
|
890
|
+
* same thing: Solid 2.0's `broadcast`. The handler still runs per call, as the
|
|
891
|
+
* gate it is (an auth check, a redirect), and a joiner's own answer is closed
|
|
892
|
+
* unread. The shared rendering belongs to no request: it reads no cookie,
|
|
893
|
+
* header or session, and it stops when its last connection goes.
|
|
894
|
+
*/
|
|
895
|
+
readonly broadcast?: boolean;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Author a server function. The value this returns is replaced by the compiler
|
|
899
|
+
* on both sides, so what it does when compiled by nothing is only the
|
|
900
|
+
* uncompiled-development path: it runs the handler in-process.
|
|
901
|
+
*/
|
|
902
|
+
declare function createServerFn<Method extends ServerFnMethod = "GET", const Strict extends Strictness = true>(options?: ServerFnOptions<Method, Strict>): ServerFnBuilder<FreshServerFn<Method, Strict>>;
|
|
903
|
+
/**
|
|
904
|
+
* The server half. The compiler emits this in a module compiled for the server,
|
|
905
|
+
* with the real handler and the id it assigned.
|
|
906
|
+
*
|
|
907
|
+
* `In` is what a caller passes and `Data` what the handler is handed; the
|
|
908
|
+
* validator is what turns one into the other, at runtime.
|
|
909
|
+
*/
|
|
910
|
+
declare function serverRpc<In, Out, Data = In, Context extends object = Empty, Method extends ServerFnMethod = "POST">(meta: ServerFnMeta, built: Built<Data, Out, Context>): ServerFn<In, Streamed<Awaited<Out>>, Method>;
|
|
911
|
+
/**
|
|
912
|
+
* The middleware chain a server function carries, by REFERENCE.
|
|
913
|
+
*
|
|
914
|
+
* `serverRpc` attaches `built` to the function object, so the chain is the real
|
|
915
|
+
* array of closures rather than something re-derived. That matters: a build
|
|
916
|
+
* cannot read a chain out of source. `.middleware([m])`, `.middleware([...c])`
|
|
917
|
+
* and `.middleware(c.filter(Boolean))` are all runtime expressions, and
|
|
918
|
+
* `Middleware` is an anonymous closure with no build-visible identity — so the
|
|
919
|
+
* only sound comparison is `===` against the same closure the route declared.
|
|
920
|
+
*
|
|
921
|
+
* Empty for a client stub, which carries no chain because it carries no handler.
|
|
922
|
+
*/
|
|
923
|
+
declare function middlewareOf(fn: AnyServerFn): readonly Middleware[];
|
|
924
|
+
export { getRequestHeaders as $, RateLimitCount as A, Session as At, appendResponseHeader as B, CookieOptions as Bt, InputProblem as C, Register as Ct, WireProblem as D, clearStart as Dt, Strictness as E, StartOptions as Et, rateLimit as F, getSession as Ft, deleteCookie as G, clearResponseHeaders as H, parseCookies as Ht, DevStylesheets as I, sealSession as It, getCookie as J, devStylesheets as K, ForwardedForTrust as L, unsealSession as Lt, RateLimitStore as M, SessionData as Mt, byIP as N, SessionManager as Nt, ServerTiming as O, createStart as Ot, memoryStore as P, clearSession as Pt, getRequestHeader as Q, RequestContext as R, updateSession as Rt, Crossable as S, GlobalRequestContext as St, StrictOn as T, StartInstance as Tt, collectRequestCss as U, serializeCookie as Ut, applyResponseDraft as V, deleteCookieLine as Vt, createResponseDraft as W, getGlobalStartContext as X, getCookies as Y, getRequest as Z, createSerializationAdapter as _, setResponseStatus as _t, FreshServerFn as a, getResponseHeaders as at, middlewareOf as b, FunctionContextOf as bt, HandlerData as c, invalidateFrames as ct, SerializationAdapter as d, peekResponseDraft as dt, getRequestHost as et, ServerFnBuilder as f, removeResponseHeader as ft, checkInput as g, setResponseHeaders as gt, Validates as h, setResponseHeader as ht, FnWithValidator as i, getResponseHeader as it, RateLimitOptions as j, SessionConfig as jt, serverTiming as k, startOptions as kt, InputCheck as l, markResponseSent as lt, ServerFnState as m, setRequestMiddlewareContext as mt, CallerInput as n, getRequestProtocol as nt, HandlerContext as o, getResponseStatus as ot, ServerFnOptions as p, setCookie as pt, draftedStatus as q, FnWithChain as r, getRequestUrl as rt, HandlerContextOf as s, installCssSink as st, AnySerializationAdapter as t, getRequestIP as tt, ResultCheck as u, peekRequest as ut, createServerFn as v, takeSendContext as vt, ResultProblem as w, RequestContextOf as wt, serverRpc as x, GlobalFunctionContext as xt, json as y, withRequest as yt, ResponseDraft as z, useSession as zt };
|
|
925
|
+
//# sourceMappingURL=index-B4o7eyCr.d.ts.map
|