rossa 0.0.5 → 0.1.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 +1 -1
- package/README.md +295 -1
- package/dist/index.d.ts +2066 -235
- package/dist/index.js +74 -3
- package/package.json +21 -18
package/dist/index.d.ts
CHANGED
|
@@ -1,253 +1,853 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
type obj<T> = Record<string, T>;
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* A custom Map implementation that provides additional utility methods for working with objects and maps.
|
|
9
|
-
*
|
|
10
|
-
* @template K - The type of the keys in the map.
|
|
11
|
-
* @template V - The type of the values in the map.
|
|
12
|
-
*/
|
|
13
|
-
declare class Mapper<K, V> extends Map<K, V> {
|
|
14
|
-
obj(obj?: object | null): void;
|
|
15
|
-
map(map: Mapper<K, V>): void;
|
|
16
|
-
ass<T>(key: K, obj: T): void;
|
|
17
|
-
lacks(key: K): boolean;
|
|
18
|
-
init(key: K, val: V): V;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
declare class log {
|
|
22
|
-
static set i(a: any);
|
|
23
|
-
static set e(a: any);
|
|
24
|
-
static set w(a: any);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
declare class Time {
|
|
28
|
-
date: Date;
|
|
29
|
-
constructor(dateMS?: number);
|
|
30
|
-
delta(date2?: number | null, _Date?: boolean): number | Date;
|
|
31
|
-
timed(time?: {
|
|
32
|
-
year?: number;
|
|
33
|
-
month?: number;
|
|
34
|
-
day?: number;
|
|
35
|
-
hour?: number;
|
|
36
|
-
minute?: number;
|
|
37
|
-
second?: number;
|
|
38
|
-
}): Date;
|
|
39
|
-
static delta(date1: number, date2?: number | null): number;
|
|
40
|
-
static local(date: number): string;
|
|
41
|
-
static get now(): number;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
declare class session {
|
|
45
|
-
session: obj<string>;
|
|
46
|
-
jwt: obj<string>;
|
|
47
|
-
timedJWT: ServerSide;
|
|
48
|
-
}
|
|
49
|
-
declare class ResponseSession implements session {
|
|
50
|
-
__session?: ServerSide;
|
|
51
|
-
__jwt?: ServerSide;
|
|
52
|
-
get session(): ServerSide;
|
|
53
|
-
set session(sesh: ServerSide);
|
|
54
|
-
get jwt(): ServerSide;
|
|
55
|
-
set jwt(jwt: ServerSide);
|
|
56
|
-
get timedJWT(): ServerSide;
|
|
57
|
-
setServerSession(rsp: ResponseSession): void;
|
|
58
|
-
}
|
|
59
|
-
declare const auths: {
|
|
60
|
-
session<T>(...arg: any[]): any;
|
|
61
|
-
jwt<T>(...arg: any[]): any;
|
|
62
|
-
jwt_refresh<T>(...arg: any[]): any;
|
|
63
|
-
};
|
|
1
|
+
import { Server, SocketAddress, BunFile, ServerWebSocket, WebSocketHandler, SQL } from 'bun';
|
|
2
|
+
import { McpServer, McpRequestContext } from '@modelcontextprotocol/server';
|
|
3
|
+
export { McpRequestContext, McpServer } from '@modelcontextprotocol/server';
|
|
64
4
|
|
|
65
|
-
declare class
|
|
66
|
-
|
|
67
|
-
server?: Server | undefined;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
5
|
+
declare class req {
|
|
6
|
+
readonly request: Request;
|
|
7
|
+
readonly server?: Server<unknown> | undefined;
|
|
8
|
+
private readonly fileDetector;
|
|
9
|
+
params: Record<string, string>;
|
|
10
|
+
private _url?;
|
|
11
|
+
private _query?;
|
|
12
|
+
private _cookies?;
|
|
13
|
+
private _formData?;
|
|
14
|
+
private _json?;
|
|
15
|
+
private _txt?;
|
|
16
|
+
constructor(request: Request, server?: Server<unknown> | undefined, fileDetector?: (path: string) => boolean);
|
|
17
|
+
/**
|
|
18
|
+
* Caches the raw text.
|
|
19
|
+
* By resolving text first, we prevent Bun's "body stream already locked" error
|
|
20
|
+
* if you attempt to read .text() and .json() in the same request lifecycle.
|
|
21
|
+
*/
|
|
22
|
+
text(): Promise<string>;
|
|
23
|
+
/**
|
|
24
|
+
* Parses JSON from the cached text to prevent stream locks.
|
|
25
|
+
*/
|
|
26
|
+
json<T extends Record<string, any>>(): Promise<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Parses FormData. Cannot be mixed with .text() or .json() for multipart binary uploads.
|
|
29
|
+
*/
|
|
74
30
|
form(): Promise<FormData>;
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
jwtv: string;
|
|
78
|
-
refreshjwt: string;
|
|
79
|
-
}>;
|
|
80
|
-
upgradeConnection(data?: obj<any>): boolean;
|
|
81
|
-
get auth(): string | undefined;
|
|
82
|
-
get accept(): string | null;
|
|
83
|
-
get contentType(): string | null;
|
|
31
|
+
get url(): URL;
|
|
32
|
+
get query(): Record<string, string>;
|
|
84
33
|
get cookies(): Map<string, string>;
|
|
34
|
+
get auth(): string | undefined;
|
|
35
|
+
get method(): string;
|
|
85
36
|
get headers(): Headers;
|
|
86
|
-
|
|
87
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Helper to grab a specific header safely.
|
|
39
|
+
*/
|
|
40
|
+
header(key: string): string | null;
|
|
41
|
+
get ip(): SocketAddress | null;
|
|
88
42
|
get path(): string;
|
|
89
|
-
get
|
|
90
|
-
get fullPath(): string;
|
|
91
|
-
get parsed(): string[];
|
|
92
|
-
get searchParams(): URLSearchParams;
|
|
93
|
-
get range(): string | undefined;
|
|
94
|
-
get isEventStream(): boolean | undefined;
|
|
43
|
+
get isForm(): boolean;
|
|
95
44
|
get isWSS(): boolean;
|
|
45
|
+
get isEventStream(): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Infers if the route is a static file by checking for an extension in the last URL segment.
|
|
48
|
+
*/
|
|
96
49
|
get isFile(): boolean;
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
50
|
+
getAuthCredentials(): Promise<{
|
|
51
|
+
sid: string;
|
|
52
|
+
jwt: string;
|
|
53
|
+
refresh: string;
|
|
54
|
+
}>;
|
|
55
|
+
upgrade<T = any>(data?: T): boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type HeaderObject$1 = Record<string, string>;
|
|
59
|
+
|
|
60
|
+
declare class HeadBase {
|
|
61
|
+
protected data: HeaderObject$1;
|
|
62
|
+
constructor(initialData?: HeaderObject$1);
|
|
63
|
+
protected _add(key: string, value: string): this;
|
|
64
|
+
add(key: string, value: string): this;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** * Layer 1: Security
|
|
68
|
+
*/
|
|
69
|
+
declare class SecurityHead extends HeadBase {
|
|
70
|
+
/** * Prevents clickjacking by forbidding the page from being framed.
|
|
71
|
+
* Options: 'DENY', 'SAMEORIGIN'
|
|
72
|
+
*/
|
|
73
|
+
frameOptions(option?: "DENY" | "SAMEORIGIN"): this;
|
|
74
|
+
/** * Forces browser to stick to the declared Content-Type.
|
|
75
|
+
*/
|
|
76
|
+
noSniff(): this;
|
|
77
|
+
/** * Forces HTTPS for a set duration (default 1 year).
|
|
78
|
+
*/
|
|
79
|
+
hsts(maxAge?: number): this;
|
|
80
|
+
/** * Basic CSP: Only allow scripts/styles from your own origin.
|
|
81
|
+
*/
|
|
82
|
+
csp(policy?: string): this;
|
|
83
|
+
/** Referrer policy for privacy */
|
|
84
|
+
referrer(policy?: "no-referrer" | "origin" | "strict-origin-when-cross-origin"): this;
|
|
85
|
+
/** * NEW: Cross-Origin Opener Policy (Isolates your tab from others)
|
|
86
|
+
*/
|
|
87
|
+
coop(policy?: "same-origin" | "same-origin-allow-popups" | "unsafe-none"): this;
|
|
88
|
+
/** * NEW: Cross-Origin Embedder Policy
|
|
89
|
+
*/
|
|
90
|
+
coep(policy?: "require-corp" | "unsafe-none"): this;
|
|
91
|
+
/** * Modern replacement for Feature-Policy.
|
|
92
|
+
* e.g., "camera=(), microphone=()"
|
|
93
|
+
*/
|
|
94
|
+
permissions(policy: string): this;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** * Layer 2: Traffic (Extends SecurityHead)
|
|
98
|
+
*/
|
|
99
|
+
declare class Traffic extends SecurityHead {
|
|
100
|
+
cors(origin?: string): this;
|
|
101
|
+
cache(seconds?: number): this;
|
|
102
|
+
noCache(): this;
|
|
103
|
+
etag(val: string): this;
|
|
104
|
+
/** * Set custom timing metrics for browser dev tools.
|
|
105
|
+
*/
|
|
106
|
+
serverTiming(name: string, durMs: number, desc?: string): this;
|
|
107
|
+
/** Sets standard rate limit headers */
|
|
108
|
+
rateLimit(limit: number, remaining: number, resetSeconds: number): this;
|
|
109
|
+
/** Sets the Retry-After header (useful for 429 or 503) */
|
|
110
|
+
retryAfter(seconds: number | string): this;
|
|
111
|
+
/**
|
|
112
|
+
* Sets the date/time after which the response is considered stale.
|
|
113
|
+
*/
|
|
114
|
+
expires(date: Date): this;
|
|
115
|
+
/**
|
|
116
|
+
* Indicates the date and time at which the resource was last modified.
|
|
117
|
+
*/
|
|
118
|
+
lastModified(date: Date): this;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** * Layer 3: Auth (Extends Traffic)
|
|
122
|
+
*/
|
|
123
|
+
declare class AuthHead extends Traffic {
|
|
124
|
+
/** * Sets the WWW-Authenticate header for 401 responses.
|
|
125
|
+
* e.g., head.authenticate("Bearer", "realm=\"access\"")
|
|
126
|
+
*/
|
|
127
|
+
authenticate(scheme: "Bearer" | "Basic" | "Digest", details?: string): this;
|
|
128
|
+
/** * Sets the Proxy-Authenticate header.
|
|
129
|
+
*/
|
|
130
|
+
proxyAuthenticate(value: string): this;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type CommonMimeType = "text/plain" | "text/html" | "text/css" | "text/javascript" | "application/json" | "application/xml" | "application/x-www-form-urlencoded" | "multipart/form-data" | "audio/mpeg" | "video/mp4" | (string & {});
|
|
134
|
+
/** * Layer 3: Auth (Extends AuthHead)
|
|
135
|
+
*/
|
|
136
|
+
declare class Contents extends AuthHead {
|
|
137
|
+
/**
|
|
138
|
+
* Bulk setter for content headers.
|
|
139
|
+
* Accepts an object where keys match semantic method names.
|
|
140
|
+
*/
|
|
141
|
+
content(options: {
|
|
142
|
+
length?: number;
|
|
143
|
+
type?: CommonMimeType;
|
|
144
|
+
encoding?: "gzip" | "deflate" | "br" | "identity" | "zstd";
|
|
145
|
+
disposition?: {
|
|
146
|
+
type: "inline" | "attachment";
|
|
147
|
+
filename?: string;
|
|
148
|
+
};
|
|
149
|
+
language?: string;
|
|
150
|
+
range?: string;
|
|
151
|
+
location?: string;
|
|
152
|
+
md5?: string;
|
|
153
|
+
}): this;
|
|
154
|
+
/** The size of the response body in bytes */
|
|
155
|
+
contentLength(bytes: number): this;
|
|
156
|
+
/** The MD5 hash of the body to verify data integrity */
|
|
157
|
+
contentMD5(hash: string): this;
|
|
158
|
+
/** content type */
|
|
159
|
+
contentType(mime: CommonMimeType): this;
|
|
160
|
+
/** * Defines the compression algorithm used.
|
|
161
|
+
* Common: 'gzip', 'deflate', 'br' (Brotli)
|
|
162
|
+
*/
|
|
163
|
+
contentEncoding(encoding: "gzip" | "deflate" | "br" | "identity" | "zstd"): this;
|
|
164
|
+
/** * Where the content actually lives if this is a partial view
|
|
165
|
+
* or a reference to another location.
|
|
166
|
+
*/
|
|
167
|
+
contentLocation(url: string): this;
|
|
168
|
+
/** Used to indicate the range of bytes in a partial response (Status 206) */
|
|
169
|
+
contentRange(range: string): this;
|
|
170
|
+
/** Specifies the security level or sensitivity of the content */
|
|
171
|
+
contentSecurity(value: string): this;
|
|
172
|
+
/** * Controls if content is displayed inline or as an attachment (download).
|
|
173
|
+
* @param type 'inline' or 'attachment'
|
|
174
|
+
* @param filename Optional name for the downloaded file
|
|
175
|
+
*/
|
|
176
|
+
disposition(type?: "inline" | "attachment", filename?: string): this;
|
|
177
|
+
/** Tells the client which request headers were used to decide the response */
|
|
178
|
+
vary(...headers: string[]): this;
|
|
179
|
+
/** Suggests a language for the content */
|
|
180
|
+
language(lang: string): this;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** * Layer 5: Auth (Extends Traffic)
|
|
184
|
+
*/
|
|
185
|
+
declare class Utils extends Contents {
|
|
186
|
+
location(url: string): this;
|
|
187
|
+
/**
|
|
188
|
+
* Specifically sets the Access-Control-Allow-Origin header.
|
|
189
|
+
*/
|
|
190
|
+
origin(value?: string): this;
|
|
191
|
+
/**
|
|
192
|
+
* The date and time at which the message was originated.
|
|
193
|
+
*/
|
|
194
|
+
date(date?: Date): this;
|
|
195
|
+
/**
|
|
196
|
+
* Contains information about the software used by the origin server.
|
|
197
|
+
*/
|
|
198
|
+
server(name: string): this;
|
|
199
|
+
/**
|
|
200
|
+
* Controls whether the network connection stays open after the transaction finishes.
|
|
201
|
+
* Common: 'keep-alive', 'close'
|
|
202
|
+
*/
|
|
203
|
+
connection(value: "keep-alive" | "close"): this;
|
|
204
|
+
/**
|
|
205
|
+
* Sets parameters for a persistent connection (timeout and max requests).
|
|
206
|
+
* e.g., head.keepAlive("timeout=5, max=1000")
|
|
207
|
+
*/
|
|
208
|
+
keepAlive(value: string | number): this;
|
|
209
|
+
cookie(name: string, value: string, options?: CookieOptions): this;
|
|
210
|
+
}
|
|
211
|
+
interface CookieOptions {
|
|
212
|
+
/**
|
|
213
|
+
* Max-Age in seconds, or a Date from which seconds will be derived.
|
|
214
|
+
*/
|
|
215
|
+
maxAge?: number | Date;
|
|
216
|
+
/**
|
|
217
|
+
* Expires as Date, timestamp, or preformatted date string.
|
|
218
|
+
*/
|
|
219
|
+
expires?: Date | number | string;
|
|
220
|
+
path?: string | null;
|
|
221
|
+
domain?: string;
|
|
222
|
+
secure?: boolean;
|
|
223
|
+
httpOnly?: boolean;
|
|
224
|
+
sameSite?: "Lax" | "Strict" | "None" | null;
|
|
225
|
+
/**
|
|
226
|
+
* Internal only – not serialized; used if you actually measure size.
|
|
227
|
+
*/
|
|
228
|
+
maxSize?: number;
|
|
229
|
+
syncExpires?: boolean;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** * Final Master Class (The one you actually use)
|
|
233
|
+
*/
|
|
234
|
+
declare class Heder extends Utils {
|
|
235
|
+
/**
|
|
236
|
+
* Creates a deep copy of the current builder for reuse.
|
|
237
|
+
*/
|
|
238
|
+
get copy(): Heder;
|
|
239
|
+
use(plugin: HederPlugin): this;
|
|
240
|
+
merge(_heder: Heder | HeaderObject$1): this;
|
|
241
|
+
static init(initial?: HeaderObject$1): Heder;
|
|
242
|
+
static get $(): Heder;
|
|
243
|
+
get done(): HeaderObject$1;
|
|
244
|
+
}
|
|
245
|
+
type HederPlugin = (h: Heder) => void;
|
|
246
|
+
|
|
247
|
+
declare class ServerSide<TData extends Record<string, any> = Record<string, any>> {
|
|
248
|
+
sid: string;
|
|
249
|
+
data: TData;
|
|
250
|
+
isNew: boolean;
|
|
251
|
+
isModified: boolean;
|
|
252
|
+
isReadOnly: boolean;
|
|
253
|
+
isFound: boolean;
|
|
254
|
+
length: number;
|
|
255
|
+
constructor(sid?: string, initialData?: Partial<TData>, readOnly?: boolean, isNew?: boolean, isFound?: boolean);
|
|
256
|
+
/**
|
|
257
|
+
* Generates the dynamic Proxy trapped instance.
|
|
258
|
+
* We use `this & TData` so TypeScript knows this object contains both
|
|
259
|
+
* the class methods AND the dynamic user data.
|
|
260
|
+
*/
|
|
261
|
+
get session(): any;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
declare class ctx<Args extends Record<string, string> = Record<string, string>, SessionType = ServerSide, BodyType = unknown> {
|
|
265
|
+
readonly res: res;
|
|
266
|
+
params: Args;
|
|
267
|
+
/**
|
|
268
|
+
* Custom header maker
|
|
269
|
+
*/
|
|
270
|
+
headr: Heder;
|
|
271
|
+
url: URL;
|
|
272
|
+
data: Record<string, any>;
|
|
273
|
+
jwtData: Record<string, any>;
|
|
274
|
+
session?: SessionType;
|
|
275
|
+
body?: BodyType;
|
|
276
|
+
query: Record<string, string | string[] | undefined>;
|
|
277
|
+
form: Record<string, any>;
|
|
278
|
+
readonly req: req;
|
|
279
|
+
method: string;
|
|
280
|
+
methods: string[];
|
|
281
|
+
clientDirectory: string;
|
|
282
|
+
constructor(res: res);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
type ErrorConfig = {
|
|
286
|
+
code?: number | undefined;
|
|
287
|
+
message?: string | undefined;
|
|
288
|
+
redirect?: string | undefined;
|
|
289
|
+
headers?: Record<string, string> | undefined;
|
|
290
|
+
error?: (ctx: ctx) => Response;
|
|
291
|
+
maxSize?: number | undefined;
|
|
292
|
+
};
|
|
293
|
+
declare function sendError(config: ErrorConfig, details?: any): Response;
|
|
294
|
+
|
|
295
|
+
type ContentEncodingType = "gzip" | "deflate" | "br" | "zstd" | "none";
|
|
296
|
+
|
|
297
|
+
interface StreamPayload {
|
|
298
|
+
/** Provides a recovery ID for automatic reconnection tracking. */
|
|
299
|
+
id?: string | number;
|
|
300
|
+
/** Contains the actual payload (must be the last field in the packet). */
|
|
301
|
+
data: string | Record<string, any>;
|
|
302
|
+
/** Names the event so the client can use addEventListener('name', ...). */
|
|
303
|
+
event?: string;
|
|
304
|
+
/** Tells the client how many milliseconds to wait before reconnecting (default is 3000ms). */
|
|
305
|
+
retry?: number;
|
|
306
|
+
/** Forcefully end and close the stream. */
|
|
307
|
+
end?: boolean;
|
|
308
|
+
/** State function to return the value as an argument in the next interval. */
|
|
309
|
+
fn?: () => any;
|
|
310
|
+
}
|
|
311
|
+
type StreamPushFn = (prevFnResult?: any) => StreamPayload;
|
|
312
|
+
|
|
313
|
+
declare class StaticFileServer {
|
|
314
|
+
private readonly absoluteClientPath;
|
|
315
|
+
private readonly additionalExtensions;
|
|
316
|
+
private readonly SMALL_FILE_THRESHOLD;
|
|
317
|
+
private readonly CACHE_TTL;
|
|
318
|
+
constructor(resolvedAssetRootPath: string, additionalExtensions?: string[]);
|
|
319
|
+
isFile(path: string): boolean;
|
|
320
|
+
/**
|
|
321
|
+
* Serves the request from this server's root.
|
|
322
|
+
*
|
|
323
|
+
* @param lookupPath - Optional already-decoded path to resolve instead of the
|
|
324
|
+
* request pathname. Scoped mounts use it to serve a prefix-stripped path;
|
|
325
|
+
* when omitted the request URL is decoded exactly as before.
|
|
326
|
+
*/
|
|
327
|
+
serve(req: req, res: res, lookupPath?: string): Promise<Response>;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
type HeaderObject = Record<string, string>;
|
|
331
|
+
interface RespoOptions {
|
|
332
|
+
/** Compression encoding to apply to generated response bodies. */
|
|
333
|
+
encoding?: ContentEncodingType;
|
|
334
|
+
}
|
|
335
|
+
interface FileMeta {
|
|
336
|
+
/** Byte length of a raw `Uint8Array` file. */
|
|
337
|
+
size: number;
|
|
338
|
+
/** MIME type of a raw `Uint8Array` file. */
|
|
339
|
+
type: string;
|
|
340
|
+
}
|
|
341
|
+
/** Builds HTTP responses while retaining status, headers, and encoding settings. */
|
|
342
|
+
declare class res {
|
|
343
|
+
readonly req: req;
|
|
344
|
+
private readonly staticServer;
|
|
345
|
+
private readonly server?;
|
|
346
|
+
private _code;
|
|
347
|
+
private _headers;
|
|
348
|
+
private _encoding?;
|
|
349
|
+
/**
|
|
350
|
+
* Creates a response builder for the current request.
|
|
351
|
+
*
|
|
352
|
+
* @param options - Optional response encoding settings.
|
|
353
|
+
* @param req - The request context used by file serving and streaming helpers.
|
|
354
|
+
* @param staticServer - Static file server used by {@link fileServer}.
|
|
355
|
+
* @param server - Optional Bun server. Streaming helpers need it to disable
|
|
356
|
+
* Bun's request timeout for the long-lived connection.
|
|
357
|
+
*/
|
|
358
|
+
constructor(options: RespoOptions | undefined, req: req, staticServer: StaticFileServer, server?: Bun.Server<undefined> | undefined);
|
|
359
|
+
/**
|
|
360
|
+
* Sets the HTTP response status code.
|
|
361
|
+
* * ### 1xx: Informational
|
|
362
|
+
* - **101 (Switching Protocols):** Switching to WebSockets.
|
|
363
|
+
* * ### 2xx: Success
|
|
364
|
+
* - **200 (OK):** Request succeeded.
|
|
365
|
+
* - **201 (Created):** Resource created (e.g., new database record).
|
|
366
|
+
* - **202 (Accepted):** Request accepted but still processing (Async).
|
|
367
|
+
* - **204 (No Content):** Success, but returning no body (e.g., OPTIONS/DELETE).
|
|
368
|
+
* - **206 (Partial Content):** Range request success (Streaming).
|
|
369
|
+
* * ### 3xx: Redirection
|
|
370
|
+
* - **301 (Moved Permanently):** Permanent URL change.
|
|
371
|
+
* - **302 (Found):** Temporary URL change.
|
|
372
|
+
* - **304 (Not Modified):** Use the browser's cached version.
|
|
373
|
+
* - **307/308:** Temporary/Permanent redirect (preserves POST data).
|
|
374
|
+
* * ### 4xx: Client Errors
|
|
375
|
+
* - **400 (Bad Request):** Invalid syntax or malformed data.
|
|
376
|
+
* - **401 (Unauthorized):** Authentication is missing or invalid.
|
|
377
|
+
* - **403 (Forbidden):** Authenticated but lacks permissions.
|
|
378
|
+
* - **404 (Not Found):** Resource doesn't exist.
|
|
379
|
+
* - **405 (Method Not Allowed):** e.g., POSTing to a GET-only route.
|
|
380
|
+
* - **406 (Not Acceptable):** Requested format (Accept header) not supported.
|
|
381
|
+
* - **408 (Request Timeout):** Client took too long to send data.
|
|
382
|
+
* - **409 (Conflict):** State conflict (e.g., duplicate username).
|
|
383
|
+
* - **410 (Gone):** Resource is permanently deleted.
|
|
384
|
+
* - **413 (Payload Too Large):** Request body exceeds limits.
|
|
385
|
+
* - **415 (Unsupported Media Type):** e.g., sending XML when API expects JSON.
|
|
386
|
+
* - **416 (Range Not Satisfiable):** Invalid byte range requested.
|
|
387
|
+
* - **422 (Unprocessable Entity):** Validation error (correct syntax, wrong data).
|
|
388
|
+
* - **429 (Too Many Requests):** Rate limit exceeded.
|
|
389
|
+
* * ### 5xx: Server Errors
|
|
390
|
+
* - **500 (Internal Server Error):** General server crash.
|
|
391
|
+
* - **501 (Not Implemented):** Server doesn't support the requested method.
|
|
392
|
+
* - **502 (Bad Gateway):** Upstream server (proxy) sent an invalid response.
|
|
393
|
+
* - **503 (Service Unavailable):** Server is overloaded or down for maintenance.
|
|
394
|
+
* - **504 (Gateway Timeout):** Upstream server took too long to respond.
|
|
395
|
+
* * @param code - The numeric HTTP status code.
|
|
396
|
+
*/
|
|
397
|
+
status(code: number): this;
|
|
398
|
+
/**
|
|
399
|
+
* Sets the Content-Encoding header and internal state.
|
|
400
|
+
*/
|
|
401
|
+
/**
|
|
402
|
+
* Sets or clears the response content encoding.
|
|
403
|
+
*
|
|
404
|
+
* @param type - Encoding to use, or `"none"` to remove the encoding header.
|
|
405
|
+
* @returns This response builder for chaining.
|
|
406
|
+
*/
|
|
407
|
+
encode(type: ContentEncodingType): this;
|
|
408
|
+
/**
|
|
409
|
+
* Consumes the Head builder object.
|
|
410
|
+
*/
|
|
411
|
+
/**
|
|
412
|
+
* Adds or replaces response headers. `Vary` values are merged without
|
|
413
|
+
* duplicates so callers can add negotiation dimensions incrementally.
|
|
414
|
+
*
|
|
415
|
+
* @param input - A header builder or a map of header names to values.
|
|
416
|
+
* @returns This response builder for chaining.
|
|
417
|
+
*/
|
|
418
|
+
header(input: Heder | HeaderObject): this;
|
|
419
|
+
private _assemble;
|
|
420
|
+
/**
|
|
421
|
+
* Creates a response with no body using the supplied status or current status.
|
|
422
|
+
*
|
|
423
|
+
* @param status - Optional status code for this response.
|
|
424
|
+
*/
|
|
425
|
+
null(status?: number): Response;
|
|
426
|
+
/** Serializes a value as JSON and returns an `application/json` response. */
|
|
427
|
+
json(data: Record<string, any>): Response;
|
|
428
|
+
/** Returns an HTML response with a UTF-8 content type. */
|
|
429
|
+
html(body: string): Response;
|
|
430
|
+
/** Returns a plain text response with a UTF-8 content type. */
|
|
431
|
+
text(body?: string): Response;
|
|
432
|
+
/**
|
|
433
|
+
* Standardized Error Response.
|
|
434
|
+
* Automatically sets the status code and returns a JSON error structure.
|
|
435
|
+
* * ### Common Error Codes:
|
|
436
|
+
* - **400 (Bad Request):** The server cannot process the request due to client error (e.g., malformed syntax).
|
|
437
|
+
* - **401 (Unauthorized):** Authentication is required and has failed or has not yet been provided.
|
|
438
|
+
* - **403 (Forbidden):** The server understood the request but refuses to authorize it.
|
|
439
|
+
* - **404 (Not Found):** The requested resource could not be found.
|
|
440
|
+
* - **405 (Method Not Allowed):** The request method is known by the server but has been disabled.
|
|
441
|
+
* - **409 (Conflict):** Request conflicts with current state (e.g., duplicate entry).
|
|
442
|
+
* - **413 (Payload Too Large):** The request entity is larger than limits defined by server.
|
|
443
|
+
* - **415 (Unsupported Media Type):** The media format of the requested data is not supported.
|
|
444
|
+
* - **422 (Unprocessable Entity):** Valid syntax but contains semantic errors (e.g., validation failed).
|
|
445
|
+
* - **429 (Too Many Requests):** The user has sent too many requests in a given amount of time.
|
|
446
|
+
* - **500 (Internal Server Error):** A generic error message, given when an unexpected condition was encountered.
|
|
447
|
+
* - **503 (Service Unavailable):** The server is currently unable to handle the request (overloaded or down).
|
|
448
|
+
* @param code - The numeric HTTP error status code.
|
|
449
|
+
* @param message - A human-readable explanation of the error.
|
|
450
|
+
* @param details - Optional object or array containing specific error details (e.g., field-level validation).
|
|
451
|
+
*/
|
|
452
|
+
error(code: number, message: string | Record<string, any>): Response;
|
|
453
|
+
/**
|
|
454
|
+
* Standardized Success Response.
|
|
455
|
+
* Automatically sets the status code and returns a JSON success structure.
|
|
456
|
+
* * ### Common Success Codes:
|
|
457
|
+
* - **200 (OK):** The request was successful and the payload is returned in the response body.
|
|
458
|
+
* - **201 (Created):** The request succeeded and a new resource was created (e.g., successful insert or register).
|
|
459
|
+
* - **202 (Accepted):** The request was received but has not yet been acted upon (e.g., background job started).
|
|
460
|
+
* - **204 (No Content):** The request succeeded but there is no payload to return (e.g., successful delete).
|
|
461
|
+
* * @param code - The numeric HTTP success status code (defaults to 200).
|
|
462
|
+
* @param data - Optional primary payload or resource data returned to the client.
|
|
463
|
+
* @param message - Optional human-readable confirmation message.
|
|
464
|
+
*/
|
|
465
|
+
success(code?: number, data?: any, message?: string): Response;
|
|
466
|
+
/**
|
|
467
|
+
* Creates an empty redirect response with a `Location` header.
|
|
468
|
+
*
|
|
469
|
+
* @param url - Destination URL placed in the `Location` header.
|
|
470
|
+
* @param status - Redirect status code; defaults to `302`.
|
|
471
|
+
*/
|
|
472
|
+
redirect(url: string, status?: number): Response;
|
|
473
|
+
/**
|
|
474
|
+
* use fileserver to serve the file securely.
|
|
475
|
+
*/
|
|
476
|
+
/** Serves the current request through the configured secure static file server. */
|
|
477
|
+
fileServer(): Promise<Response>;
|
|
478
|
+
/**
|
|
479
|
+
* Universal file handler supporting BunFile and raw Uint8Array.
|
|
480
|
+
*/
|
|
481
|
+
/**
|
|
482
|
+
* Sends a Bun file or byte array, with optional metadata and extra headers.
|
|
483
|
+
* Bun files support byte range requests; byte arrays do not. A missing Bun
|
|
484
|
+
* file returns `404`, and an invalid range returns `416`.
|
|
485
|
+
*
|
|
486
|
+
* @param file - File handle or bytes to send.
|
|
487
|
+
* @param meta - MIME type and size metadata for a byte array.
|
|
488
|
+
* @param extraHeaders - Additional headers to apply before sending.
|
|
489
|
+
*/
|
|
490
|
+
file(file: BunFile | Uint8Array, meta?: FileMeta, extraHeaders?: Heder | HeaderObject): Promise<Response>;
|
|
491
|
+
/**
|
|
492
|
+
* Returns Server-Sent Events (SSE) response helpers.
|
|
493
|
+
*
|
|
494
|
+
* SSE keeps an HTTP response open so the server can push events to a client.
|
|
495
|
+
* Use the returned helper that best fits the producer:
|
|
496
|
+
*
|
|
497
|
+
* - `asyncStream` consumes an async generator and emits each yielded value as
|
|
498
|
+
* a `data:` message. Objects are JSON-encoded; other values are stringified.
|
|
499
|
+
* - `eStream` calls a push function on an interval and supports SSE `id`,
|
|
500
|
+
* `event`, `retry`, and end-of-stream fields in its returned payload.
|
|
501
|
+
* - `readableStream` gives a producer the stream controller for fully manual
|
|
502
|
+
* framing and lifecycle control.
|
|
503
|
+
*
|
|
504
|
+
* Each helper returns a `text/event-stream` response and disables Bun's
|
|
505
|
+
* request timeout for the current request. If this response builder was
|
|
506
|
+
* created without a Bun server, its helpers return a `500` response.
|
|
507
|
+
* Consumers can listen in browsers with `EventSource`; SSE is one-way, from
|
|
508
|
+
* server to client. Use WebSockets when clients also need to send live data.
|
|
509
|
+
*/
|
|
510
|
+
get event(): {
|
|
511
|
+
/**
|
|
512
|
+
* Creates an SSE stream from an async generator.
|
|
513
|
+
*
|
|
514
|
+
* Every yielded value becomes one `data: ...` message followed by a blank
|
|
515
|
+
* line. Objects are JSON-encoded; primitives are converted to strings.
|
|
516
|
+
* Returning from the generator closes the stream. If the client
|
|
517
|
+
* disconnects, the generator's `return()` method is called when present.
|
|
518
|
+
*
|
|
519
|
+
* @param generator - Factory that returns the async iterable of messages.
|
|
520
|
+
* @returns An SSE response, or a `500` response when no Bun server is set.
|
|
521
|
+
*
|
|
522
|
+
* @example
|
|
523
|
+
* ```ts
|
|
524
|
+
* return res.event.asyncStream(async function* () {
|
|
525
|
+
* yield { status: "connected" };
|
|
526
|
+
* while (true) {
|
|
527
|
+
* yield { time: new Date().toISOString() };
|
|
528
|
+
* await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
529
|
+
* }
|
|
530
|
+
* });
|
|
531
|
+
* ```
|
|
532
|
+
*/
|
|
533
|
+
asyncStream: (generator: () => AsyncGenerator<any, void, unknown>) => Response;
|
|
534
|
+
/**
|
|
535
|
+
* Creates an interval-driven SSE stream.
|
|
536
|
+
*
|
|
537
|
+
* The callback returns a payload containing `data` and optional SSE
|
|
538
|
+
* metadata (`id`, `event`, `retry`), an `end` flag, or an `fn` callback
|
|
539
|
+
* whose result is passed to the next invocation. The interval is clamped
|
|
540
|
+
* to at least one second. Setting `end: true` closes the stream before
|
|
541
|
+
* emitting that callback's payload. On client disconnect, the interval
|
|
542
|
+
* is cleared and `onCancel` is invoked.
|
|
543
|
+
*
|
|
544
|
+
* @param push - Produces the next event payload, optionally using the
|
|
545
|
+
* previous `fn` result.
|
|
546
|
+
* @param options - Interval in milliseconds and disconnect callback.
|
|
547
|
+
* @returns An SSE response, or a `500` response when no Bun server is set.
|
|
548
|
+
*
|
|
549
|
+
* @example
|
|
550
|
+
* ```ts
|
|
551
|
+
* return res.event.eStream(
|
|
552
|
+
* () => ({ event: "heartbeat", data: { time: Date.now() } }),
|
|
553
|
+
* { interval: 5000 },
|
|
554
|
+
* );
|
|
555
|
+
* ```
|
|
556
|
+
*/
|
|
557
|
+
eStream: (push: StreamPushFn, { interval, onCancel, }?: {
|
|
558
|
+
interval?: number;
|
|
559
|
+
onCancel?: () => void;
|
|
560
|
+
}) => Response;
|
|
561
|
+
/**
|
|
562
|
+
* Creates an SSE response with direct control over its stream controller.
|
|
563
|
+
*
|
|
564
|
+
* The producer is responsible for writing valid SSE frames (for example,
|
|
565
|
+
* `data: hello\\n\\n`) and closing or erroring the controller when done.
|
|
566
|
+
* `onCancel` runs if the client cancels or disconnects.
|
|
567
|
+
*
|
|
568
|
+
* @param producer - Writes to the response stream using its controller.
|
|
569
|
+
* @param onCancel - Optional cleanup callback for client cancellation.
|
|
570
|
+
* @returns An SSE response, or a `500` response when no Bun server is set.
|
|
571
|
+
*/
|
|
572
|
+
readableStream: (producer: (controller: ReadableStreamDefaultController<any>) => void | Promise<void>, onCancel?: () => void) => Response;
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
declare const METHODS: readonly ["GET", "POST", "PUT", "HEAD", "DELETE", "PATCH", "EVENT", "OPTIONS"];
|
|
577
|
+
type methodsKeys = (typeof METHODS)[number];
|
|
578
|
+
type handlerGuard = {
|
|
579
|
+
guards: any[];
|
|
580
|
+
handler: Function;
|
|
581
|
+
};
|
|
582
|
+
type methodGuards = Partial<Record<methodsKeys, handlerGuard>>;
|
|
583
|
+
declare class Methods {
|
|
120
584
|
[key: string]: any;
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
585
|
+
/**
|
|
586
|
+
* The GET method requests a representation of the specified resource.
|
|
587
|
+
* Requests using GET should only retrieve data.
|
|
588
|
+
*/
|
|
589
|
+
get?({ req, res }: ctx): Promise<Response> | Response;
|
|
590
|
+
/**
|
|
591
|
+
* The POST method is used to submit an entity to the specified resource,
|
|
592
|
+
* often causing a change in state or side effects on the server.
|
|
593
|
+
*/
|
|
594
|
+
post?({ req, res }: ctx): Promise<Response> | Response;
|
|
595
|
+
/**
|
|
596
|
+
* The PUT method replaces all current representations of the target
|
|
597
|
+
* resource with the request payload.
|
|
598
|
+
*/
|
|
599
|
+
put?({ req, res }: ctx): Promise<Response> | Response;
|
|
600
|
+
/**
|
|
601
|
+
* The HEAD method asks for a response identical to that of a GET request,
|
|
602
|
+
* but without the response body.
|
|
603
|
+
*/
|
|
604
|
+
head?({ req, res }: ctx): Promise<Response> | Response;
|
|
605
|
+
/**
|
|
606
|
+
* The DELETE method deletes the specified resource.
|
|
607
|
+
*/
|
|
608
|
+
delete?({ req, res }: ctx): Promise<Response> | Response;
|
|
609
|
+
/**
|
|
610
|
+
* The OPTIONS method is used to describe the communication options
|
|
611
|
+
* for the target resource (essential for CORS preflight).
|
|
612
|
+
*/
|
|
613
|
+
options({ res, methods }: ctx): Response;
|
|
614
|
+
/**
|
|
615
|
+
* The PATCH method is used to apply partial modifications to a resource.
|
|
616
|
+
*/
|
|
617
|
+
patch?({ req, res }: ctx): Promise<Response> | Response;
|
|
618
|
+
/**
|
|
619
|
+
* Specialized handler for Server-Sent Events (SSE).
|
|
620
|
+
* Used for real-time, uni-directional streaming from server to client.
|
|
621
|
+
*/
|
|
622
|
+
event?({ req, res }: ctx): Promise<Response> | Response;
|
|
143
623
|
}
|
|
144
624
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
625
|
+
type TopicPublishStatus = "sent" | "backpressured" | "dropped" | "oversize";
|
|
626
|
+
interface TopicPublishResult {
|
|
627
|
+
topic: string;
|
|
628
|
+
status: TopicPublishStatus;
|
|
629
|
+
}
|
|
630
|
+
declare class subManager {
|
|
631
|
+
private ws;
|
|
152
632
|
id: string;
|
|
153
|
-
|
|
633
|
+
constructor(ws: ServerWebSocket<any>, nickname?: string);
|
|
634
|
+
subscribe(topic: string): void;
|
|
635
|
+
unsubscribe(topic: string): void;
|
|
636
|
+
cleanup(): void;
|
|
637
|
+
unregister(): void;
|
|
638
|
+
setAdmin(topic: string): void;
|
|
639
|
+
isAdmin(topic: string): boolean;
|
|
640
|
+
isSubscribed(topic: string): boolean;
|
|
641
|
+
setTopicConfig(topic: string, config?: WssConfig): void;
|
|
642
|
+
/** Publishes to unique topics and returns Bun's outcome for each topic. */
|
|
643
|
+
broadcast(topics: string[], data: any): TopicPublishResult[];
|
|
644
|
+
}
|
|
645
|
+
declare class WssManager {
|
|
646
|
+
private connections;
|
|
647
|
+
private topicConfigs;
|
|
648
|
+
private topicRegistry;
|
|
649
|
+
private memberTopics;
|
|
650
|
+
private roomAdmins;
|
|
651
|
+
private defaultTopicConfig;
|
|
652
|
+
/** 1. Lifecycle: Register/Unregister Connections */
|
|
653
|
+
register(ws: ServerWebSocket<any>, nickname?: string): string;
|
|
654
|
+
getMemberDetails(topic: string): {
|
|
655
|
+
id: string;
|
|
656
|
+
userId: any;
|
|
657
|
+
nickname: any;
|
|
658
|
+
}[];
|
|
659
|
+
/** Get all topics a specific user is currently in */
|
|
660
|
+
getUserTopics(id: string): string[];
|
|
661
|
+
get(topic: string): {
|
|
662
|
+
id: string;
|
|
663
|
+
userId: any;
|
|
664
|
+
nickname: any;
|
|
665
|
+
}[];
|
|
666
|
+
unregister(id: string): void;
|
|
667
|
+
/** 2. Subscription Management */
|
|
668
|
+
subscribe(id: string, topic: string): void;
|
|
669
|
+
isSubscribed(id: string, topic: string): boolean;
|
|
670
|
+
unsubscribe(id: string, topic: string): void;
|
|
671
|
+
/** 3. Admin & Role Management */
|
|
672
|
+
setAdmin(id: string, topic: string): void;
|
|
673
|
+
isAdmin(id: string, topic: string): boolean;
|
|
674
|
+
/** 4. Security & Config Helpers */
|
|
675
|
+
isPayloadTooLarge(topic: string, byteLength: number): boolean;
|
|
676
|
+
/** Helper to get the correct config for any topic */
|
|
677
|
+
private getConfigForTopic;
|
|
678
|
+
setTopicConfig(topic: string, config?: WssConfig): void;
|
|
679
|
+
/** Broadcast to an array of topics */
|
|
680
|
+
/**
|
|
681
|
+
* Publishes an encoded payload to each unique topic within that topic's
|
|
682
|
+
* configured byte limit. Bun's `-1` result is reported as backpressured,
|
|
683
|
+
* `0` as dropped, and a positive result as sent.
|
|
684
|
+
*/
|
|
685
|
+
broadcastToTopics(ws: ServerWebSocket<any>, topics: string[], data: unknown): TopicPublishResult[];
|
|
686
|
+
/** Ensures all topics for a client are cleaned up on disconnect */
|
|
687
|
+
cleanup(id: string): void;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
declare const WSSMAN: WssManager;
|
|
691
|
+
interface WssConfig {
|
|
692
|
+
maxClients?: number;
|
|
693
|
+
maxPayloadSize?: number;
|
|
694
|
+
}
|
|
695
|
+
/** Fixed-window incoming message limit applied independently to each socket. */
|
|
696
|
+
interface WssMessageRateLimit {
|
|
697
|
+
/** Maximum messages accepted from each connection during one window. */
|
|
154
698
|
max: number;
|
|
155
|
-
|
|
156
|
-
|
|
699
|
+
/** Fixed-window duration in milliseconds. */
|
|
700
|
+
windowMs: number;
|
|
701
|
+
}
|
|
702
|
+
type wssMessage<T extends Record<string, any> = Record<string, any>> = {
|
|
703
|
+
text: string;
|
|
704
|
+
json: T;
|
|
705
|
+
topic?: string | undefined;
|
|
706
|
+
};
|
|
707
|
+
|
|
708
|
+
declare class Websocket<T extends Record<string, any> = Record<string, any>> {
|
|
709
|
+
ws: ServerWebSocket<{}>;
|
|
710
|
+
manager: subManager;
|
|
711
|
+
/** Data populated by WebSocket route guards before the connection upgrades. */
|
|
712
|
+
contextData: Record<string, any>;
|
|
713
|
+
data: T;
|
|
714
|
+
constructor();
|
|
157
715
|
open(): Promise<void> | void;
|
|
158
|
-
message(
|
|
716
|
+
message({ text, json, topic }: wssMessage): Promise<void> | void;
|
|
717
|
+
/** Called when Bun has drained buffered outbound data for this connection. */
|
|
718
|
+
drain(): Promise<void> | void;
|
|
159
719
|
close(code: number, reason: string): Promise<void> | void;
|
|
160
|
-
set send(message: string | Bun.BufferSource
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
declare
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
* - /url/\<string:hell>
|
|
180
|
-
*/
|
|
181
|
-
route: (path: string) => <T extends typeof response>(f?: T | undefined) => T | undefined;
|
|
182
|
-
wss: (path: string, config?: wssConfig) => <T extends typeof websocket>(f?: T | undefined) => T | undefined;
|
|
183
|
-
error: (...codes: number[]) => <T extends typeof response>(f?: T | undefined) => T | undefined;
|
|
184
|
-
folders: (...folder: ([
|
|
185
|
-
string,
|
|
186
|
-
{
|
|
187
|
-
requireSession?: boolean;
|
|
188
|
-
}
|
|
189
|
-
] | string)[]) => void;
|
|
190
|
-
redirect: (url: string, headers?: obj<string>) => Response;
|
|
191
|
-
}
|
|
192
|
-
declare class Formula extends routeCFG {
|
|
193
|
-
dir: string;
|
|
194
|
-
apt: string;
|
|
195
|
-
base: string;
|
|
196
|
-
protected _statics?: obj<Response>;
|
|
197
|
-
constructor(dir?: string, options?: yveOptions);
|
|
198
|
-
protected _base(str: string): string;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
interface yveOptions {
|
|
202
|
-
dir?: string;
|
|
203
|
-
clientDir?: string;
|
|
204
|
-
envPath?: string;
|
|
205
|
-
session?: Auth;
|
|
206
|
-
base?: string;
|
|
207
|
-
}
|
|
208
|
-
type for_srver = Partial<Serve> & dev & {
|
|
209
|
-
fn?: (port: number) => void;
|
|
720
|
+
set send(message: string | Bun.BufferSource);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Router entry
|
|
725
|
+
* @param basePath - /url/:hello
|
|
726
|
+
* @returns
|
|
727
|
+
*/
|
|
728
|
+
declare function route(basePath?: string): <TTarget extends abstract new (...args: any[]) => Methods>(target: TTarget, context: ClassDecoratorContext<any>) => void | TTarget;
|
|
729
|
+
/**
|
|
730
|
+
* Router entry
|
|
731
|
+
* @param basePath - /url/:hello
|
|
732
|
+
* @returns
|
|
733
|
+
*/
|
|
734
|
+
declare function wss(basePath?: string): <TTarget extends abstract new (...args: any[]) => Websocket<Record<string, any>>>(target: TTarget, context: ClassDecoratorContext<any>) => void | TTarget;
|
|
735
|
+
|
|
736
|
+
type GuardFactoryHandler<TOptions = void, ExtraCfg = Record<string, any>> = (ctx: ctx, next: () => Promise<Response> | Response, options: TOptions, Config: ErrorConfig & ExtraCfg) => Promise<Response>;
|
|
737
|
+
type GuardConfig = ErrorConfig & {
|
|
738
|
+
id?: string | undefined;
|
|
210
739
|
};
|
|
211
|
-
type
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
740
|
+
type BaseConfig = Omit<ErrorConfig, "code">;
|
|
741
|
+
type GuardReturnType = {
|
|
742
|
+
(ctx: ctx, next: () => Promise<Response> | Response): Promise<Response>;
|
|
743
|
+
_middlewareId: string;
|
|
744
|
+
id: string;
|
|
745
|
+
};
|
|
746
|
+
declare function createGuard<TOptions = void, ExtraCfg = Record<string, unknown>>(handler: GuardFactoryHandler<TOptions, ExtraCfg>, defaultConfig?: GuardConfig): (options?: TOptions, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
747
|
+
|
|
748
|
+
type Class = new (...args: any[]) => any;
|
|
749
|
+
type RouteHandler = (ctx: ctx) => Promise<Response> | Response;
|
|
750
|
+
interface WssBaseController {
|
|
751
|
+
open?(ws: any): void;
|
|
752
|
+
message(ws: any, message: string | Uint8Array): void;
|
|
753
|
+
close?(ws: any, code: number, reason: string): void;
|
|
754
|
+
}
|
|
755
|
+
interface WssRouteConfig {
|
|
756
|
+
path: string;
|
|
757
|
+
regex: RegExp;
|
|
758
|
+
paramNames: string[];
|
|
759
|
+
instance: typeof Websocket<{}>;
|
|
760
|
+
guards: GuardReturnType[];
|
|
761
|
+
}
|
|
762
|
+
interface HttpRouteConfig {
|
|
763
|
+
path: string;
|
|
764
|
+
regex: RegExp;
|
|
765
|
+
controller: Class;
|
|
766
|
+
methods: methodGuards;
|
|
767
|
+
methodKeys: string[];
|
|
768
|
+
paramNames: string[];
|
|
769
|
+
}
|
|
770
|
+
interface HttpRouteMatch extends Partial<handlerGuard> {
|
|
771
|
+
controller?: Class;
|
|
772
|
+
methodKeys?: string[];
|
|
773
|
+
params: Record<string, string>;
|
|
774
|
+
}
|
|
775
|
+
declare class RouterManager {
|
|
776
|
+
protected globalBasePath: string;
|
|
777
|
+
httpRoutes: HttpRouteConfig[];
|
|
778
|
+
wssRoutes: WssRouteConfig[];
|
|
779
|
+
protected globalGuards: any[];
|
|
780
|
+
private registeredSignatures;
|
|
781
|
+
private programmaticRoutes;
|
|
782
|
+
constructor(globalBasePath?: string);
|
|
783
|
+
use(...guards: GuardReturnType[]): void;
|
|
784
|
+
private fullRoutePath;
|
|
785
|
+
private compiler;
|
|
786
|
+
private checkSignature;
|
|
787
|
+
registerWSS(...ControllerClass: (typeof Websocket<{}>)[]): void;
|
|
788
|
+
register(...ControllerClass: (typeof Methods)[]): void;
|
|
789
|
+
/**
|
|
790
|
+
* Registers a programmatic HTTP route without a decorated controller class.
|
|
791
|
+
* Used by framework features such as MCP endpoints; a matching programmatic
|
|
792
|
+
* route can be replaced, while a decorated HTTP route at the same path is a
|
|
793
|
+
* collision.
|
|
794
|
+
*/
|
|
795
|
+
protected registerHandlerRoute(path: string, handlers: Partial<Record<methodsKeys, RouteHandler>>, options?: {
|
|
796
|
+
replace?: boolean;
|
|
797
|
+
}): void;
|
|
798
|
+
protected matchWSS(url: string): Partial<WssRouteConfig & {
|
|
799
|
+
params: HttpRouteMatch["params"];
|
|
800
|
+
}>;
|
|
801
|
+
protected match(method: methodsKeys, url: string): HttpRouteMatch;
|
|
802
|
+
printRoutes(): void;
|
|
803
|
+
/** Returns registered HTTP paths, including the base path, with parameter colons removed. */
|
|
804
|
+
getPaths(): string[];
|
|
248
805
|
}
|
|
249
806
|
|
|
250
|
-
|
|
807
|
+
/**
|
|
808
|
+
* Base class for decorator-driven MCP endpoints.
|
|
809
|
+
*
|
|
810
|
+
* The framework creates a fresh `McpServer` for each request (named after the
|
|
811
|
+
* controller class) and calls {@link McpController.build} before serving it.
|
|
812
|
+
* Combine it with the `@mcp("/path")` decorator and register it with
|
|
813
|
+
* `app.registerMCP(MyController)`.
|
|
814
|
+
*/
|
|
815
|
+
declare abstract class McpController {
|
|
816
|
+
/**
|
|
817
|
+
* Builds the MCP server: register tools, resources, and prompts here.
|
|
818
|
+
* Runs once per request via the SDK factory, so async setup is supported.
|
|
819
|
+
*/
|
|
820
|
+
abstract build(server: McpServer): void | Promise<void>;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Produces a fresh MCP server for one HTTP exchange. Under the SDK's v2
|
|
825
|
+
* handler the factory runs once per request, so per-request tools are possible.
|
|
826
|
+
* Zero-argument factories remain assignable.
|
|
827
|
+
*/
|
|
828
|
+
type McpServerFactory = (context: McpRequestContext) => McpServer | Promise<McpServer>;
|
|
829
|
+
interface McpOptions {
|
|
830
|
+
/**
|
|
831
|
+
* Allowed browser `Origin` values. Entries may be full origins
|
|
832
|
+
* (`https://app.example.com`), hostnames (`app.example.com`), or the SDK's
|
|
833
|
+
* extension form (`moz-extension://*`). Full origins are matched exactly
|
|
834
|
+
* (scheme, host, and port); hostnames are matched port-agnostically.
|
|
835
|
+
*
|
|
836
|
+
* Requests without an `Origin` header always pass, as non-browser MCP
|
|
837
|
+
* clients do not send one. When omitted, Origin validation is disabled;
|
|
838
|
+
* production apps should set this or use the CORS and IP guards.
|
|
839
|
+
*/
|
|
840
|
+
origin?: string | string[];
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Marks an {@link McpController} subclass as an MCP endpoint.
|
|
845
|
+
*
|
|
846
|
+
* @param path - MCP endpoint path, resolved under the app's `basePath`.
|
|
847
|
+
* @param options - Optional MCP endpoint settings such as allowed origins.
|
|
848
|
+
* @returns A class decorator, used as `@mcp("/mcp")`.
|
|
849
|
+
*/
|
|
850
|
+
declare function mcp(path?: string, options?: McpOptions): <TTarget extends abstract new (...args: any[]) => McpController>(target: TTarget, context: ClassDecoratorContext<any>) => void | TTarget;
|
|
251
851
|
|
|
252
852
|
interface dev {
|
|
253
853
|
path?: string;
|
|
@@ -255,6 +855,1237 @@ interface dev {
|
|
|
255
855
|
method?: string;
|
|
256
856
|
port?: number;
|
|
257
857
|
}
|
|
858
|
+
interface serverOptions {
|
|
859
|
+
server: Partial<Bun.Serve.Options<any, never>> & dev & {
|
|
860
|
+
fn?: (port: number) => void;
|
|
861
|
+
};
|
|
862
|
+
wss?: RossaWebSocketOptions | undefined;
|
|
863
|
+
}
|
|
864
|
+
type RossaWebSocketOptions = Partial<WebSocketHandler<any>> & {
|
|
865
|
+
/** Optional fixed-window incoming message limit applied separately per socket. */
|
|
866
|
+
messageRateLimit?: WssMessageRateLimit;
|
|
867
|
+
};
|
|
868
|
+
interface RossaOptions {
|
|
869
|
+
basePath?: string;
|
|
870
|
+
clientPath?: string;
|
|
871
|
+
dirPath?: string;
|
|
872
|
+
/** Additional static-file extensions to recognize, with or without a leading dot. */
|
|
873
|
+
fileExtensions?: string[];
|
|
874
|
+
logError?: boolean | undefined;
|
|
875
|
+
Encoding?: ContentEncodingType;
|
|
876
|
+
}
|
|
877
|
+
declare class Rossa extends RouterManager {
|
|
878
|
+
protected options: Omit<Required<RossaOptions>, "fileExtensions">;
|
|
879
|
+
fileServer: StaticFileServer;
|
|
880
|
+
private clientRoot;
|
|
881
|
+
constructor(options?: RossaOptions);
|
|
882
|
+
/**
|
|
883
|
+
* Mounts an MCP server over Streamable HTTP.
|
|
884
|
+
*
|
|
885
|
+
* Use the decorator idiom for controllers:
|
|
886
|
+
* ```ts
|
|
887
|
+
* @mcp("/mcp")
|
|
888
|
+
* class MyMcp extends McpController {
|
|
889
|
+
* build(server: McpServer) { ... }
|
|
890
|
+
* }
|
|
891
|
+
* app.registerMCP(MyMcp);
|
|
892
|
+
* ```
|
|
893
|
+
*
|
|
894
|
+
* A raw per-request factory remains available when an explicit path is
|
|
895
|
+
* supplied: `app.registerMCP("/mcp", () => new McpServer(...))`.
|
|
896
|
+
*
|
|
897
|
+
* Decorator-provided options are merged with per-call options; a per-call
|
|
898
|
+
* `origin` wins. Global guards added with `use(...)` run before the MCP
|
|
899
|
+
* handler. Registering the same path again replaces the previous MCP route.
|
|
900
|
+
*
|
|
901
|
+
* @param controller - A decorated `McpController` class or instance.
|
|
902
|
+
* @param options - Optional per-call MCP settings.
|
|
903
|
+
*/
|
|
904
|
+
registerMCP(controller: McpController, options?: McpOptions): void;
|
|
905
|
+
registerMCP(controller: new () => McpController, options?: McpOptions): void;
|
|
906
|
+
/**
|
|
907
|
+
* Mounts a raw MCP factory at an explicit path.
|
|
908
|
+
*
|
|
909
|
+
* @param path - MCP endpoint path, for example `/mcp`.
|
|
910
|
+
* @param factory - Produces the `McpServer` served for each request.
|
|
911
|
+
* @param options - Optional allowed browser origins.
|
|
912
|
+
*/
|
|
913
|
+
registerMCP(path: string, factory: McpServerFactory, options?: McpOptions): void;
|
|
914
|
+
private mountMcp;
|
|
915
|
+
private get getClientRoot();
|
|
916
|
+
private pipeline;
|
|
917
|
+
private processRouter;
|
|
918
|
+
private processWSS;
|
|
919
|
+
test(req: Request, encoding?: ContentEncodingType): Promise<Response>;
|
|
920
|
+
serve(server?: serverOptions["server"], wss?: serverOptions["wss"]): Bun.Server<undefined>;
|
|
921
|
+
protected errorHandler(res: res, error: any): Response;
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
type ColumnType = "text" | "integer" | "bigint" | "boolean" | "json" | "timestamp" | "serial" | "numeric";
|
|
925
|
+
/** Logical column definition interpreted by the selected database dialect. */
|
|
926
|
+
declare class Column {
|
|
927
|
+
readonly type: ColumnType;
|
|
928
|
+
readonly precision?: number | undefined;
|
|
929
|
+
readonly scale?: number | undefined;
|
|
930
|
+
primaryKey: boolean;
|
|
931
|
+
required: boolean;
|
|
932
|
+
isUnique: boolean;
|
|
933
|
+
hasDefault: boolean;
|
|
934
|
+
defaultIsCurrentTimestamp: boolean;
|
|
935
|
+
defaultValue: string | number | boolean | null;
|
|
936
|
+
constructor(type: ColumnType, precision?: number | undefined, scale?: number | undefined);
|
|
937
|
+
get primary(): this;
|
|
938
|
+
get notNull(): this;
|
|
939
|
+
get unique(): this;
|
|
940
|
+
get defaultNow(): this;
|
|
941
|
+
default(value: string | number | boolean): this;
|
|
942
|
+
}
|
|
943
|
+
declare const t: {
|
|
944
|
+
text: () => Column;
|
|
945
|
+
int: () => Column;
|
|
946
|
+
bigint: () => Column;
|
|
947
|
+
boolean: () => Column;
|
|
948
|
+
json: () => Column;
|
|
949
|
+
timestamp: () => Column;
|
|
950
|
+
serial: () => Column;
|
|
951
|
+
numeric: (precision?: number, scale?: number) => Column;
|
|
952
|
+
};
|
|
953
|
+
|
|
954
|
+
declare class DatabaseError extends Error {
|
|
955
|
+
constructor(message: string);
|
|
956
|
+
}
|
|
957
|
+
declare class UniqueConstraintError extends DatabaseError {
|
|
958
|
+
constructor(message: string);
|
|
959
|
+
}
|
|
960
|
+
declare class ForeignKeyError extends DatabaseError {
|
|
961
|
+
constructor(message?: string);
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
type DbDialectName = "sqlite" | "postgres" | "mysql" | "mariadb";
|
|
965
|
+
interface TableStats {
|
|
966
|
+
rowCount: number;
|
|
967
|
+
diskSize: string;
|
|
968
|
+
indexCount: number;
|
|
969
|
+
}
|
|
970
|
+
/** Operations whose SQL differs between database engines. */
|
|
971
|
+
interface DbDialectAdapter {
|
|
972
|
+
readonly name: DbDialectName;
|
|
973
|
+
quoteIdentifier(name: string): string;
|
|
974
|
+
quoteTable(name: string): string;
|
|
975
|
+
normalizeColumnName(name: string): string;
|
|
976
|
+
buildColumn(name: string, column: Column): string;
|
|
977
|
+
buildColumnType(column: Column): string;
|
|
978
|
+
normalizeOperator(operator: string): string;
|
|
979
|
+
version(db: SQL): Promise<string>;
|
|
980
|
+
createTable(db: SQL, schema: DbSchema<any>): Promise<void>;
|
|
981
|
+
getColumns(db: SQL, schema: DbSchema<any>): Promise<string[]>;
|
|
982
|
+
addColumn(db: SQL, schema: DbSchema<any>, name: string, type: string): Promise<void>;
|
|
983
|
+
dropColumn(db: SQL, schema: DbSchema<any>, name: string): Promise<void>;
|
|
984
|
+
upsert<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>, data: T, conflictColumn: keyof T): Promise<T | undefined>;
|
|
985
|
+
listTables(db: SQL): Promise<string[]>;
|
|
986
|
+
dropTable(db: SQL, schema: DbSchema<any>): Promise<void>;
|
|
987
|
+
truncateTable(db: SQL, schema: DbSchema<any>): Promise<void>;
|
|
988
|
+
getTableStats(db: SQL, schema: DbSchema<any>): Promise<TableStats>;
|
|
989
|
+
getTableIndices(db: SQL, schema: DbSchema<any>): Promise<any[]>;
|
|
990
|
+
getTableSchema(db: SQL, schema: DbSchema<any>): Promise<any[]>;
|
|
991
|
+
getTableData(db: SQL, schema: DbSchema<any>, limit: number, offset: number): Promise<any[]>;
|
|
992
|
+
optimize(db: SQL, schema: DbSchema<any>): Promise<void>;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
declare class DbSchema<T extends Record<string, any>> {
|
|
996
|
+
readonly table: string;
|
|
997
|
+
private readonly definitions;
|
|
998
|
+
readonly dialect: DbDialectAdapter;
|
|
999
|
+
constructor(table: string, definitions: Record<keyof T, Column>, dialect: DbDialectAdapter);
|
|
1000
|
+
entries(): Array<[string, Column]>;
|
|
1001
|
+
withDialect(dialect: DbDialectAdapter): DbSchema<T>;
|
|
1002
|
+
createSQL(adapter?: DbDialectAdapter): string;
|
|
1003
|
+
columnDefinitions(adapter?: DbDialectAdapter): Record<string, string>;
|
|
1004
|
+
get columns(): {
|
|
1005
|
+
[K in keyof T]: string;
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/** Shared inspection API; SQL-specific operations live in the dialect adapter. */
|
|
1010
|
+
declare class DbInspector<T extends Record<string, any>> {
|
|
1011
|
+
private readonly db;
|
|
1012
|
+
readonly schema: DbSchema<T>;
|
|
1013
|
+
constructor(db: SQL, schema: DbSchema<T>);
|
|
1014
|
+
listTables(): Promise<string[]>;
|
|
1015
|
+
dropTable(): Promise<void>;
|
|
1016
|
+
truncateTable(): Promise<void>;
|
|
1017
|
+
getTableStats(): Promise<TableStats>;
|
|
1018
|
+
getTableIndices(): Promise<any[]>;
|
|
1019
|
+
getTableSchema(): Promise<any[]>;
|
|
1020
|
+
getTableData(limit?: number, offset?: number): Promise<any[]>;
|
|
1021
|
+
optimize(): Promise<void>;
|
|
1022
|
+
static sqlite<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
|
|
1023
|
+
static postgres<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
type Where<T> = {
|
|
1027
|
+
[K in keyof T]?: T[K] | {
|
|
1028
|
+
operator: string;
|
|
1029
|
+
value: unknown;
|
|
1030
|
+
};
|
|
1031
|
+
};
|
|
1032
|
+
/** Shared CRUD repository. Dialect-specific statements are delegated to its adapter. */
|
|
1033
|
+
declare class DbRepository<T extends Record<string, any>> {
|
|
1034
|
+
private readonly db;
|
|
1035
|
+
readonly schema: DbSchema<T>;
|
|
1036
|
+
constructor(db: SQL, schema: DbSchema<T>);
|
|
1037
|
+
private get dialect();
|
|
1038
|
+
get inspect(): DbInspector<T>;
|
|
1039
|
+
withContext(context: SQL): DbRepository<T>;
|
|
1040
|
+
create(): Promise<void>;
|
|
1041
|
+
testConnection(): Promise<string>;
|
|
1042
|
+
syncColumns(allowDrop?: boolean): Promise<void>;
|
|
1043
|
+
private identifier;
|
|
1044
|
+
private get table();
|
|
1045
|
+
private joinSql;
|
|
1046
|
+
private buildWhere;
|
|
1047
|
+
insert(data: T): Promise<T | undefined>;
|
|
1048
|
+
upsert(data: T, conflictColumn: keyof T): Promise<T | undefined>;
|
|
1049
|
+
find(where: Where<T>): Promise<T | null>;
|
|
1050
|
+
findAll(where?: Where<T>): Promise<T[]>;
|
|
1051
|
+
count(where?: Where<T>): Promise<number>;
|
|
1052
|
+
exists(where: Where<T>): Promise<boolean>;
|
|
1053
|
+
paginate(page: number, limit: number, where?: Where<T>): Promise<T[]>;
|
|
1054
|
+
update(where: Where<T>, data: Partial<T>): Promise<T[]>;
|
|
1055
|
+
delete(where: Where<T>): Promise<T[]>;
|
|
1056
|
+
transaction<R>(callback: (repository: DbRepository<T>, tx: SQL) => Promise<R>): Promise<R>;
|
|
1057
|
+
private handleDbError;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
declare function getDialect(name: DbDialectName): DbDialectAdapter;
|
|
1061
|
+
|
|
1062
|
+
declare const postgresDialect: DbDialectAdapter;
|
|
1063
|
+
|
|
1064
|
+
declare const sqliteDialect: DbDialectAdapter;
|
|
1065
|
+
|
|
1066
|
+
declare const mysqlDialect: DbDialectAdapter;
|
|
1067
|
+
declare const mariadbDialect: DbDialectAdapter;
|
|
1068
|
+
|
|
1069
|
+
declare function use(...middlewares: GuardReturnType[]): <TTarget, TCtx extends ClassDecoratorContext<any> | ClassMethodDecoratorContext<any, any>>(target: TTarget, context: TCtx) => void | TTarget;
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* Creates a guard that validates a bearer token from the `Authorization` header.
|
|
1073
|
+
*
|
|
1074
|
+
* @param validator - Checks the request context and extracted bearer token.
|
|
1075
|
+
* @returns A guard factory that accepts a validator and optional error configuration.
|
|
1076
|
+
*/
|
|
1077
|
+
declare const authBearer: (options?: ((ctx: ctx, token?: string) => Promise<boolean> | boolean) | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1078
|
+
/**
|
|
1079
|
+
* Creates a guard that validates an API key from the `x-api-key` header.
|
|
1080
|
+
*
|
|
1081
|
+
* @param validator - Checks the request context and extracted API key.
|
|
1082
|
+
* @returns A guard factory that accepts a validator and optional error configuration.
|
|
1083
|
+
*/
|
|
1084
|
+
declare const apiKey: (options?: ((ctx: ctx, key?: string) => Promise<boolean> | boolean) | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1085
|
+
/**
|
|
1086
|
+
* Creates a guard that validates one or more request headers.
|
|
1087
|
+
*
|
|
1088
|
+
* Each entry in the validator map uses a header name as its key and a callback
|
|
1089
|
+
* that validates that header's value.
|
|
1090
|
+
*
|
|
1091
|
+
* @param validator - Map of header names to validation callbacks.
|
|
1092
|
+
* @returns A guard factory that accepts validators and optional error configuration.
|
|
1093
|
+
*/
|
|
1094
|
+
declare const auth: (options?: Record<string, (ctx: ctx, keyValue?: string) => Promise<boolean> | boolean> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1095
|
+
/**
|
|
1096
|
+
* Checks whether the authenticated request may access a route.
|
|
1097
|
+
*
|
|
1098
|
+
* Use this after an authentication guard has established the identity in
|
|
1099
|
+
* `ctx`, then check roles, ownership, scopes, or other application policy in
|
|
1100
|
+
* the callback. A failed check returns HTTP 403 by default.
|
|
1101
|
+
*
|
|
1102
|
+
* @param canAccess - Synchronous or asynchronous authorization check.
|
|
1103
|
+
* @returns A guard factory that accepts the check and optional error config.
|
|
1104
|
+
*/
|
|
1105
|
+
declare const authorize: (options?: ((ctx: ctx) => Promise<boolean> | boolean) | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1106
|
+
|
|
1107
|
+
interface CacheOptions {
|
|
1108
|
+
ttlMs: number;
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Caches public, successful GET responses by their full URL for the configured
|
|
1112
|
+
* lifetime. Requests carrying cookies or authorization headers bypass the cache.
|
|
1113
|
+
*/
|
|
1114
|
+
declare const smartCache: (options?: CacheOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1115
|
+
|
|
1116
|
+
/**
|
|
1117
|
+
* Rule parameter: a single MIME type string, an array, or a custom validator function.
|
|
1118
|
+
* @example 'application/json'
|
|
1119
|
+
* @example ['application/json', 'multipart/form-data']
|
|
1120
|
+
* @example (ct, ctx) => ct?.startsWith('application/') ?? false
|
|
1121
|
+
*/
|
|
1122
|
+
type ContentTypeRules = string | string[] | ((contentType: string | null, ctx: ctx) => boolean);
|
|
1123
|
+
/**
|
|
1124
|
+
* `contentType` — validates that the request `Content-Type` matches allowed types.
|
|
1125
|
+
*
|
|
1126
|
+
* @example
|
|
1127
|
+
* @Use(contentType('application/json'))
|
|
1128
|
+
* @Post('/upload')
|
|
1129
|
+
* upload(ctx: RossaContext) { ... }
|
|
1130
|
+
*/
|
|
1131
|
+
declare const contentType: (options?: ContentTypeRules | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Requires the named cookie to be present on the request.
|
|
1135
|
+
*
|
|
1136
|
+
* @param name - Cookie name to look up in the request's Cookie header.
|
|
1137
|
+
* @returns A guard factory that continues when the cookie exists.
|
|
1138
|
+
*/
|
|
1139
|
+
declare const cookies: (options?: string | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1140
|
+
|
|
1141
|
+
interface CorsOptions {
|
|
1142
|
+
/**
|
|
1143
|
+
* Allowed origin(s). Can be "*", exact origin URLs, or an array of them,
|
|
1144
|
+
* or a custom validator function.
|
|
1145
|
+
* @default "*"
|
|
1146
|
+
*/
|
|
1147
|
+
origin?: string | string[] | ((incomingOrigin: string | null, ctx: ctx) => string | boolean);
|
|
1148
|
+
/**
|
|
1149
|
+
* Headers allowed in requests (Access-Control-Allow-Headers).
|
|
1150
|
+
* @default "*"
|
|
1151
|
+
*/
|
|
1152
|
+
allowHeaders?: string | string[];
|
|
1153
|
+
/** Methods advertised for browser preflight requests. */
|
|
1154
|
+
methods?: string | string[];
|
|
1155
|
+
/**
|
|
1156
|
+
* Headers exposed to the browser client (Access-Control-Expose-Headers).
|
|
1157
|
+
*/
|
|
1158
|
+
exposeHeaders?: string | string[];
|
|
1159
|
+
/**
|
|
1160
|
+
* Whether to allow credentials like cookies or Authorization headers.
|
|
1161
|
+
* @default false
|
|
1162
|
+
*/
|
|
1163
|
+
credentials?: boolean;
|
|
1164
|
+
/**
|
|
1165
|
+
* Preflight cache duration in seconds (Access-Control-Max-Age).
|
|
1166
|
+
* @default 86400 (24 hours)
|
|
1167
|
+
*/
|
|
1168
|
+
maxAge?: number | string;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Sets CORS response headers and rejects requests whose origin is not allowed.
|
|
1172
|
+
*
|
|
1173
|
+
* @param options - Allowed origins, headers, credentials, and preflight caching.
|
|
1174
|
+
* @returns A guard factory that accepts CORS options and optional error config.
|
|
1175
|
+
*/
|
|
1176
|
+
declare const cors: (options?: CorsOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1177
|
+
|
|
1178
|
+
interface CsrfOptions {
|
|
1179
|
+
headerName?: string;
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Checks a CSRF header against the `csrf_token` cookie on state-changing requests.
|
|
1183
|
+
*
|
|
1184
|
+
* @param options - Optional name of the request header containing the token.
|
|
1185
|
+
* @returns A guard factory that accepts CSRF options and optional error config.
|
|
1186
|
+
*/
|
|
1187
|
+
declare const csrf: (options?: CsrfOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1188
|
+
|
|
1189
|
+
type DenyConfig = ErrorConfig & {
|
|
1190
|
+
/** When provided, the guard denies only requests where the predicate returns true; otherwise it continues. */
|
|
1191
|
+
when?: (ctx: ctx) => boolean | Promise<boolean>;
|
|
1192
|
+
};
|
|
1193
|
+
/**
|
|
1194
|
+
* Rejects requests with an HTTP error, optionally only when a predicate matches.
|
|
1195
|
+
*
|
|
1196
|
+
* Without `when` every request is denied, which is useful for maintenance
|
|
1197
|
+
* windows or permanently closing a route. With `when`, non-matching requests
|
|
1198
|
+
* continue through the remaining guards and the handler.
|
|
1199
|
+
*
|
|
1200
|
+
* ```ts
|
|
1201
|
+
* @use(deny()) // always 403
|
|
1202
|
+
* @use(deny({ code: 503, message: "Under maintenance" })) // custom status
|
|
1203
|
+
* @use(deny({ when: (ctx) => ctx.req.method === "TRACE" })) // conditional
|
|
1204
|
+
* ```
|
|
1205
|
+
*
|
|
1206
|
+
* @param options - Optional status, message, headers, redirect, and predicate.
|
|
1207
|
+
* @returns A guard factory that denies matching requests and continues otherwise.
|
|
1208
|
+
*/
|
|
1209
|
+
declare const deny: (options?: DenyConfig | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1210
|
+
|
|
1211
|
+
interface ErrorGuardOptions {
|
|
1212
|
+
/** Log caught errors. Defaults to false. */
|
|
1213
|
+
logErrors?: boolean;
|
|
1214
|
+
/** Safe message returned for unexpected errors. */
|
|
1215
|
+
message?: string;
|
|
1216
|
+
/** Custom response handler. */
|
|
1217
|
+
onError?: (error: unknown, ctx: ctx) => Response | Promise<Response>;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Catches errors thrown by downstream guards or handlers and returns a safe
|
|
1221
|
+
* 500 response unless a custom handler is provided. Place it before the guards
|
|
1222
|
+
* and handlers whose errors it should catch.
|
|
1223
|
+
*
|
|
1224
|
+
* @param options - Logging, public message, and custom error response behavior.
|
|
1225
|
+
* @returns A guard factory that wraps downstream execution with error handling.
|
|
1226
|
+
*/
|
|
1227
|
+
declare const errorHandler: (options?: ErrorGuardOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1228
|
+
|
|
1229
|
+
type HeaderValidationRules = Record<string, (ctx: ctx, headName: string, value: string) => boolean>;
|
|
1230
|
+
/**
|
|
1231
|
+
* Requires named headers or validates header values with caller-provided rules.
|
|
1232
|
+
*
|
|
1233
|
+
* @param rules - Header names to require, or a map of names to validators.
|
|
1234
|
+
* @returns A guard factory that accepts header rules and optional error config.
|
|
1235
|
+
*/
|
|
1236
|
+
declare const header: (options?: string | string[] | HeaderValidationRules | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1237
|
+
|
|
1238
|
+
type IpOptions = {
|
|
1239
|
+
whitelist?: string[];
|
|
1240
|
+
blacklist?: string[];
|
|
1241
|
+
};
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* Allows or blocks requests based on configured client IP allow and deny lists.
|
|
1245
|
+
*
|
|
1246
|
+
* @param options - IP allowlist and blocklist rules.
|
|
1247
|
+
* @returns A guard factory that accepts IP rules and optional error config.
|
|
1248
|
+
*/
|
|
1249
|
+
declare const ipFilter: (options?: IpOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* TypeScript types for the
|
|
1253
|
+
* {@link https://standardschema.dev/ | Standard Schema} and
|
|
1254
|
+
* Standard JSON Schema interfaces.
|
|
1255
|
+
*
|
|
1256
|
+
* They mirror the vendor-neutral contracts consumed by the MCP SDK. Keeping
|
|
1257
|
+
* local copies avoids a runtime dependency on the SDK from the schema library.
|
|
1258
|
+
*/
|
|
1259
|
+
/** A single property key or named path segment in an issue path. */
|
|
1260
|
+
type StandardPathSegment = PropertyKey | {
|
|
1261
|
+
readonly key: PropertyKey;
|
|
1262
|
+
};
|
|
1263
|
+
/** One validation problem in the Standard Schema shape. */
|
|
1264
|
+
interface StandardIssue {
|
|
1265
|
+
/** Human-readable explanation of the failure. */
|
|
1266
|
+
readonly message: string;
|
|
1267
|
+
/** Location of the failing value inside nested data. */
|
|
1268
|
+
readonly path?: ReadonlyArray<StandardPathSegment> | undefined;
|
|
1269
|
+
}
|
|
1270
|
+
/** Successful validation result. */
|
|
1271
|
+
interface StandardSuccessResult<Output> {
|
|
1272
|
+
/** Parsed and normalized output value. */
|
|
1273
|
+
readonly value: Output;
|
|
1274
|
+
readonly issues?: undefined;
|
|
1275
|
+
}
|
|
1276
|
+
/** Failed validation result. */
|
|
1277
|
+
interface StandardFailureResult {
|
|
1278
|
+
/** Every problem found while validating the input. */
|
|
1279
|
+
readonly issues: ReadonlyArray<StandardIssue>;
|
|
1280
|
+
}
|
|
1281
|
+
/** Discriminated union returned by `~standard.validate`. */
|
|
1282
|
+
type StandardValidateResult<Output> = StandardSuccessResult<Output> | StandardFailureResult;
|
|
1283
|
+
/** Options passed to `~standard.validate`. */
|
|
1284
|
+
interface StandardValidateOptions {
|
|
1285
|
+
/** Extra options for the producing library; unused by Rossa schemas. */
|
|
1286
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
1287
|
+
}
|
|
1288
|
+
/** JSON Schema dialect requested by a consumer. */
|
|
1289
|
+
type StandardJSONSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | (object & string);
|
|
1290
|
+
/** Options passed to the `~standard.jsonSchema` converters. */
|
|
1291
|
+
interface StandardJSONSchemaOptions {
|
|
1292
|
+
/** Target dialect. Rossa emits the same subset for every target. */
|
|
1293
|
+
readonly target?: StandardJSONSchemaTarget | undefined;
|
|
1294
|
+
/** Extra options for the producing library; unused by Rossa schemas. */
|
|
1295
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
1296
|
+
}
|
|
1297
|
+
/** Converters that advertise a schema's wire shape as JSON Schema. */
|
|
1298
|
+
interface StandardJSONSchemaConverter {
|
|
1299
|
+
/** JSON Schema describing accepted input values. */
|
|
1300
|
+
readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
|
|
1301
|
+
/** JSON Schema describing produced output values. */
|
|
1302
|
+
readonly output: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
|
|
1303
|
+
}
|
|
1304
|
+
/** Phantom input/output type pair exposed through `~standard.types`. */
|
|
1305
|
+
interface StandardTypes<Input = unknown, Output = Input> {
|
|
1306
|
+
readonly input: Input;
|
|
1307
|
+
readonly output: Output;
|
|
1308
|
+
}
|
|
1309
|
+
/** Properties attached to every schema under the `~standard` key. */
|
|
1310
|
+
interface StandardSchemaProps<Input = unknown, Output = Input> {
|
|
1311
|
+
readonly version: 1;
|
|
1312
|
+
readonly vendor: string;
|
|
1313
|
+
readonly types?: StandardTypes<Input, Output> | undefined;
|
|
1314
|
+
readonly validate: (value: unknown, options?: StandardValidateOptions | undefined) => StandardValidateResult<Output>;
|
|
1315
|
+
readonly jsonSchema: StandardJSONSchemaConverter;
|
|
1316
|
+
}
|
|
1317
|
+
/** Any value implementing the Standard Schema contract. */
|
|
1318
|
+
interface StandardSchema<Input = unknown, Output = Input> {
|
|
1319
|
+
readonly "~standard": StandardSchemaProps<Input, Output>;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/**
|
|
1323
|
+
* A single validation problem found while parsing a value.
|
|
1324
|
+
*
|
|
1325
|
+
* `path` identifies the failing location in nested data (for example
|
|
1326
|
+
* `["address", "city"]` or `["tags", 0]`), while `message` is a human-friendly
|
|
1327
|
+
* explanation written for API consumers.
|
|
1328
|
+
*/
|
|
1329
|
+
type Issue = {
|
|
1330
|
+
path: (string | number)[];
|
|
1331
|
+
message: string;
|
|
1332
|
+
};
|
|
1333
|
+
/** Result of a successful {@link Schema.safeParse} call. */
|
|
1334
|
+
type SafeParseSuccess<T> = {
|
|
1335
|
+
success: true;
|
|
1336
|
+
data: T;
|
|
1337
|
+
};
|
|
1338
|
+
/** Result of a failed {@link Schema.safeParse} call. */
|
|
1339
|
+
type SafeParseFailure = {
|
|
1340
|
+
success: false;
|
|
1341
|
+
error: SchemaError;
|
|
1342
|
+
};
|
|
1343
|
+
/** Discriminated union returned by {@link Schema.safeParse}. */
|
|
1344
|
+
type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseFailure;
|
|
1345
|
+
/**
|
|
1346
|
+
* Error thrown by {@link Schema.parse} when validation fails.
|
|
1347
|
+
*
|
|
1348
|
+
* Inspect `issues` for structured, path-aware details, or read `message` for a
|
|
1349
|
+
* short joined summary.
|
|
1350
|
+
*/
|
|
1351
|
+
declare class SchemaError extends Error {
|
|
1352
|
+
/** Structured validation problems, in the order they were discovered. */
|
|
1353
|
+
readonly issues: Issue[];
|
|
1354
|
+
constructor(issues: Issue[]);
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Any schema, regardless of its output type. Useful for guard options and for
|
|
1358
|
+
* accepting schemas whose exact output is not important.
|
|
1359
|
+
*/
|
|
1360
|
+
type AnySchema = Schema<unknown>;
|
|
1361
|
+
/** Resolve the output type carried by a schema. */
|
|
1362
|
+
type InferSchema<S> = S extends Schema<infer Output> ? Output : never;
|
|
1363
|
+
/** Internal, cloneable flags shared by every schema. */
|
|
1364
|
+
interface SchemaState {
|
|
1365
|
+
optional: boolean;
|
|
1366
|
+
nullable: boolean;
|
|
1367
|
+
hasDefault: boolean;
|
|
1368
|
+
defaultValue: unknown;
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Base class for every schema.
|
|
1372
|
+
*
|
|
1373
|
+
* It owns the shared modifier flags (`.optional()`, `.nullable()`, `.default()`)
|
|
1374
|
+
* and the parse/safeParse entry points. Concrete schemas implement `_clone` and
|
|
1375
|
+
* `_validate`. All modifier methods return fresh instances, so a schema value
|
|
1376
|
+
* can be safely reused in multiple chains.
|
|
1377
|
+
*/
|
|
1378
|
+
declare abstract class Schema<Output> {
|
|
1379
|
+
/** Phantom output type used by `z.infer`. */
|
|
1380
|
+
readonly _output: Output;
|
|
1381
|
+
/**
|
|
1382
|
+
* Standard Schema and Standard JSON Schema interface.
|
|
1383
|
+
*
|
|
1384
|
+
* This is the vendor-neutral contract used by the MCP SDK's `registerTool`
|
|
1385
|
+
* and `registerPrompt`. `validate` runs the same pipeline as
|
|
1386
|
+
* {@link Schema.safeParse}; `jsonSchema` advertises the wire shape.
|
|
1387
|
+
*/
|
|
1388
|
+
readonly "~standard": StandardSchemaProps<unknown, Output>;
|
|
1389
|
+
protected readonly _state: SchemaState;
|
|
1390
|
+
constructor(state?: SchemaState);
|
|
1391
|
+
/** Create a fresh copy of this schema, including its modifier flags. */
|
|
1392
|
+
protected abstract _clone(): this;
|
|
1393
|
+
/** Validate a defined, non-null value and return the parsed output. */
|
|
1394
|
+
protected abstract _validate(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
|
|
1395
|
+
/**
|
|
1396
|
+
* Render this schema as JSON Schema.
|
|
1397
|
+
*
|
|
1398
|
+
* The result uses a subset that is valid for draft-07 and draft-2020-12.
|
|
1399
|
+
* Unknown top-level input keys are described with
|
|
1400
|
+
* `additionalProperties: false`; the requested target is ignored.
|
|
1401
|
+
*/
|
|
1402
|
+
toJSONSchema(options?: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1403
|
+
/**
|
|
1404
|
+
* Implement each concrete schema's JSON Schema mapping.
|
|
1405
|
+
*
|
|
1406
|
+
* @internal
|
|
1407
|
+
*/
|
|
1408
|
+
protected abstract _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1409
|
+
/**
|
|
1410
|
+
* Whether the field must appear in an object's `required` list.
|
|
1411
|
+
*
|
|
1412
|
+
* Fields with `.optional()` or `.default(...)` are not required.
|
|
1413
|
+
*
|
|
1414
|
+
* @internal
|
|
1415
|
+
*/
|
|
1416
|
+
_isRequired(): boolean;
|
|
1417
|
+
/** Return a copy that also accepts `undefined` (a missing key is allowed). */
|
|
1418
|
+
optional(): Schema<Output | undefined>;
|
|
1419
|
+
/** Return a copy that also accepts `null`, but still rejects `undefined`. */
|
|
1420
|
+
nullable(): Schema<Output | null>;
|
|
1421
|
+
/**
|
|
1422
|
+
* Return a copy that substitutes `value` when the input is `undefined`.
|
|
1423
|
+
* The same default reference is used for every parse.
|
|
1424
|
+
*/
|
|
1425
|
+
default(value: Exclude<Output, undefined>): Schema<Exclude<Output, undefined>>;
|
|
1426
|
+
/**
|
|
1427
|
+
* Shared handling for `undefined`, `null`, and defaults before a concrete
|
|
1428
|
+
* schema runs its own type checks.
|
|
1429
|
+
*
|
|
1430
|
+
* @internal
|
|
1431
|
+
*/
|
|
1432
|
+
_run(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
|
|
1433
|
+
/**
|
|
1434
|
+
* Validate a value without throwing.
|
|
1435
|
+
*
|
|
1436
|
+
* Unknown object keys are stripped from the returned data. On failure the
|
|
1437
|
+
* result contains a {@link SchemaError} with every collected issue.
|
|
1438
|
+
*/
|
|
1439
|
+
safeParse(data: unknown): SafeParseResult<Output>;
|
|
1440
|
+
/**
|
|
1441
|
+
* Validate a value and return the parsed output.
|
|
1442
|
+
*
|
|
1443
|
+
* @throws {SchemaError} When the input does not satisfy this schema.
|
|
1444
|
+
*/
|
|
1445
|
+
parse(data: unknown): Output;
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
type StringRule = {
|
|
1449
|
+
kind: "min";
|
|
1450
|
+
value: number;
|
|
1451
|
+
} | {
|
|
1452
|
+
kind: "max";
|
|
1453
|
+
value: number;
|
|
1454
|
+
} | {
|
|
1455
|
+
kind: "email";
|
|
1456
|
+
} | {
|
|
1457
|
+
kind: "trim";
|
|
1458
|
+
};
|
|
1459
|
+
type NumberRule = {
|
|
1460
|
+
kind: "min";
|
|
1461
|
+
value: number;
|
|
1462
|
+
} | {
|
|
1463
|
+
kind: "max";
|
|
1464
|
+
value: number;
|
|
1465
|
+
} | {
|
|
1466
|
+
kind: "int";
|
|
1467
|
+
};
|
|
1468
|
+
interface StringOptions {
|
|
1469
|
+
coerce?: boolean;
|
|
1470
|
+
rules?: StringRule[];
|
|
1471
|
+
state?: SchemaState;
|
|
1472
|
+
}
|
|
1473
|
+
interface NumberOptions {
|
|
1474
|
+
coerce?: boolean;
|
|
1475
|
+
rules?: NumberRule[];
|
|
1476
|
+
state?: SchemaState;
|
|
1477
|
+
}
|
|
1478
|
+
interface BooleanOptions {
|
|
1479
|
+
coerce?: boolean;
|
|
1480
|
+
state?: SchemaState;
|
|
1481
|
+
}
|
|
1482
|
+
/** Schema for text values, with `.min`, `.max`, and `.email` rules. */
|
|
1483
|
+
declare class StringSchema extends Schema<string> {
|
|
1484
|
+
private readonly _rules;
|
|
1485
|
+
private readonly _coerce;
|
|
1486
|
+
constructor(options?: StringOptions);
|
|
1487
|
+
protected _clone(): this;
|
|
1488
|
+
/** Require at least `length` characters. */
|
|
1489
|
+
min(length: number): this;
|
|
1490
|
+
/** Require at most `length` characters. */
|
|
1491
|
+
max(length: number): this;
|
|
1492
|
+
/** Require a conventional email address (`local@domain.tld`). */
|
|
1493
|
+
email(): this;
|
|
1494
|
+
/**
|
|
1495
|
+
* Trim leading and trailing whitespace before validation.
|
|
1496
|
+
*
|
|
1497
|
+
* `.min`, `.max`, and `.email` see the trimmed value, and the parsed output
|
|
1498
|
+
* is trimmed.
|
|
1499
|
+
*/
|
|
1500
|
+
trim(): this;
|
|
1501
|
+
private _withRule;
|
|
1502
|
+
protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1503
|
+
protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): string | undefined;
|
|
1504
|
+
}
|
|
1505
|
+
/** Schema for numeric values, with `.min`, `.max`, and `.int` rules. */
|
|
1506
|
+
declare class NumberSchema extends Schema<number> {
|
|
1507
|
+
private readonly _rules;
|
|
1508
|
+
private readonly _coerce;
|
|
1509
|
+
constructor(options?: NumberOptions);
|
|
1510
|
+
protected _clone(): this;
|
|
1511
|
+
/** Require a value greater than or equal to `minimum`. */
|
|
1512
|
+
min(minimum: number): this;
|
|
1513
|
+
/** Require a value less than or equal to `maximum`. */
|
|
1514
|
+
max(maximum: number): this;
|
|
1515
|
+
/** Require a whole number. */
|
|
1516
|
+
int(): this;
|
|
1517
|
+
private _withRule;
|
|
1518
|
+
protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1519
|
+
protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): number | undefined;
|
|
1520
|
+
}
|
|
1521
|
+
/** Schema for boolean values. */
|
|
1522
|
+
declare class BooleanSchema extends Schema<boolean> {
|
|
1523
|
+
private readonly _coerce;
|
|
1524
|
+
constructor(options?: BooleanOptions);
|
|
1525
|
+
protected _clone(): this;
|
|
1526
|
+
protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1527
|
+
protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): boolean | undefined;
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
/** A map of field names to schemas. */
|
|
1531
|
+
type Shape = Record<string, AnySchema>;
|
|
1532
|
+
type OptionalShapeKeys<TShape extends Shape> = {
|
|
1533
|
+
[K in keyof TShape]: undefined extends InferSchema<TShape[K]> ? K : never;
|
|
1534
|
+
}[keyof TShape];
|
|
1535
|
+
/** Output type produced by an object schema, with optional fields preserved. */
|
|
1536
|
+
type InferShape<TShape extends Shape> = {
|
|
1537
|
+
[K in Exclude<keyof TShape, OptionalShapeKeys<TShape>>]: InferSchema<TShape[K]>;
|
|
1538
|
+
} & {
|
|
1539
|
+
[K in OptionalShapeKeys<TShape>]?: Exclude<InferSchema<TShape[K]>, undefined>;
|
|
1540
|
+
};
|
|
1541
|
+
type ArrayRule = {
|
|
1542
|
+
kind: "min";
|
|
1543
|
+
value: number;
|
|
1544
|
+
} | {
|
|
1545
|
+
kind: "max";
|
|
1546
|
+
value: number;
|
|
1547
|
+
};
|
|
1548
|
+
interface ArrayOptions {
|
|
1549
|
+
rules?: ArrayRule[];
|
|
1550
|
+
state?: SchemaState;
|
|
1551
|
+
}
|
|
1552
|
+
/** Schema for arrays whose items share a single item schema. */
|
|
1553
|
+
declare class ArraySchema<Item extends AnySchema> extends Schema<InferSchema<Item>[]> {
|
|
1554
|
+
private readonly _item;
|
|
1555
|
+
private readonly _rules;
|
|
1556
|
+
constructor(item: Item, options?: ArrayOptions);
|
|
1557
|
+
protected _clone(): this;
|
|
1558
|
+
/** Require at least `length` items. */
|
|
1559
|
+
min(length: number): this;
|
|
1560
|
+
/** Require at most `length` items. */
|
|
1561
|
+
max(length: number): this;
|
|
1562
|
+
private _withRule;
|
|
1563
|
+
protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1564
|
+
protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferSchema<Item>[] | undefined;
|
|
1565
|
+
}
|
|
1566
|
+
interface ObjectOptions {
|
|
1567
|
+
state?: SchemaState;
|
|
1568
|
+
}
|
|
1569
|
+
/**
|
|
1570
|
+
* Schema for objects with a fixed shape.
|
|
1571
|
+
*
|
|
1572
|
+
* Unknown input keys are stripped from the parsed output (zod `.strip()`
|
|
1573
|
+
* behavior).
|
|
1574
|
+
*/
|
|
1575
|
+
declare class ObjectSchema<TShape extends Shape> extends Schema<InferShape<TShape>> {
|
|
1576
|
+
/** Field schemas keyed by output property name. */
|
|
1577
|
+
readonly shape: TShape;
|
|
1578
|
+
constructor(shape: TShape, options?: ObjectOptions);
|
|
1579
|
+
protected _clone(): this;
|
|
1580
|
+
protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
|
|
1581
|
+
protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferShape<TShape> | undefined;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/** Create a text schema. */
|
|
1585
|
+
declare const string: () => StringSchema;
|
|
1586
|
+
/** Create a numeric schema. */
|
|
1587
|
+
declare const number: () => NumberSchema;
|
|
1588
|
+
/** Create a boolean schema. */
|
|
1589
|
+
declare const boolean: () => BooleanSchema;
|
|
1590
|
+
/** Create an array schema for the given item schema. */
|
|
1591
|
+
declare const array: <Item extends AnySchema>(item: Item) => ArraySchema<Item>;
|
|
1592
|
+
/** Create an object schema with a fixed shape. */
|
|
1593
|
+
declare const object: <TShape extends Shape>(shape: TShape) => ObjectSchema<TShape>;
|
|
1594
|
+
/**
|
|
1595
|
+
* Coercing variants that convert raw query/form strings before validation.
|
|
1596
|
+
* Non-string inputs pass through to the underlying type checks.
|
|
1597
|
+
*/
|
|
1598
|
+
declare const coerce: {
|
|
1599
|
+
/** Create a text schema that stringifies numbers and booleans. */
|
|
1600
|
+
string: () => StringSchema;
|
|
1601
|
+
/** Create a numeric schema that converts numeric strings with `Number()`. */
|
|
1602
|
+
number: () => NumberSchema;
|
|
1603
|
+
/**
|
|
1604
|
+
* Create a boolean schema that accepts `"true"`/`"1"` and
|
|
1605
|
+
* `"false"`/`"0"` case-insensitively.
|
|
1606
|
+
*/
|
|
1607
|
+
boolean: () => BooleanSchema;
|
|
1608
|
+
};
|
|
1609
|
+
/**
|
|
1610
|
+
* Resolve the output type of a schema.
|
|
1611
|
+
*
|
|
1612
|
+
* ```ts
|
|
1613
|
+
* const User = z.object({ name: z.string() });
|
|
1614
|
+
* type User = z.infer<typeof User>; // { name: string }
|
|
1615
|
+
* ```
|
|
1616
|
+
*/
|
|
1617
|
+
type Infer<S extends AnySchema> = InferSchema<S>;
|
|
1618
|
+
|
|
1619
|
+
declare const z_d_array: typeof array;
|
|
1620
|
+
declare const z_d_boolean: typeof boolean;
|
|
1621
|
+
declare const z_d_coerce: typeof coerce;
|
|
1622
|
+
declare const z_d_number: typeof number;
|
|
1623
|
+
declare const z_d_object: typeof object;
|
|
1624
|
+
declare const z_d_string: typeof string;
|
|
1625
|
+
declare namespace z_d {
|
|
1626
|
+
export { z_d_array as array, z_d_boolean as boolean, z_d_coerce as coerce, z_d_number as number, z_d_object as object, z_d_string as string };
|
|
1627
|
+
export type { Infer as infer };
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
declare const DEFAULT_MAX_SIZE: number;
|
|
1631
|
+
/**
|
|
1632
|
+
* Parses and validates JSON request bodies for POST, PUT, and PATCH requests.
|
|
1633
|
+
* The validated value is stored on the request as `_json`.
|
|
1634
|
+
*
|
|
1635
|
+
* @param schema - Schema used to validate the parsed JSON object.
|
|
1636
|
+
* @returns A guard factory that accepts a schema and optional error config.
|
|
1637
|
+
*/
|
|
1638
|
+
declare const json: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1639
|
+
interface RequireKeysOptions {
|
|
1640
|
+
keys: string[];
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Requires the JSON request body to contain each listed key and stores the
|
|
1644
|
+
* parsed body in `ctx.body`.
|
|
1645
|
+
*
|
|
1646
|
+
* @param keys - Required top-level body keys.
|
|
1647
|
+
* @returns A guard factory that accepts required keys and optional error config.
|
|
1648
|
+
*/
|
|
1649
|
+
declare const keys: (options?: string[] | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1650
|
+
|
|
1651
|
+
type JwtPayload<T> = T & {
|
|
1652
|
+
iat: number;
|
|
1653
|
+
exp: number;
|
|
1654
|
+
/**
|
|
1655
|
+
* Unique token identifier assigned on every signature.
|
|
1656
|
+
*
|
|
1657
|
+
* Optional only so tokens issued before this claim existed remain readable.
|
|
1658
|
+
*/
|
|
1659
|
+
jti?: string;
|
|
1660
|
+
};
|
|
1661
|
+
|
|
1662
|
+
/**
|
|
1663
|
+
* Persistence contract for refresh tokens.
|
|
1664
|
+
*
|
|
1665
|
+
* Implement this interface with any database, key-value store, or external
|
|
1666
|
+
* persistence service. `consume` must atomically remove a token and return
|
|
1667
|
+
* `true` only for the caller that removed it, preventing concurrent reuse.
|
|
1668
|
+
*/
|
|
1669
|
+
interface JwtRefreshTokenStore {
|
|
1670
|
+
/** Initialize the backing store or its schema when needed. */
|
|
1671
|
+
initialize?(): Promise<void>;
|
|
1672
|
+
/** Persist a refresh token until its Unix expiration time in milliseconds. */
|
|
1673
|
+
save(token: string, expiresAt: number): Promise<void>;
|
|
1674
|
+
/** Atomically remove a stored refresh token and report whether it existed. */
|
|
1675
|
+
consume(token: string): Promise<boolean>;
|
|
1676
|
+
}
|
|
1677
|
+
interface JWTConfig {
|
|
1678
|
+
/** Refresh token lifetime in days. Defaults to 7. */
|
|
1679
|
+
refreshValidity?: number;
|
|
1680
|
+
/** Access token lifetime in minutes. Defaults to 15. */
|
|
1681
|
+
tokenValidity?: number;
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* Signs access tokens and manages one-time refresh tokens through an injected
|
|
1685
|
+
* persistence adapter.
|
|
1686
|
+
*
|
|
1687
|
+
* @typeParam T - Shape of the claims carried by the access and refresh tokens.
|
|
1688
|
+
*/
|
|
1689
|
+
declare class JWTAuthService<T extends Record<string, any> = {}> {
|
|
1690
|
+
private readonly refreshTokens;
|
|
1691
|
+
readonly config: Required<JWTConfig>;
|
|
1692
|
+
private readonly engine;
|
|
1693
|
+
constructor(refreshTokens: JwtRefreshTokenStore, secret: string, config?: JWTConfig);
|
|
1694
|
+
/** Initialize the configured persistence adapter, if it needs initialization. */
|
|
1695
|
+
init(): Promise<void>;
|
|
1696
|
+
/** Sign an access token using the configured access-token lifetime. */
|
|
1697
|
+
sign(payload: T): string;
|
|
1698
|
+
/** Verify an access token and return its claims, or `null` if invalid. */
|
|
1699
|
+
verify(token: string): JwtPayload<T> | null;
|
|
1700
|
+
/**
|
|
1701
|
+
* Atomically consume a valid, stored refresh token.
|
|
1702
|
+
*
|
|
1703
|
+
* @returns The token claims when consumption succeeds; otherwise `null`.
|
|
1704
|
+
*/
|
|
1705
|
+
consume(token: string): Promise<JwtPayload<T> | null>;
|
|
1706
|
+
/** Issue a refresh token, persist it, and return it with a new access token. */
|
|
1707
|
+
issue(payload: T): Promise<{
|
|
1708
|
+
accessToken: string;
|
|
1709
|
+
refreshToken: string;
|
|
1710
|
+
}>;
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
/**
|
|
1714
|
+
* Verifies a Bearer access token and stores its decoded claims in `ctx.jwtData`.
|
|
1715
|
+
*
|
|
1716
|
+
* @param service - JWT service used to verify the access token.
|
|
1717
|
+
* @returns A guard factory that accepts a JWT service and optional error config.
|
|
1718
|
+
*/
|
|
1719
|
+
declare const jwtAuth: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1720
|
+
/**
|
|
1721
|
+
* Consumes an `x-refresh-token`, issues a replacement token pair, and stores
|
|
1722
|
+
* the authenticated claims in `ctx.jwtData` and the new tokens in
|
|
1723
|
+
* `ctx.data.jwtTokens`.
|
|
1724
|
+
*
|
|
1725
|
+
* @param service - JWT service used to consume and issue tokens.
|
|
1726
|
+
* @returns A guard factory that accepts a JWT service and optional error config.
|
|
1727
|
+
*/
|
|
1728
|
+
declare const jwtRefresh: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1729
|
+
|
|
1730
|
+
/**
|
|
1731
|
+
* Logs the request method, path, timestamp, and optional label before continuing.
|
|
1732
|
+
*
|
|
1733
|
+
* @param label - Optional text included in the log entry.
|
|
1734
|
+
* @returns A guard factory that accepts a label and optional error config.
|
|
1735
|
+
*/
|
|
1736
|
+
declare const logger: (options?: string | void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1737
|
+
type logFN = {
|
|
1738
|
+
ctx: ctx;
|
|
1739
|
+
res: Response;
|
|
1740
|
+
timestamp: string;
|
|
1741
|
+
method: string;
|
|
1742
|
+
url: string;
|
|
1743
|
+
};
|
|
1744
|
+
/**
|
|
1745
|
+
* Runs a formatter with request metadata and the downstream response, then logs
|
|
1746
|
+
* its returned value when truthy.
|
|
1747
|
+
*
|
|
1748
|
+
* @param formatter - Function that formats the request and response details.
|
|
1749
|
+
* @returns A guard factory that accepts a formatter and optional error config.
|
|
1750
|
+
*/
|
|
1751
|
+
declare const loggerFN: (options?: ((ff: logFN) => any) | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1752
|
+
|
|
1753
|
+
/**
|
|
1754
|
+
* Parses a multipart request and stores its fields and uploaded files in
|
|
1755
|
+
* `ctx.form`.
|
|
1756
|
+
*
|
|
1757
|
+
* @returns A guard factory that parses multipart form data before continuing.
|
|
1758
|
+
*/
|
|
1759
|
+
declare const multipart: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1760
|
+
|
|
1761
|
+
/** Options accepted by {@link validateQuery}. */
|
|
1762
|
+
interface QueryValidationOptions {
|
|
1763
|
+
/** Schema used to validate and coerce query parameters. */
|
|
1764
|
+
schema: AnySchema;
|
|
1765
|
+
}
|
|
1766
|
+
/** Options accepted by {@link validateForm}. */
|
|
1767
|
+
interface FormValidationOptions {
|
|
1768
|
+
/** Schema used to validate and coerce form fields. */
|
|
1769
|
+
schema: AnySchema;
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Validates and coerces URL query parameters against a schema, then stores the
|
|
1773
|
+
* result in `ctx.query`.
|
|
1774
|
+
*
|
|
1775
|
+
* @param schema - Schema used to validate and coerce query values.
|
|
1776
|
+
* @returns A guard factory that accepts the schema and optional error config.
|
|
1777
|
+
*/
|
|
1778
|
+
declare const validateQuery: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1779
|
+
/**
|
|
1780
|
+
* Validates multipart or URL-encoded form fields against a schema and stores
|
|
1781
|
+
* the processed result in `ctx.form`.
|
|
1782
|
+
*
|
|
1783
|
+
* @param schema - Schema used to validate and coerce form values.
|
|
1784
|
+
* @returns A guard factory that accepts the schema and optional error config.
|
|
1785
|
+
*/
|
|
1786
|
+
declare const validateForm: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1787
|
+
|
|
1788
|
+
interface RateLimitOptions {
|
|
1789
|
+
/** Maximum number of connections/requests allowed within the window. @default 100 */
|
|
1790
|
+
max?: number;
|
|
1791
|
+
/** Window duration in milliseconds. @default 60000 (1 minute) */
|
|
1792
|
+
windowMs?: number;
|
|
1793
|
+
/** Whether to attach X-RateLimit-* headers to responses. @default true */
|
|
1794
|
+
expose?: boolean;
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* Limits requests by client IP, HTTP method, and URL path.
|
|
1798
|
+
*
|
|
1799
|
+
* @param options - Request limit, time window, and response-header settings.
|
|
1800
|
+
* @returns A guard factory that accepts rate-limit settings and optional error config.
|
|
1801
|
+
*/
|
|
1802
|
+
declare const rateLimit: (options?: RateLimitOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1803
|
+
|
|
1804
|
+
interface SanitizeOptions {
|
|
1805
|
+
/** Custom string sanitizer. Defaults to escaping HTML-sensitive characters. */
|
|
1806
|
+
sanitizeString?: (value: string) => string;
|
|
1807
|
+
/** Whether to sanitize `ctx.query`. @default true */
|
|
1808
|
+
query?: boolean;
|
|
1809
|
+
/** Whether to sanitize `ctx.form`. @default true */
|
|
1810
|
+
form?: boolean;
|
|
1811
|
+
/** Whether to sanitize parsed JSON in `ctx.body` and `ctx.req._json`. @default true */
|
|
1812
|
+
body?: boolean;
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* Escapes or custom-sanitizes string values in parsed request data before
|
|
1816
|
+
* handlers consume them. Continue to encode output for its final HTML context.
|
|
1817
|
+
*
|
|
1818
|
+
* @param options - Selects request data and the string sanitizer to apply.
|
|
1819
|
+
* @returns A guard factory that sanitizes selected context data.
|
|
1820
|
+
*/
|
|
1821
|
+
declare const sanitize: (options?: SanitizeOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1822
|
+
|
|
1823
|
+
interface SecurityHeadersOptions {
|
|
1824
|
+
contentSecurityPolicy?: string | false;
|
|
1825
|
+
crossOriginEmbedderPolicy?: string | false;
|
|
1826
|
+
crossOriginOpenerPolicy?: string | false;
|
|
1827
|
+
crossOriginResourcePolicy?: string | false;
|
|
1828
|
+
hsts?: string | false;
|
|
1829
|
+
permissionsPolicy?: string | false;
|
|
1830
|
+
referrerPolicy?: string | false;
|
|
1831
|
+
xContentTypeOptions?: string | false;
|
|
1832
|
+
xFrameOptions?: string | false;
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Adds common security headers to downstream responses. CSP and HSTS are opt-in
|
|
1836
|
+
* because their correct values depend on the application and deployment.
|
|
1837
|
+
*
|
|
1838
|
+
* @param options - Header values to apply or disable.
|
|
1839
|
+
* @returns A guard factory that applies security headers to each response.
|
|
1840
|
+
*/
|
|
1841
|
+
declare const security: (options?: SecurityHeadersOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1842
|
+
|
|
1843
|
+
declare class Signator {
|
|
1844
|
+
salt: string;
|
|
1845
|
+
private readonly key;
|
|
1846
|
+
constructor(salt: string);
|
|
1847
|
+
/**
|
|
1848
|
+
* Generates an HMAC SHA-256 signature, encoded cleanly for URLs.
|
|
1849
|
+
*/
|
|
1850
|
+
getSignature(val: string): string;
|
|
1851
|
+
/**
|
|
1852
|
+
* Attaches the signature to the value using the standard "." separator.
|
|
1853
|
+
* Format: payload.signature
|
|
1854
|
+
*/
|
|
1855
|
+
sign(val: string): string;
|
|
1856
|
+
/**
|
|
1857
|
+
* Verifies a signed string.
|
|
1858
|
+
* Returns the original value if valid, or null if tampered/invalid.
|
|
1859
|
+
*/
|
|
1860
|
+
unsign(signedVal: string): string | null;
|
|
1861
|
+
/**
|
|
1862
|
+
* Cryptographically secure comparison to prevent Timing Attacks.
|
|
1863
|
+
*/
|
|
1864
|
+
private verifySignature;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
declare class SidGenerator {
|
|
1868
|
+
protected signer: Signator;
|
|
1869
|
+
constructor(salt: string);
|
|
1870
|
+
/**
|
|
1871
|
+
* Generates a URL-safe, cryptographically secure, signed session ID.
|
|
1872
|
+
*/
|
|
1873
|
+
generate(len?: number): string;
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
interface AuthConfig {
|
|
1877
|
+
COOKIE_NAME?: string;
|
|
1878
|
+
COOKIE_LIFETIME?: number;
|
|
1879
|
+
COOKIE_DOMAIN?: string | undefined;
|
|
1880
|
+
COOKIE_PATH?: string;
|
|
1881
|
+
COOKIE_HTTPONLY?: boolean;
|
|
1882
|
+
COOKIE_SECURE?: boolean;
|
|
1883
|
+
COOKIE_SAMESITE?: "Strict" | "Lax" | "None";
|
|
1884
|
+
MAX_COOKIE_SIZE?: number;
|
|
1885
|
+
SESSION_LIFETIME?: number;
|
|
1886
|
+
}
|
|
1887
|
+
type newSession = {
|
|
1888
|
+
sid?: string | undefined;
|
|
1889
|
+
readonly?: boolean | undefined;
|
|
1890
|
+
isFound?: boolean;
|
|
1891
|
+
};
|
|
1892
|
+
declare abstract class SessionAuthInterface extends SidGenerator {
|
|
1893
|
+
config: Required<AuthConfig>;
|
|
1894
|
+
constructor(config: AuthConfig, salt?: string);
|
|
1895
|
+
init(): Promise<void>;
|
|
1896
|
+
/**
|
|
1897
|
+
* Verifies the cryptographic signature and opens the session.
|
|
1898
|
+
*/
|
|
1899
|
+
openSession(sid?: string, readonly?: boolean): Promise<ServerSide>;
|
|
1900
|
+
/** To be implemented by child class: Retrieve from DB */
|
|
1901
|
+
fetchSession(sid: string, readonly?: boolean): Promise<any>;
|
|
1902
|
+
abstract fetchData(sid: string, readonly?: boolean): Promise<any | undefined>;
|
|
1903
|
+
/** To be implemented by child class: Save to DB */
|
|
1904
|
+
abstract saveSession(session: ServerSide, headers: Headers): Promise<void>;
|
|
1905
|
+
/** To be implemented by child class: Save to DB */
|
|
1906
|
+
abstract deleteSession(session: ServerSide, headers: Headers): Promise<void>;
|
|
1907
|
+
/** Instantiates a fresh, writable session */
|
|
1908
|
+
new({ sid, isFound, readonly, }: newSession): ServerSide;
|
|
1909
|
+
/** Instantiates a read-only session */
|
|
1910
|
+
get readonly(): ServerSide;
|
|
1911
|
+
/**
|
|
1912
|
+
* Calculates the exact Date object when this session expires.
|
|
1913
|
+
*/
|
|
1914
|
+
get getSessionExpirationDate(): Date;
|
|
1915
|
+
get getCookieExpirationDate(): Date;
|
|
1916
|
+
/**
|
|
1917
|
+
* Verifies if the session is still active and has not expired.
|
|
1918
|
+
* @returns true if valid, false if expired.
|
|
1919
|
+
*/
|
|
1920
|
+
isNotExpired(_date: Date): boolean;
|
|
1921
|
+
/**
|
|
1922
|
+
* Builds the raw standard HTTP Set-Cookie string.
|
|
1923
|
+
*/
|
|
1924
|
+
buildCookieString(session: ServerSide, expirationOverride?: Date | number, sameSiteOverride?: AuthConfig["COOKIE_SAMESITE"]): string;
|
|
1925
|
+
setCookie(session: ServerSide, headers: Headers): void;
|
|
1926
|
+
removeCookie(session: ServerSide, headers: Headers): void;
|
|
1927
|
+
/**
|
|
1928
|
+
* Extracts the Cookie directly from the Web API Request instance.
|
|
1929
|
+
*/
|
|
1930
|
+
loadHeader(req: Request, readonly?: boolean): Promise<[string | undefined, ServerSide]>;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
interface SessionConfig {
|
|
1934
|
+
auth: SessionAuthInterface;
|
|
1935
|
+
readonly?: boolean;
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Loads the request session into `ctx.session` and persists session changes
|
|
1939
|
+
* after downstream guards and handlers complete.
|
|
1940
|
+
*
|
|
1941
|
+
* @param auth - Session service used to load, save, and delete sessions.
|
|
1942
|
+
* @returns A guard factory that accepts a session service and optional error config.
|
|
1943
|
+
*/
|
|
1944
|
+
declare const session: (options?: SessionAuthInterface | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1945
|
+
/** Optional extra check applied to a session that `session()` already resolved. */
|
|
1946
|
+
type SessionValidator = (session: ServerSide) => boolean | Promise<boolean>;
|
|
1947
|
+
/**
|
|
1948
|
+
* Rejects requests that do not carry a valid, stored session.
|
|
1949
|
+
*
|
|
1950
|
+
* A session counts as authenticated only when the cookie signature is valid,
|
|
1951
|
+
* the row still exists in the store, it has not expired, and it is not a
|
|
1952
|
+
* freshly created anonymous session. Compose this guard after
|
|
1953
|
+
* `session(service)` — it reads `ctx.session` and never loads the cookie
|
|
1954
|
+
* itself:
|
|
1955
|
+
*
|
|
1956
|
+
* ```ts
|
|
1957
|
+
* @use(session(service), requireSession())
|
|
1958
|
+
* ```
|
|
1959
|
+
*
|
|
1960
|
+
* Pass a validator to add an application-level check, for example an identity
|
|
1961
|
+
* field written during login. Session data keys are not part of the
|
|
1962
|
+
* `ServerSide` type, so cast to your session shape:
|
|
1963
|
+
*
|
|
1964
|
+
* ```ts
|
|
1965
|
+
* @use(session(service), requireSession((s) => typeof (s as AccountSession).userId === "number"))
|
|
1966
|
+
* ```
|
|
1967
|
+
*
|
|
1968
|
+
* @param validator - Optional additional check for the resolved session.
|
|
1969
|
+
* @returns A guard factory that returns 401 and continues otherwise.
|
|
1970
|
+
*/
|
|
1971
|
+
declare const requireSession: (options?: SessionValidator | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
1972
|
+
|
|
1973
|
+
/** Configuration for a {@link staticFiles} mount. */
|
|
1974
|
+
interface StaticFilesOptions {
|
|
1975
|
+
/**
|
|
1976
|
+
* Restricts this mount to request paths under the given prefix. The decoded
|
|
1977
|
+
* pathname is compared at a path-segment boundary, so `/assets` matches
|
|
1978
|
+
* `/assets` and `/assets/app.js` but not `/assetsfoo.png`. Requests outside
|
|
1979
|
+
* the prefix fall through to the remaining guards and routes, which keeps
|
|
1980
|
+
* authentication and route handling reachable. Omit it to intercept every
|
|
1981
|
+
* file-like path, as a global static mount does.
|
|
1982
|
+
*/
|
|
1983
|
+
prefix?: string;
|
|
1984
|
+
/**
|
|
1985
|
+
* Directory this mount serves from. Relative paths resolve against
|
|
1986
|
+
* `process.cwd()`; absolute paths are used as-is. When set, the mount uses a
|
|
1987
|
+
* dedicated static file server instead of the app-wide `clientPath` server.
|
|
1988
|
+
* With a `prefix`, the prefix is stripped before the lookup, so
|
|
1989
|
+
* `/files/logo.png` maps to `<root>/logo.png`. Without a prefix the full
|
|
1990
|
+
* request path is used.
|
|
1991
|
+
*/
|
|
1992
|
+
root?: string;
|
|
1993
|
+
/**
|
|
1994
|
+
* Additional file extensions recognized by this mount, with or without a
|
|
1995
|
+
* leading dot. They extend the built-in extension list but do not replace
|
|
1996
|
+
* the app-wide `fileExtensions` configuration.
|
|
1997
|
+
*/
|
|
1998
|
+
extensions?: string[];
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Serves requests for file-like paths through a static file server.
|
|
2002
|
+
* Only GET and HEAD requests are intercepted; HEAD responses keep the file
|
|
2003
|
+
* headers but drop the body.
|
|
2004
|
+
*
|
|
2005
|
+
* Without options it behaves like a global mount: every recognized file-like
|
|
2006
|
+
* path is served from the app-wide `clientPath` server before route guards run.
|
|
2007
|
+
* Pass `prefix` and/or `root` to scope a mount, for example
|
|
2008
|
+
* `staticFiles({ prefix: "/files", root: "./private-files" })` registered
|
|
2009
|
+
* behind an authentication guard.
|
|
2010
|
+
*
|
|
2011
|
+
* @param options - Optional prefix, root, and extension configuration.
|
|
2012
|
+
* @returns A guard factory that serves static assets before route handling.
|
|
2013
|
+
*/
|
|
2014
|
+
declare const staticFiles: (options?: StaticFilesOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
2015
|
+
|
|
2016
|
+
/**
|
|
2017
|
+
* Stops waiting for downstream work after the configured number of milliseconds.
|
|
2018
|
+
*
|
|
2019
|
+
* @param ms - Maximum time to wait for downstream guards and handlers.
|
|
2020
|
+
* @returns A guard factory that accepts a timeout and optional error config.
|
|
2021
|
+
*/
|
|
2022
|
+
declare const timeout: (options?: number | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
2023
|
+
|
|
2024
|
+
/** Function signature for a guard that receives request context and continues the pipeline. */
|
|
2025
|
+
type GlobalGuard = (ctx: ctx, next: () => Promise<Response>) => Promise<Response>;
|
|
2026
|
+
|
|
2027
|
+
interface UrlValidationOptions {
|
|
2028
|
+
maxUrlLength?: number;
|
|
2029
|
+
maxQueryLength?: number;
|
|
2030
|
+
allowedKeys?: string[];
|
|
2031
|
+
disallowedKeys?: string[];
|
|
2032
|
+
noDuplicates?: boolean;
|
|
2033
|
+
sanitizePaths?: boolean;
|
|
2034
|
+
patterns?: Record<string, RegExp>;
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* Validates URL and query limits, query keys, duplicate keys, and path safety.
|
|
2038
|
+
*
|
|
2039
|
+
* @param options - URL size, query, and path validation rules.
|
|
2040
|
+
* @returns A guard factory that accepts validation rules and optional error config.
|
|
2041
|
+
*/
|
|
2042
|
+
declare const validateUrl: (options?: number | void | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
2043
|
+
|
|
2044
|
+
/**
|
|
2045
|
+
* Parses an URL-encoded form request and stores its fields in `ctx.form`.
|
|
2046
|
+
*
|
|
2047
|
+
* @returns A guard factory that parses URL-encoded form data before continuing.
|
|
2048
|
+
*/
|
|
2049
|
+
declare const urlencoded: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
|
|
2050
|
+
|
|
2051
|
+
type ScopeDecorator<V> = (value: undefined, context: ClassFieldDecoratorContext<any, V>) => (this: any) => V;
|
|
2052
|
+
type ScopeProxy<T> = {
|
|
2053
|
+
readonly [K in keyof T]: ScopeDecorator<T[K]>;
|
|
2054
|
+
};
|
|
2055
|
+
type FieldScopeSet<Config extends Record<string, Record<string, any>>> = {
|
|
2056
|
+
use<Name extends keyof Config & string>(name: Name): ScopeProxy<Config[Name]>;
|
|
2057
|
+
};
|
|
2058
|
+
declare class _FieldScope {
|
|
2059
|
+
private static registry;
|
|
2060
|
+
static register<Config extends Record<string, Record<string, any>>>(data: Config): FieldScopeSet<Config>;
|
|
2061
|
+
static use<T extends Record<string, any>>(scopeName: string): ScopeProxy<T>;
|
|
2062
|
+
}
|
|
2063
|
+
/**
|
|
2064
|
+
* Describes the static interface of the Field class
|
|
2065
|
+
*/
|
|
2066
|
+
interface FieldScopeStatic {
|
|
2067
|
+
register<Config extends Record<string, Record<string, any>>>(data: Config): FieldScopeSet<Config>;
|
|
2068
|
+
use<T extends Record<string, any>>(name: string): ScopeProxy<T>;
|
|
2069
|
+
}
|
|
2070
|
+
type Field = _FieldScope;
|
|
2071
|
+
declare const Field: FieldScopeStatic;
|
|
2072
|
+
|
|
2073
|
+
type ScopeSet<Config extends Record<string, Record<string, any>>> = {
|
|
2074
|
+
use<Name extends keyof Config & string>(name: Name): Config[Name];
|
|
2075
|
+
};
|
|
2076
|
+
/** Named, shared values for use in functions, classes, or application setup. */
|
|
2077
|
+
declare class _Scope {
|
|
2078
|
+
private static registry;
|
|
2079
|
+
static register<Config extends Record<string, Record<string, any>>>(data: Config): ScopeSet<Config>;
|
|
2080
|
+
static use<T extends Record<string, any>>(name: string): T;
|
|
2081
|
+
}
|
|
2082
|
+
/** Describes the static interface of the Scope class. */
|
|
2083
|
+
interface ScopeStatic {
|
|
2084
|
+
register<Config extends Record<string, Record<string, any>>>(data: Config): ScopeSet<Config>;
|
|
2085
|
+
use<T extends Record<string, any>>(name: string): T;
|
|
2086
|
+
}
|
|
2087
|
+
type Scope = _Scope;
|
|
2088
|
+
declare const Scope: ScopeStatic;
|
|
258
2089
|
|
|
259
|
-
export {
|
|
260
|
-
export type { dev };
|
|
2090
|
+
export { ArraySchema, BooleanSchema, Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, DbSchema, Field, ForeignKeyError, JWTAuthService, McpController, Methods, NumberSchema, ObjectSchema, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaError, Scope, ServerSide, SessionAuthInterface, StringSchema, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, deny, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, keys, logger, loggerFN, mariadbDialect, mcp, multipart, mysqlDialect, postgresDialect, rateLimit, requireSession, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z_d as z };
|
|
2091
|
+
export type { AnySchema, AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, DenyConfig, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, InferSchema, InferShape, Issue, JWTConfig, JwtPayload, JwtRefreshTokenStore, McpOptions, McpServerFactory, QueryValidationOptions, RateLimitOptions, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SafeParseFailure, SafeParseResult, SafeParseSuccess, SanitizeOptions, SchemaState, SecurityHeadersOptions, SessionConfig, SessionValidator, Shape, StandardIssue, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardPathSegment, StandardSchema, StandardSchemaProps, StandardTypes, StandardValidateOptions, StandardValidateResult, StaticFilesOptions, TableStats, TopicPublishResult, TopicPublishStatus, UrlValidationOptions, Where, WssBaseController, WssConfig, WssMessageRateLimit, WssRouteConfig, dev, methodsKeys, serverOptions, wssMessage };
|