@aomex/web 3.30.7 → 3.30.8-alpha.62.sha-92b25bb
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/dist/index.d.ts +1056 -487
- package/dist/index.js +1770 -1007
- package/dist/index.js.map +1 -1
- package/package.json +37 -35
package/dist/index.d.ts
CHANGED
|
@@ -1,564 +1,1133 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
6
|
-
import
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { MatchFunction, ParamData } from 'path-to-regexp';
|
|
14
|
-
export { default as statuses } from 'statuses';
|
|
15
|
-
|
|
1
|
+
import http, { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
import stream, { Stream } from "node:stream";
|
|
4
|
+
import { Accepts } from "accepts";
|
|
5
|
+
import { SerializeOptions } from "cookie";
|
|
6
|
+
import statuses from "statuses";
|
|
7
|
+
import { CombinedServices, ComposeFn, I18nLanguage, Middleware, MixinMiddleware, Next, OpenAPI, PromisifiedService, TransformedValidator, ValidateResult, Validator, ValidatorFieldTable, ValidatorSchema, ValidatorToken } from "@aomex/common";
|
|
8
|
+
import { NonReadonly, Union2Intersection } from "@aomex/internal-tools";
|
|
9
|
+
import { File } from "formidable";
|
|
10
|
+
import { GlobPathOptions } from "@aomex/internal-file-import";
|
|
11
|
+
import { MatchFunction, ParamData } from "path-to-regexp";
|
|
12
|
+
import { BaseLoggerService } from "@aomex/logger";
|
|
16
13
|
type UpperHeaderKeys = UpperArrayHeaderKeys | UpperStringHeaderKeys;
|
|
17
14
|
type UpperArrayHeaderKeys = 'Set-Cookie';
|
|
18
15
|
type UpperStringHeaderKeys = UpperExternalStringHeaderKeys | UpperOfficialStringHeaderKeys;
|
|
19
16
|
type LowerExternalStringHeaderKeys = 'accept-encoding' | 'x-forwarded-for' | 'x-forwarded-proto' | 'x-forwarded-host' | 'x-real-ip' | 'access-control-request-private-network' | 'access-control-allow-private-network' | ':authority';
|
|
20
17
|
type UpperExternalStringHeaderKeys = 'Accept-Encoding' | 'X-Forwarded-For' | 'X-Forwarded-Proto' | 'X-Forwarded-Host' | 'X-Real-IP' | 'Access-Control-Request-Private-Network' | 'Access-Control-Allow-Private-Network';
|
|
21
18
|
type UpperOfficialStringHeaderKeys = 'Accept' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Ranges' | 'Access-Control-Allow-Credentials' | 'Access-Control-Allow-Headers' | 'Access-Control-Allow-Methods' | 'Access-Control-Allow-Origin' | 'Access-Control-Expose-Headers' | 'Access-Control-Max-Age' | 'Access-Control-Request-Headers' | 'Access-Control-Request-Method' | 'Age' | 'Allow' | 'Alt-Svc' | 'Authorization' | 'Cache-Control' | 'Connection' | 'Content-Disposition' | 'Content-Encoding' | 'Content-Language' | 'Content-Length' | 'Content-Location' | 'Content-Range' | 'Content-Type' | 'Cookie' | 'Date' | 'Etag' | 'Expect' | 'Expires' | 'Forwarded' | 'From' | 'Host' | 'If-Match' | 'If-Modified-Since' | 'If-None-Match' | 'If-Unmodified-Since' | 'Last-Modified' | 'Location' | 'Origin' | 'Pragma' | 'Proxy-Authenticate' | 'Proxy-Authorization' | 'Public-Key-Pins' | 'Range' | 'Referer' | 'Retry-After' | 'Sec-Websocket-Accept' | 'Sec-Websocket-Extensions' | 'Sec-Websocket-Key' | 'Sec-Websocket-Protocol' | 'Sec-Websocket-Version' | 'Strict-Transport-Security' | 'Tk' | 'Trailer' | 'Transfer-Encoding' | 'Upgrade' | 'User-Agent' | 'Vary' | 'Via' | 'Warning' | 'WWW-Authenticate';
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
19
|
+
export declare class WebRequest {
|
|
20
|
+
app: WebApp;
|
|
21
|
+
req: IncomingMessage;
|
|
22
|
+
res: ServerResponse;
|
|
23
|
+
ctx: WebContext;
|
|
24
|
+
url: string;
|
|
25
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
|
26
|
+
headers: IncomingMessage['headers'];
|
|
27
|
+
rawHeaders: IncomingMessage['rawHeaders'];
|
|
28
|
+
params: Record<string, unknown>;
|
|
29
|
+
private _accept?;
|
|
30
|
+
private _cookies?;
|
|
31
|
+
private _body?;
|
|
32
|
+
private _rawBody?;
|
|
33
|
+
private _parsedUrl;
|
|
34
|
+
private _query?;
|
|
35
|
+
private _ip?;
|
|
36
|
+
get accept(): Accepts;
|
|
37
|
+
get contentType(): string;
|
|
38
|
+
/**
|
|
39
|
+
* 返回从`headers['cookie']`解析后的cookie列表
|
|
40
|
+
*/
|
|
41
|
+
get cookies(): {
|
|
42
|
+
readonly [key: string]: string | undefined;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* 解析后的请求体。若需要原始报文请用 `rawBody`
|
|
46
|
+
*/
|
|
47
|
+
get body(): unknown;
|
|
48
|
+
get fresh(): boolean;
|
|
49
|
+
get host(): string;
|
|
50
|
+
/**
|
|
51
|
+
* 包括了协议,域名,端口和路径的完整链接
|
|
52
|
+
*/
|
|
53
|
+
get href(): string;
|
|
54
|
+
/**
|
|
55
|
+
* 客户端 IP。
|
|
56
|
+
* - `proxyIP.mode: 'detect'`:探测常见代理头(可被伪造)
|
|
57
|
+
* - `proxyIP.mode: 'specify'`:按 `hops` / `header` 严格解析
|
|
58
|
+
*/
|
|
59
|
+
get ip(): string;
|
|
60
|
+
get origin(): string;
|
|
61
|
+
get pathname(): string;
|
|
62
|
+
get protocol(): string;
|
|
63
|
+
/**
|
|
64
|
+
* 查询字符串对象
|
|
65
|
+
*/
|
|
66
|
+
get query(): Record<string, unknown>;
|
|
67
|
+
/**
|
|
68
|
+
* 查询字符串
|
|
69
|
+
*/
|
|
70
|
+
get querystring(): string;
|
|
71
|
+
/**
|
|
72
|
+
* 原始请求体字符串。解析后的结构化数据请用 `body`
|
|
73
|
+
*/
|
|
74
|
+
get rawBody(): string;
|
|
75
|
+
/**
|
|
76
|
+
* 搜索字符串,比查询字符串多了一个开头问号(?)
|
|
77
|
+
*/
|
|
78
|
+
get search(): string;
|
|
79
|
+
get secure(): boolean;
|
|
80
|
+
protected get URL(): URL;
|
|
81
|
+
matchContentType(type: string, ...types: string[]): string | null;
|
|
82
|
+
}
|
|
83
|
+
declare module 'node:http' {
|
|
84
|
+
type ExternalHeaders = { [K in LowerExternalStringHeaderKeys]?: string; };
|
|
85
|
+
interface IncomingHttpHeaders extends ExternalHeaders {}
|
|
86
|
+
}
|
|
87
|
+
export declare namespace ServerSentEvents {
|
|
88
|
+
interface Options {
|
|
41
89
|
/**
|
|
42
|
-
*
|
|
90
|
+
* 心跳间隔(毫秒)。写入 SSE 注释行以保持连接。
|
|
91
|
+
* 默认:`15000`。设为 `0` 或 `false` 关闭心跳。
|
|
43
92
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
93
|
+
heartbeat?: number | false;
|
|
94
|
+
/**
|
|
95
|
+
* 写入 `retry:` 字段,提示客户端重连间隔(毫秒)
|
|
96
|
+
*/
|
|
97
|
+
retry?: number;
|
|
98
|
+
}
|
|
99
|
+
interface Message {
|
|
50
100
|
/**
|
|
51
|
-
*
|
|
101
|
+
* 对应帧里的 `data:`。非字符串会 `JSON.stringify`;含换行时拆成多行 `data:`。
|
|
52
102
|
*/
|
|
53
|
-
|
|
54
|
-
get ip(): string;
|
|
55
|
-
get origin(): string;
|
|
56
|
-
get pathname(): string;
|
|
57
|
-
get protocol(): string;
|
|
103
|
+
data?: unknown;
|
|
58
104
|
/**
|
|
59
|
-
*
|
|
105
|
+
* 对应帧里的 `event:`。不写时浏览器走默认的 `message` 事件
|
|
106
|
+
*(`EventSource#onmessage` / `addEventListener('message', ...)`)。
|
|
60
107
|
*/
|
|
61
|
-
|
|
108
|
+
event?: string;
|
|
62
109
|
/**
|
|
63
|
-
*
|
|
110
|
+
* 对应帧里的 `id:`。浏览器会记住最后一次 id,重连时通过请求头 `Last-Event-ID` 带回,
|
|
111
|
+
* 服务端可用 `sse.lastEventId` 读取以做断点续传。
|
|
64
112
|
*/
|
|
65
|
-
|
|
66
|
-
get rawBody(): string;
|
|
113
|
+
id?: string;
|
|
67
114
|
/**
|
|
68
|
-
*
|
|
115
|
+
* 对应帧里的 `retry:`(毫秒)。更新客户端断线后的重连间隔。
|
|
69
116
|
*/
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
protected get URL(): URL;
|
|
73
|
-
matchContentType(type: string, ...types: string[]): string | null;
|
|
117
|
+
retry?: number;
|
|
118
|
+
}
|
|
74
119
|
}
|
|
75
|
-
declare
|
|
76
|
-
|
|
77
|
-
|
|
120
|
+
export declare class ServerSentEvents {
|
|
121
|
+
protected readonly ctx: WebContext;
|
|
122
|
+
protected closed: boolean;
|
|
123
|
+
protected readonly teardowns: Array<() => void>;
|
|
124
|
+
protected readonly abortController: AbortController;
|
|
125
|
+
protected readonly heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
126
|
+
constructor(ctx: WebContext, options?: ServerSentEvents.Options);
|
|
127
|
+
/**
|
|
128
|
+
* 客户端带来的 `Last-Event-ID`(若有)。
|
|
129
|
+
* 发送事件时带上 `id` 后,浏览器断线重连会自动带上该请求头;首次连接或未发过 id 时为 `undefined`。
|
|
130
|
+
*
|
|
131
|
+
* ```typescript
|
|
132
|
+
* const sse = ctx.sse();
|
|
133
|
+
* const after = sse.lastEventId;
|
|
134
|
+
* await sse.stream(async (emit, signal) => {
|
|
135
|
+
* for await (const item of events.watch({ after, signal })) {
|
|
136
|
+
* emit({ id: String(item.id), data: item });
|
|
137
|
+
* }
|
|
138
|
+
* });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
get lastEventId(): string | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* 与本连接绑定的 `AbortSignal`。连接 `close`(含客户端断开)时会 abort,
|
|
144
|
+
* 可传给异步源(如 `watch({ signal })`)以便自动取消;`stream` 的第二参数是同一个 signal。
|
|
145
|
+
*/
|
|
146
|
+
get signal(): AbortSignal;
|
|
147
|
+
protected get writable(): boolean;
|
|
148
|
+
/**
|
|
149
|
+
* 发送一条 SSE 事件
|
|
150
|
+
*/
|
|
151
|
+
send(message: ServerSentEvents.Message): void;
|
|
152
|
+
/**
|
|
153
|
+
* 连接关闭时回调(若已关闭则立即执行)
|
|
154
|
+
*/
|
|
155
|
+
onClose(fn: () => void): this;
|
|
156
|
+
/**
|
|
157
|
+
* 跟随异步源推送;结束或中断时自动 `close()`。
|
|
158
|
+
* 第二参数 `signal` 即 `this.signal`,连接关闭时 abort。
|
|
159
|
+
*/
|
|
160
|
+
stream(fn: (emit: (message: ServerSentEvents.Message) => void, signal: AbortSignal) => void | Promise<void>): Promise<void>;
|
|
161
|
+
/**
|
|
162
|
+
* 结束 SSE 连接并执行 teardown。
|
|
163
|
+
*
|
|
164
|
+
* 客户端断开或 request/response `close` 时会自动调用,一般不必手动关;
|
|
165
|
+
* 服务端主动收尾(推送结束、`stream` 跑完)时再调用。
|
|
166
|
+
*/
|
|
167
|
+
close(): void;
|
|
168
|
+
protected writeField(name: string, value: string): void;
|
|
169
|
+
protected writeRaw(chunk: string): void;
|
|
170
|
+
protected escapeBreak(value: string): string;
|
|
171
|
+
}
|
|
172
|
+
export type Body = string | object | Stream | Buffer | null;
|
|
173
|
+
export type BodyType = 'string' | 'json' | 'stream' | 'buffer' | 'null';
|
|
174
|
+
export declare class WebResponse {
|
|
175
|
+
app: WebApp;
|
|
176
|
+
res: ServerResponse;
|
|
177
|
+
ctx: WebContext;
|
|
178
|
+
req: WebRequest;
|
|
179
|
+
statusCode: number;
|
|
180
|
+
statusMessage: string;
|
|
181
|
+
private _body;
|
|
182
|
+
private _bodyType;
|
|
183
|
+
private _jsonString;
|
|
184
|
+
/**
|
|
185
|
+
* 是否明确设置过内容
|
|
186
|
+
*/
|
|
187
|
+
private _explicitBody;
|
|
188
|
+
/**
|
|
189
|
+
* 是否明确设置过状态码
|
|
190
|
+
*/
|
|
191
|
+
private _explicitStatus;
|
|
192
|
+
/**
|
|
193
|
+
* `formatError` 已写过错误响应;`onError` 跳过默认纯文本兜底
|
|
194
|
+
*/
|
|
195
|
+
private _errorHandled;
|
|
196
|
+
private _statusCode;
|
|
197
|
+
private _updatingContentType;
|
|
198
|
+
constructor(req: IncomingMessage);
|
|
199
|
+
get contentLength(): number;
|
|
200
|
+
set contentLength(length: number);
|
|
201
|
+
get contentType(): string;
|
|
202
|
+
set contentType(typeOrFilenameOrExt: string);
|
|
203
|
+
get body(): Body;
|
|
204
|
+
set body(val: Body);
|
|
205
|
+
/**
|
|
206
|
+
* 下载文件。
|
|
207
|
+
* 返回的 Promise 在响应结束(发送完成或关闭)后 settled,便于清理临时文件。
|
|
208
|
+
*
|
|
209
|
+
* @param filePath 路径
|
|
210
|
+
* @param type 附件类型。默认值:`attachment`
|
|
211
|
+
*
|
|
212
|
+
* @link https://developer.mozilla.org/zh_CN/docs/Web/HTTP/Headers/Content-Disposition
|
|
213
|
+
*
|
|
214
|
+
*/
|
|
215
|
+
download(filePath: string, type?: 'attachment' | 'inline'): Promise<void>;
|
|
216
|
+
/**
|
|
217
|
+
* 打开 SSE(Server-Sent Events)连接。
|
|
218
|
+
*
|
|
219
|
+
* ```typescript
|
|
220
|
+
* const sse = ctx.response.sse();
|
|
221
|
+
* // 或 ctx.sse()
|
|
222
|
+
* sse.send({ event: 'ready', data: { ok: true } });
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
sse(options?: ServerSentEvents.Options): ServerSentEvents;
|
|
226
|
+
getHeader: {
|
|
227
|
+
(name: UpperStringHeaderKeys): string | undefined;
|
|
228
|
+
(name: UpperArrayHeaderKeys): string[] | undefined;
|
|
229
|
+
(name: string): string | string[] | undefined;
|
|
230
|
+
};
|
|
231
|
+
getHeaderNames: () => (UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {}))[];
|
|
232
|
+
getHeaders: () => OutgoingHttpHeaders;
|
|
233
|
+
flush(): void;
|
|
234
|
+
hasHeader: (name: UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {})) => boolean;
|
|
235
|
+
isJSON(value: Body): value is object;
|
|
236
|
+
matchContentType(type: string, ...types: string[]): string | null;
|
|
237
|
+
onError(error?: Error | null): void;
|
|
238
|
+
redirect(url: string): void;
|
|
239
|
+
redirect(statusCode: 300 | 301 | 302 | 303 | 305 | 307 | 308, url: string): void;
|
|
240
|
+
removeCookie(name: string, options?: Pick<SerializeOptions, 'path'>): void;
|
|
241
|
+
removeHeader: (name: UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {})) => void;
|
|
242
|
+
removeHeaders(...headers: ((string & {}) | UpperStringHeaderKeys | UpperArrayHeaderKeys)[]): void;
|
|
243
|
+
setCookie(name: string, value: string, options?: SerializeOptions): void;
|
|
244
|
+
setHeader: {
|
|
245
|
+
<T extends WebResponse>(name: UpperStringHeaderKeys, value: number | string): T;
|
|
246
|
+
<T extends WebResponse>(name: UpperArrayHeaderKeys, value: readonly string[]): T;
|
|
247
|
+
<T extends WebResponse>(name: string, value: number | string | readonly string[]): T;
|
|
248
|
+
};
|
|
249
|
+
setHeaders(headers: Headers | Map<string, string | number | readonly string[]> | ({
|
|
250
|
+
[K: string]: string | number | readonly string[];
|
|
251
|
+
} & { [K in UpperStringHeaderKeys]?: string | number; } & { [K in UpperArrayHeaderKeys]?: readonly string[]; })): this;
|
|
252
|
+
vary(field: UpperHeaderKeys | UpperHeaderKeys[] | (string & {}) | (string & {})[]): string;
|
|
253
|
+
protected setStatus(code: number): void;
|
|
254
|
+
protected updateContentType(): void;
|
|
255
|
+
protected getBodyType(body: Body): BodyType;
|
|
256
|
+
}
|
|
257
|
+
type OKStatus = 200 | 201 | 202 | 203 | 206 | 207 | 208 | 226;
|
|
258
|
+
type EmptyStatus = 204 | 205 | 304;
|
|
259
|
+
type RedirectStatus = 300 | 301 | 302 | 303 | 305 | 307 | 308;
|
|
260
|
+
type ClientErrorStatus = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451;
|
|
261
|
+
type ServerErrorStatus = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511;
|
|
262
|
+
/** 可作为 `HttpError` / `ctx.throw` / `formatError.statusCodes` 的状态码(仅 4xx / 5xx) */
|
|
263
|
+
type HttpErrorStatus = ClientErrorStatus | ServerErrorStatus;
|
|
264
|
+
type HttpStatus = OKStatus | EmptyStatus | RedirectStatus | ClientErrorStatus | ServerErrorStatus;
|
|
265
|
+
/**
|
|
266
|
+
* `response` / `formatError` 共享的响应媒体声明(写入 OpenAPI ResponseObject)。
|
|
267
|
+
*/
|
|
268
|
+
interface WebResponseMediaOptions<Content extends ValidatorToken = ValidatorToken> extends Pick<OpenAPI.MediaTypeObject, 'example'> {
|
|
269
|
+
/**
|
|
270
|
+
* 响应格式,支持简写和完整写法。如果不填,则根据 content 的结构判断
|
|
271
|
+
*
|
|
272
|
+
* 包括但不限于如下类型:
|
|
273
|
+
* - application/json
|
|
274
|
+
* - application/*
|
|
275
|
+
* - json
|
|
276
|
+
* - text
|
|
277
|
+
* - binary
|
|
278
|
+
* - html
|
|
279
|
+
* - stream
|
|
280
|
+
*/
|
|
281
|
+
contentType?: string;
|
|
282
|
+
/**
|
|
283
|
+
* 响应内容结构
|
|
284
|
+
*/
|
|
285
|
+
content?: Content;
|
|
286
|
+
/**
|
|
287
|
+
* 报文结构
|
|
288
|
+
*/
|
|
289
|
+
headers?: {
|
|
290
|
+
[key: string]: ValidatorToken;
|
|
291
|
+
};
|
|
292
|
+
description?: string;
|
|
293
|
+
}
|
|
294
|
+
interface HttpErrorProperties {
|
|
295
|
+
/**
|
|
296
|
+
* 是否向客户端暴露 `message`。
|
|
297
|
+
* 默认:4xx 为 `true`,5xx 为 `false`。
|
|
298
|
+
*/
|
|
299
|
+
expose?: boolean;
|
|
300
|
+
/** 业务/系统错误码,如 `ENOENT` */
|
|
301
|
+
code?: string;
|
|
302
|
+
/** 写入响应的额外头(与 Node `setHeader` 一致,值为 string / number) */
|
|
303
|
+
headers?: Record<string, string | number>;
|
|
304
|
+
cause?: unknown;
|
|
305
|
+
}
|
|
306
|
+
/** 第三方类 http-errors 实例上可能出现的字段 */
|
|
307
|
+
type ForeignHttpErrorFields = {
|
|
308
|
+
status?: unknown;
|
|
309
|
+
statusCode?: unknown;
|
|
310
|
+
expose?: unknown;
|
|
311
|
+
headers?: unknown;
|
|
312
|
+
code?: unknown;
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* HTTP 请求异常。`app.on('error')` 收到的均为本类实例。
|
|
316
|
+
*
|
|
317
|
+
* 业务侧用 `new HttpError` / `ctx.throw` 创建;第三方错误经 {@link HttpError.from} 转换。
|
|
318
|
+
*/
|
|
319
|
+
export declare class HttpError extends Error {
|
|
320
|
+
readonly statusCode: HttpErrorStatus;
|
|
321
|
+
expose: boolean;
|
|
322
|
+
code?: string;
|
|
323
|
+
headers?: Record<string, string | number>;
|
|
324
|
+
constructor(statusCode: HttpErrorStatus, message?: string, properties?: HttpErrorProperties);
|
|
325
|
+
/** 是否为自制 {@link HttpError}(覆盖 `Error.isError`,类型收窄为本类) */
|
|
326
|
+
static isError(value: unknown): value is HttpError;
|
|
327
|
+
/**
|
|
328
|
+
* 将任意错误转为自制 {@link HttpError}。
|
|
329
|
+
*
|
|
330
|
+
* - 已是本类实例:原样返回
|
|
331
|
+
* - 其余:只迁移有效字段(`statusCode`/`status`、`expose`、`headers`、`code`、`message`、`cause`、`stack`)
|
|
332
|
+
*/
|
|
333
|
+
static from(error: unknown): HttpError;
|
|
334
|
+
/**
|
|
335
|
+
* 从第三方 Error(含类 http-errors 形态)提取字段并生成自制实例。
|
|
336
|
+
*/
|
|
337
|
+
protected static fromForeign(error: Error): HttpError;
|
|
338
|
+
protected static pickStatus(raw: ForeignHttpErrorFields): number;
|
|
339
|
+
protected static pickHeaders(headers: unknown): Record<string, string | number> | undefined;
|
|
340
|
+
protected static normalizeStatus(status: number): HttpErrorStatus;
|
|
341
|
+
}
|
|
342
|
+
export declare class WebContext {
|
|
343
|
+
readonly app: WebApp;
|
|
344
|
+
readonly request: WebRequest;
|
|
345
|
+
readonly response: WebResponse;
|
|
346
|
+
readonly redirect: WebResponse['redirect'];
|
|
347
|
+
readonly download: WebResponse['download'];
|
|
348
|
+
readonly sse: WebResponse['sse'];
|
|
349
|
+
constructor(app: WebApp, request: WebRequest, response: WebResponse);
|
|
350
|
+
/** 与构造时传入的 `logger` 相同,取自 app */
|
|
351
|
+
get logger(): WebApp.Logger;
|
|
352
|
+
/**
|
|
353
|
+
* 发送响应内容和状态,包含字符串,对象,数据流,缓冲区等。
|
|
354
|
+
* ```typescript
|
|
355
|
+
* ctx.send(200, 'hello aomex');
|
|
356
|
+
* ctx.send({ count: 1 });
|
|
357
|
+
* ```
|
|
358
|
+
*/
|
|
359
|
+
send(statusCode: number, body?: Body): void;
|
|
360
|
+
send(body: Body): void;
|
|
361
|
+
/**
|
|
362
|
+
* 抛出 HTTP 请求异常(必须指定 4xx/5xx 状态码)
|
|
363
|
+
*
|
|
364
|
+
* ```typescript
|
|
365
|
+
* ctx.throw(403);
|
|
366
|
+
* ctx.throw(400, 'name required');
|
|
367
|
+
* ctx.throw(400, new Error('invalid'));
|
|
368
|
+
* ctx.throw(500, 'server error', { expose: true });
|
|
369
|
+
* ctx.throw(404, { code: 'USER_NOT_FOUND' });
|
|
370
|
+
* ```
|
|
371
|
+
* @throws {HttpError}
|
|
372
|
+
*/
|
|
373
|
+
throw(statusCode: HttpErrorStatus): never;
|
|
374
|
+
throw(statusCode: HttpErrorStatus, message?: string | Error, properties?: HttpErrorProperties): never;
|
|
375
|
+
throw(statusCode: HttpErrorStatus, properties: HttpErrorProperties): never;
|
|
376
|
+
}
|
|
377
|
+
export type WebMiddlewareToken<P extends object = object> = WebMiddleware<P> | MixinMiddleware<P>;
|
|
378
|
+
declare module '@aomex/common' {
|
|
379
|
+
interface MiddlewarePlatform<Deps extends object = object> {
|
|
380
|
+
readonly web: <Props extends object = object>(fn: WebMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>['fn'] | WebMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>) => object extends Deps ? WebMiddleware<Props> : WebMiddleware<Props> & {
|
|
381
|
+
_contextType: Middleware.WithDeps<WebContext, Deps>;
|
|
78
382
|
};
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
export interface OpenApiInjector {
|
|
386
|
+
onDocument?: (document: OpenAPI.Document) => void;
|
|
387
|
+
postDocument?: OpenApiInjector['onDocument'];
|
|
388
|
+
onPath?: (pathItem: OpenAPI.PathItemObject, opts: {
|
|
389
|
+
document: OpenAPI.Document;
|
|
390
|
+
pathName: string;
|
|
391
|
+
}) => void;
|
|
392
|
+
postPath?: OpenApiInjector['onPath'];
|
|
393
|
+
onMethod?: (methodItem: OpenAPI.OperationObject, opts: {
|
|
394
|
+
document: OpenAPI.Document;
|
|
395
|
+
pathName: string;
|
|
396
|
+
pathItem: OpenAPI.PathItemObject;
|
|
397
|
+
methodName: `${Lowercase<WebRequest['method']>}`;
|
|
398
|
+
}) => void;
|
|
399
|
+
postMethod?: OpenApiInjector['onMethod'];
|
|
400
|
+
}
|
|
401
|
+
interface WebMiddlewareArguments<T extends object> {
|
|
402
|
+
fn: (ctx: NonReadonly<T> & WebContext, next: Next) => any;
|
|
403
|
+
openapi?: OpenApiInjector;
|
|
404
|
+
}
|
|
405
|
+
export declare class WebMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
406
|
+
_contextType: WebContext;
|
|
407
|
+
protected _web_middleware_: 'web-middleware';
|
|
408
|
+
private readonly openapiInjector;
|
|
409
|
+
constructor(args: WebMiddlewareArguments<Props>['fn'] | WebMiddlewareArguments<Props>);
|
|
410
|
+
protected openapi(): OpenApiInjector;
|
|
411
|
+
}
|
|
412
|
+
declare module '@aomex/common' {
|
|
413
|
+
interface Rule {
|
|
414
|
+
file(): FileValidator;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
export declare namespace FileValidator {
|
|
418
|
+
interface Options<T> extends Validator.Options<T> {
|
|
419
|
+
maxSize?: number;
|
|
420
|
+
mimeTypes?: string[];
|
|
95
421
|
/**
|
|
96
|
-
*
|
|
422
|
+
* 认不出文件签名时,是否用客户端声明的 Content-Type 对照允许列表。
|
|
423
|
+
* 默认值:`false`
|
|
97
424
|
*/
|
|
98
|
-
|
|
425
|
+
fallbackToMimetype?: boolean;
|
|
426
|
+
}
|
|
427
|
+
interface FormidableFile extends File {
|
|
428
|
+
hash: string;
|
|
429
|
+
hashAlgorithm: 'md5';
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
export declare class FileValidator<T = FileValidator.FormidableFile> extends Validator<T> {
|
|
433
|
+
protected config: FileValidator.Options<T>;
|
|
434
|
+
docs: (docs: Validator.PartialOpenAPISchema, mode?: Validator.DocumentMergeMode) => this;
|
|
435
|
+
optional: () => FileValidator<T | Validator.TOptional>;
|
|
436
|
+
required: () => FileValidator<Exclude<T, Validator.TOptional>>;
|
|
437
|
+
transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
|
|
438
|
+
/**
|
|
439
|
+
* 允许的最大体积
|
|
440
|
+
*
|
|
441
|
+
* 可选格式:
|
|
442
|
+
* - 1024
|
|
443
|
+
* - 2048
|
|
444
|
+
* - '15KB'
|
|
445
|
+
* - '20MB'
|
|
446
|
+
*/
|
|
447
|
+
maxSize(byte: number | string): FileValidator<T>;
|
|
448
|
+
/**
|
|
449
|
+
* 允许的媒体格式。有文件签名时以文件内容为准。
|
|
450
|
+
* 认不出文件签名时默认拒绝;纯文本、HTML、SVG 需要再调用 `fallbackToMimetype()`。
|
|
451
|
+
* ```typescript
|
|
452
|
+
* file.mimeTypes('.png', 'image/*');
|
|
453
|
+
* file.mimeTypes('.html', 'text/plain').fallbackToMimetype();
|
|
454
|
+
* ```
|
|
455
|
+
*/
|
|
456
|
+
mimeTypes(mineOrExt: string, ...others: string[]): this;
|
|
457
|
+
mimeTypes(mineOrExt: string[]): this;
|
|
458
|
+
/**
|
|
459
|
+
* 认不出文件签名时,改用客户端声明的 Content-Type 对照 `mimeTypes()`。
|
|
460
|
+
* 不调用则仍然拒绝。参数默认值:`true`。
|
|
461
|
+
*
|
|
462
|
+
* 没有稳定文件签名、允许时要打开:纯文本、CSV、Markdown、CSS、JSON、
|
|
463
|
+
* JavaScript 源码、HTML,以及不以 `<?xml` 开头的 SVG。
|
|
464
|
+
* 带 `<?xml` 的 XML 会被认成 `application/xml`,不必开;同样开头的 SVG
|
|
465
|
+
* 也会被认成 XML,`image/svg+xml` 仍然对不上。
|
|
466
|
+
*/
|
|
467
|
+
fallbackToMimetype(enable?: boolean): FileValidator<T>;
|
|
468
|
+
protected isEmpty(value: any): boolean;
|
|
469
|
+
protected validateValue(file: FileValidator.FormidableFile, _key: string, label: string): Promise<ValidateResult.Any<FileValidator.FormidableFile>>;
|
|
470
|
+
/** 读取文件头中的文件签名。认不出时返回 `undefined`。 */
|
|
471
|
+
protected detectMimeType(filepath: string): Promise<string | undefined>;
|
|
472
|
+
/**
|
|
473
|
+
* 把扩展名查成媒体类型;已是 `type/subtype`(subtype 可为 `*`)则原样返回。
|
|
474
|
+
* 无法识别时抛错,避免允许列表被悄悄清空。
|
|
475
|
+
*/
|
|
476
|
+
protected resolveMimeType(token: string): string;
|
|
477
|
+
protected copy: () => FileValidator<T>;
|
|
478
|
+
protected toDocument(): OpenAPI.SchemaObject;
|
|
479
|
+
}
|
|
480
|
+
interface EnsureBodyOptions {
|
|
481
|
+
/**
|
|
482
|
+
* 允许落盘的文件字段名。
|
|
483
|
+
* 空数组:解析 multipart,但不接收任何文件。
|
|
484
|
+
*/
|
|
485
|
+
allowFileFields: readonly string[];
|
|
486
|
+
/**
|
|
487
|
+
* 单文件大小上限(字节)。
|
|
488
|
+
* 默认值:`52428800`
|
|
489
|
+
*/
|
|
490
|
+
maxFileSize?: number;
|
|
491
|
+
/**
|
|
492
|
+
* 文件个数上限。无文件字段时应为 `0`。
|
|
493
|
+
*/
|
|
494
|
+
maxFiles: number;
|
|
495
|
+
/**
|
|
496
|
+
* 字段个数上限(文本字段 + 文件字段)。
|
|
497
|
+
* 默认值:`100`
|
|
498
|
+
*/
|
|
499
|
+
maxFields?: number;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* 请求体解析限制(`WebApp` 的 `body` 选项)。
|
|
503
|
+
*
|
|
504
|
+
* - `payload`:非文件请求体,整包读入内存
|
|
505
|
+
* - `formData`:`multipart/form-data` 上传
|
|
506
|
+
*/
|
|
507
|
+
interface ParseBodyOptions {
|
|
508
|
+
/**
|
|
509
|
+
* 非文件请求体限制。
|
|
510
|
+
*
|
|
511
|
+
* 适用 Content-Type:
|
|
512
|
+
* - `application/json`
|
|
513
|
+
* - `application/*+json`
|
|
514
|
+
* - `application/csp-report`
|
|
515
|
+
* - `application/x-www-form-urlencoded`
|
|
516
|
+
* - `text/*`
|
|
517
|
+
*
|
|
518
|
+
*/
|
|
519
|
+
payload?: {
|
|
99
520
|
/**
|
|
100
|
-
*
|
|
521
|
+
* 请求体大小上限。数字为字节;字符串如 `'2mb'`。
|
|
522
|
+
* 超出返回 `413` 状态码。
|
|
523
|
+
* 默认值:`2mb`
|
|
101
524
|
*/
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
get contentType(): string;
|
|
109
|
-
set contentType(typeOrFilenameOrExt: string);
|
|
110
|
-
get body(): Body;
|
|
111
|
-
set body(val: Body);
|
|
525
|
+
maxSize?: string | number;
|
|
526
|
+
};
|
|
527
|
+
/**
|
|
528
|
+
* `multipart/form-data` 限制。
|
|
529
|
+
*/
|
|
530
|
+
formData?: {
|
|
112
531
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
* @param filePath 路径
|
|
116
|
-
* @param type 附件类型。默认值:`attachment`
|
|
117
|
-
*
|
|
118
|
-
* @link https://developer.mozilla.org/zh_CN/docs/Web/HTTP/Headers/Content-Disposition
|
|
119
|
-
*
|
|
532
|
+
* 单个文件大小上限。数字为字节;字符串如 `'20mb'`。
|
|
533
|
+
* 默认值:`50mb`
|
|
120
534
|
*/
|
|
121
|
-
|
|
122
|
-
getHeader: {
|
|
123
|
-
(name: UpperStringHeaderKeys): string | undefined;
|
|
124
|
-
(name: UpperArrayHeaderKeys): string[] | undefined;
|
|
125
|
-
(name: string): string | string[] | undefined;
|
|
126
|
-
};
|
|
127
|
-
getHeaderNames: () => (UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {}))[];
|
|
128
|
-
getHeaders: () => OutgoingHttpHeaders;
|
|
129
|
-
flush(): void;
|
|
130
|
-
hasHeader: (name: UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {})) => boolean;
|
|
131
|
-
isJSON(value: Body): value is object;
|
|
132
|
-
matchContentType(type: string, ...types: string[]): string | null;
|
|
133
|
-
onError(error?: Error | HttpError | null): void;
|
|
134
|
-
redirect(url: string): void;
|
|
135
|
-
redirect(statusCode: 300 | 301 | 302 | 303 | 305 | 307 | 308, url: string): void;
|
|
136
|
-
removeCookie(name: string, options?: Pick<SerializeOptions, 'path'>): void;
|
|
137
|
-
removeHeader: (name: UpperStringHeaderKeys | UpperArrayHeaderKeys | (string & {})) => void;
|
|
138
|
-
removeHeaders(...headers: ((string & {}) | UpperStringHeaderKeys | UpperArrayHeaderKeys)[]): void;
|
|
139
|
-
setCookie(name: string, value: string, options?: SerializeOptions): void;
|
|
140
|
-
setHeader: {
|
|
141
|
-
<T extends WebResponse>(name: UpperStringHeaderKeys, value: number | string): T;
|
|
142
|
-
<T extends WebResponse>(name: UpperArrayHeaderKeys, value: readonly string[]): T;
|
|
143
|
-
<T extends WebResponse>(name: string, value: number | string | readonly string[]): T;
|
|
144
|
-
};
|
|
145
|
-
setHeaders(headers: Headers | Map<string, string | number | readonly string[]> | ({
|
|
146
|
-
[K: string]: string | number | readonly string[];
|
|
147
|
-
} & {
|
|
148
|
-
[K in UpperStringHeaderKeys]?: string | number;
|
|
149
|
-
} & {
|
|
150
|
-
[K in UpperArrayHeaderKeys]?: readonly string[];
|
|
151
|
-
})): this;
|
|
152
|
-
vary(field: UpperHeaderKeys | UpperHeaderKeys[] | (string & {}) | (string & {})[]): string;
|
|
153
|
-
protected setStatus(code: number): void;
|
|
154
|
-
protected updateContentType(): void;
|
|
155
|
-
protected getBodyType(body: Body): BodyType;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
declare class WebContext {
|
|
159
|
-
readonly app: WebApp;
|
|
160
|
-
readonly request: WebRequest;
|
|
161
|
-
readonly response: WebResponse;
|
|
162
|
-
readonly redirect: WebResponse['redirect'];
|
|
163
|
-
readonly download: WebResponse['download'];
|
|
164
|
-
constructor(app: WebApp, request: WebRequest, response: WebResponse);
|
|
535
|
+
maxFileSize?: string | number;
|
|
165
536
|
/**
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
* ctx.send(200, 'hello aomex');
|
|
169
|
-
* ctx.send({ count: 1 });
|
|
170
|
-
* ```
|
|
537
|
+
* 单次请求允许的文件个数上限。
|
|
538
|
+
* 默认值:`10`
|
|
171
539
|
*/
|
|
172
|
-
|
|
173
|
-
send(body: Body): void;
|
|
540
|
+
maxFiles?: number;
|
|
174
541
|
/**
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
* ```typescript
|
|
178
|
-
* ctx.throw(403);
|
|
179
|
-
* ctx.throw(400, 'name required');
|
|
180
|
-
* ctx.throw(400, new Error('invalid'));
|
|
181
|
-
* ctx.throw(500, new Error('server error'), { expose: true });
|
|
182
|
-
* ```
|
|
183
|
-
* @link https://github.com/jshttp/http-errors
|
|
184
|
-
* @throws {HttpError}
|
|
185
|
-
* @see createHttpError.HttpError
|
|
186
|
-
*
|
|
542
|
+
* 字段个数上限(文本字段与文件字段合计)。
|
|
543
|
+
* 默认值:`100`
|
|
187
544
|
*/
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
throw(statusCode: number, properties?: HttpErrorProperties): never;
|
|
545
|
+
maxFields?: number;
|
|
546
|
+
};
|
|
191
547
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
declare module '@aomex/common' {
|
|
203
|
-
interface MiddlewarePlatform {
|
|
204
|
-
readonly web: <Props extends object = object>(fn: WebMiddlewareArguments<Props>['fn'] | WebMiddlewareArguments<Props>) => WebMiddleware<Props>;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
interface OpenApiInjector {
|
|
208
|
-
onDocument?: (document: OpenAPI.Document) => void;
|
|
209
|
-
postDocument?: OpenApiInjector['onDocument'];
|
|
210
|
-
onPath?: (pathItem: OpenAPI.PathItemObject, opts: {
|
|
211
|
-
document: OpenAPI.Document;
|
|
212
|
-
pathName: string;
|
|
213
|
-
}) => void;
|
|
214
|
-
postPath?: OpenApiInjector['onPath'];
|
|
215
|
-
onMethod?: (methodItem: OpenAPI.OperationObject, opts: {
|
|
216
|
-
document: OpenAPI.Document;
|
|
217
|
-
pathName: string;
|
|
218
|
-
pathItem: OpenAPI.PathItemObject;
|
|
219
|
-
methodName: `${Lowercase<WebRequest['method']>}`;
|
|
220
|
-
}) => void;
|
|
221
|
-
postMethod?: OpenApiInjector['onMethod'];
|
|
548
|
+
/** 可被响应体套壳包裹的 body 形态(stream / buffer 不包) */
|
|
549
|
+
export type EnvelopeBodyType = Extract<BodyType, 'json' | 'string' | 'null'>;
|
|
550
|
+
/** 套壳时可读的内置变量(自定义 `slot` 的唯一入参) */
|
|
551
|
+
export interface EnvelopeVars {
|
|
552
|
+
/** 原 `statusCode < 400` */
|
|
553
|
+
success: boolean;
|
|
554
|
+
/** 原响应 body(仅 json / string / null) */
|
|
555
|
+
payload: object | string | null;
|
|
556
|
+
/** 改写前的 HTTP 状态码 */
|
|
557
|
+
statusCode: number;
|
|
222
558
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
559
|
+
declare const envelopeBuiltinBrand: unique symbol;
|
|
560
|
+
declare const envelopeCustomBrand: unique symbol;
|
|
561
|
+
/** 内置槽位:success / payload / statusCode */
|
|
562
|
+
export declare class EnvelopeBuiltinSlot<Kind extends 'success' | 'payload' | 'statusCode' = 'success' | 'payload' | 'statusCode'> {
|
|
563
|
+
readonly kind: Kind;
|
|
564
|
+
readonly [envelopeBuiltinBrand]: void;
|
|
565
|
+
constructor(kind: Kind);
|
|
226
566
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
567
|
+
/** 自定义槽位:OpenAPI 用 schema,运行时用 get */
|
|
568
|
+
export declare class EnvelopeCustomSlot<Schema extends ValidatorToken = ValidatorToken> {
|
|
569
|
+
readonly schema: Schema;
|
|
570
|
+
readonly get: (vars: EnvelopeVars) => Validator.Infer<Schema>;
|
|
571
|
+
readonly [envelopeCustomBrand]: void;
|
|
572
|
+
constructor(schema: Schema, get: (vars: EnvelopeVars) => Validator.Infer<Schema>);
|
|
233
573
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
574
|
+
/**
|
|
575
|
+
* 响应体套壳声明树:只允许内置槽位、`envelope.slot`、以及嵌套普通对象。
|
|
576
|
+
* 禁止直接塞 `rule.*`(无运行时取值来源)。
|
|
577
|
+
*/
|
|
578
|
+
export type EnvelopeContent = EnvelopeBuiltinSlot<'success' | 'payload' | 'statusCode'> | EnvelopeCustomSlot<ValidatorToken> | {
|
|
579
|
+
readonly [key: string]: EnvelopeContent;
|
|
580
|
+
};
|
|
581
|
+
export interface EnvelopeOptions {
|
|
582
|
+
/**
|
|
583
|
+
* 套壳结构(声明式)。用内置槽位与 `envelope.slot` 拼装;
|
|
584
|
+
* OpenAPI / 运行时均遍历此树替换槽位,不执行用户工厂函数。
|
|
585
|
+
*/
|
|
586
|
+
content: EnvelopeContent;
|
|
587
|
+
description?: string;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* 运行时套壳:在 `flush` 写出前调用。
|
|
591
|
+
* 固定 HTTP `200`;跳过 stream、buffer、SSE、3xx、无内容状态码(204/205/304)。
|
|
592
|
+
*/
|
|
593
|
+
export declare const applyResponseEnvelope: (res: WebResponse, options: EnvelopeOptions) => void;
|
|
594
|
+
/**
|
|
595
|
+
* OpenAPI:在其它中间件的 `postMethod` 之后调用,将 2xx / 4xx·5xx·default 收成 `200`。
|
|
596
|
+
* 保留 3xx 与无内容状态码(204/205/304),与运行时跳过规则一致。
|
|
597
|
+
*/
|
|
598
|
+
export declare const createEnvelopeOpenApiInjector: (options: EnvelopeOptions) => OpenApiInjector;
|
|
599
|
+
/**
|
|
600
|
+
* 响应体套壳槽位(配置给 `WebApp.envelope`)。
|
|
601
|
+
*
|
|
602
|
+
* - 内置:`envelope.success` / `envelope.payload` / `envelope.statusCode`
|
|
603
|
+
* - 自定义:`envelope.slot(schema, get)`,`get` 只读 `{ success, payload, statusCode }`
|
|
604
|
+
*
|
|
605
|
+
* ```ts
|
|
606
|
+
* new WebApp({
|
|
607
|
+
* envelope: {
|
|
608
|
+
* content: {
|
|
609
|
+
* success: envelope.success,
|
|
610
|
+
* statusCode: envelope.statusCode,
|
|
611
|
+
* data: envelope.payload,
|
|
612
|
+
* version: envelope.slot(rule.string(), () => '1.0'),
|
|
613
|
+
* },
|
|
614
|
+
* },
|
|
615
|
+
* mount: [formatError({ ... })],
|
|
616
|
+
* // ...
|
|
617
|
+
* });
|
|
618
|
+
* ```
|
|
619
|
+
*/
|
|
620
|
+
export declare const envelope: {
|
|
621
|
+
/** 原请求是否业务成功(`statusCode < 400`);OpenAPI 成败支分别固定为 `true` / `false` */
|
|
622
|
+
success: EnvelopeBuiltinSlot<"success">;
|
|
623
|
+
/** 套壳前的响应 body(仅 json / string / null);OpenAPI 替换为对应状态支的内层 schema */
|
|
624
|
+
payload: EnvelopeBuiltinSlot<"payload">;
|
|
625
|
+
/** 套壳前的 HTTP 状态码(写出后仍固定为 200) */
|
|
626
|
+
statusCode: EnvelopeBuiltinSlot<"statusCode">;
|
|
627
|
+
/**
|
|
628
|
+
* 自定义槽位:`schema` 供 OpenAPI;`get(vars)` 供运行时取值。
|
|
629
|
+
* `vars` 仅含 `{ success, payload, statusCode }`,勿依赖其它上下文。
|
|
630
|
+
*/
|
|
631
|
+
slot: <Schema extends ValidatorToken>(schema: Schema, get: (vars: EnvelopeVars) => Validator.Infer<Schema>) => EnvelopeCustomSlot<Schema>;
|
|
632
|
+
};
|
|
633
|
+
export declare namespace WebApp {
|
|
634
|
+
type Logger = PromisifiedService<BaseLoggerService>;
|
|
635
|
+
interface Option<T extends WebMiddlewareToken[] | []> {
|
|
255
636
|
/**
|
|
256
|
-
*
|
|
637
|
+
* 全局中间件
|
|
257
638
|
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
*
|
|
639
|
+
* ```typescript
|
|
640
|
+
* const app = new WebApp({
|
|
641
|
+
* services,
|
|
642
|
+
* logger: services.logger,
|
|
643
|
+
* language: { mode: 'fixed', language: 'zh-CN' },
|
|
644
|
+
* proxyIP: { mode: 'detect' },
|
|
645
|
+
* mount: [md1, md2],
|
|
646
|
+
* });
|
|
647
|
+
*
|
|
648
|
+
* declare module '@aomex/web' {
|
|
649
|
+
* namespace WebApp {
|
|
650
|
+
* type T = WebApp.Infer<typeof app>;
|
|
651
|
+
* interface Props extends T {}
|
|
652
|
+
* }
|
|
653
|
+
* }
|
|
654
|
+
* ```
|
|
263
655
|
*/
|
|
264
|
-
|
|
656
|
+
mount?: T;
|
|
265
657
|
/**
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
658
|
+
* 响应体套壳:在 `flush` 写出前包进声明结构,固定 HTTP `200`。
|
|
659
|
+
* 成功与错误(含无 `formatError` 的默认纯文本)都经 `flush` 统一套壳。
|
|
660
|
+
*
|
|
661
|
+
* ```ts
|
|
662
|
+
* import { envelope } from '@aomex/web';
|
|
663
|
+
*
|
|
664
|
+
* new WebApp({
|
|
665
|
+
* envelope: {
|
|
666
|
+
* content: {
|
|
667
|
+
* success: envelope.success,
|
|
668
|
+
* data: envelope.payload,
|
|
669
|
+
* statusCode: envelope.statusCode,
|
|
670
|
+
* },
|
|
671
|
+
* },
|
|
672
|
+
* mount: [formatError({ ... })],
|
|
673
|
+
* // ...
|
|
674
|
+
* });
|
|
269
675
|
* ```
|
|
270
676
|
*/
|
|
271
|
-
|
|
272
|
-
mimeTypes(mineOrExt: string[]): this;
|
|
273
|
-
protected isEmpty(value: any): boolean;
|
|
274
|
-
protected validateValue(file: FileValidator.FormidableFile, _key: string, label: string): ValidateResult.Any<FileValidator.FormidableFile>;
|
|
275
|
-
protected copy: () => FileValidator<T>;
|
|
276
|
-
protected toDocument(): OpenAPI.SchemaObject;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
declare namespace WebApp {
|
|
280
|
-
interface Option<T extends WebMiddlewareToken[] | []> {
|
|
281
|
-
/**
|
|
282
|
-
* 调试模式。默认值:`process.env.NODE_ENV !== 'production'`
|
|
283
|
-
*
|
|
284
|
-
* 如果开启,则`5xx`异常会响应真实的错误信息。
|
|
285
|
-
*/
|
|
286
|
-
debug?: boolean;
|
|
287
|
-
/**
|
|
288
|
-
* 全局中间件
|
|
289
|
-
*
|
|
290
|
-
* ```typescript
|
|
291
|
-
* const app = new WebApp({
|
|
292
|
-
* mount: [md1, md2]
|
|
293
|
-
* });
|
|
294
|
-
*
|
|
295
|
-
* declare module '@aomex/web' {
|
|
296
|
-
* namespace WebApp {
|
|
297
|
-
* type T = WebApp.Infer<typeof app>;
|
|
298
|
-
* interface Props extends T {}
|
|
299
|
-
* }
|
|
300
|
-
* }
|
|
301
|
-
* ```
|
|
302
|
-
*/
|
|
303
|
-
mount?: T;
|
|
304
|
-
language?: 'zh_CN' | 'en_US' | (string & {});
|
|
305
|
-
}
|
|
306
|
-
type Infer<T> = T extends WebApp<infer U> ? U extends any[] ? Union2Intersection<Middleware.CollectArrayType<U[number]>> : unknown : unknown;
|
|
307
|
-
interface Props {
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
declare class WebApp<T extends WebMiddlewareToken[] | [] = any[]> extends stream.EventEmitter<{
|
|
311
|
-
error: [err: HttpError, ctx: WebContext & WebApp.Props];
|
|
312
|
-
}> {
|
|
313
|
-
protected readonly options: WebApp.Option<T>;
|
|
314
|
-
protected readonly point?: string;
|
|
315
|
-
protected readonly middlewareList: WebMiddlewareToken[];
|
|
316
|
-
constructor(options?: WebApp.Option<T>);
|
|
317
|
-
get debug(): boolean;
|
|
318
|
-
callback(): http.RequestListener<any, any>;
|
|
677
|
+
envelope?: EnvelopeOptions;
|
|
319
678
|
/**
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
|
|
679
|
+
* `combineServices` 的返回值(单个或数组)。
|
|
680
|
+
* 关停:SIGINT/SIGTERM → `server.close()` → 再 await 销毁已加载服务。
|
|
681
|
+
*/
|
|
682
|
+
services: CombinedServices | readonly CombinedServices[];
|
|
683
|
+
/**
|
|
684
|
+
* 优雅关停:`SIGINT`/`SIGTERM` → `close` → 超时则强制断开 → 销毁服务 → 退出。
|
|
685
|
+
* @default { timeout: 5_000 }
|
|
686
|
+
*/
|
|
687
|
+
shutdown?: ShutdownOption;
|
|
688
|
+
/**
|
|
689
|
+
* 经 `combineServices` 处理后的 logger(通常为 `services.logger`)。
|
|
690
|
+
* 默认 `error` 监听 / `ctx.logger` 均走此实例。
|
|
691
|
+
*
|
|
692
|
+
* ```ts
|
|
693
|
+
* const services = await combineServices(
|
|
694
|
+
* { logger: () => import('./logger.service.js') },
|
|
695
|
+
* { eager: ['logger'] },
|
|
696
|
+
* );
|
|
697
|
+
* new WebApp({
|
|
698
|
+
* services,
|
|
699
|
+
* logger: services.logger,
|
|
700
|
+
* language: { mode: 'fixed', language: 'zh-CN' },
|
|
701
|
+
* proxyIP: { mode: 'detect' },
|
|
702
|
+
* });
|
|
323
703
|
* ```
|
|
324
704
|
*/
|
|
325
|
-
|
|
705
|
+
logger: Logger;
|
|
326
706
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
707
|
+
* 语言。
|
|
708
|
+
*
|
|
709
|
+
* - `mode: 'fixed'`:整站固定为 `language`(内置规范码,如 `zh-CN`)。
|
|
710
|
+
* - `mode: 'dynamic'`:按请求头协商。`zh_CN`、`zh-cn` 等别名会归一到规范码;都不中则用必填的 `fallback`。
|
|
711
|
+
*
|
|
712
|
+
* ```ts
|
|
713
|
+
* language: { mode: 'fixed', language: 'zh-CN' }
|
|
714
|
+
* language: { mode: 'dynamic', fallback: 'zh-CN' }
|
|
715
|
+
* language: { mode: 'dynamic', header: 'x-language', fallback: 'en-US' }
|
|
330
716
|
* ```
|
|
331
717
|
*/
|
|
332
|
-
|
|
333
|
-
listen: {
|
|
334
|
-
(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
335
|
-
(port?: number, hostname?: string, listeningListener?: () => void): http.Server<any, any>;
|
|
336
|
-
(port?: number, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
337
|
-
(port?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
338
|
-
(path: string, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
339
|
-
(path: string, listeningListener?: () => void): http.Server<any, any>;
|
|
340
|
-
(options: net.ListenOptions, listeningListener?: () => void): http.Server<any, any>;
|
|
341
|
-
(handle: any, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
342
|
-
(handle: any, listeningListener?: () => void): http.Server<any, any>;
|
|
343
|
-
};
|
|
344
|
-
};
|
|
718
|
+
language: LanguageOption;
|
|
345
719
|
/**
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
720
|
+
* 客户端 IP 解析(`ctx.request.ip`)。
|
|
721
|
+
*
|
|
722
|
+
* - `mode: 'detect'`:探测 `X-Forwarded-For` / `X-Real-IP` / `CF-Connecting-IP` 等常见头
|
|
723
|
+
* (可被伪造,适合本地/测试)。
|
|
724
|
+
* - `mode: 'specify'`:按 `header` / `hops` 严格取值(生产推荐)。
|
|
725
|
+
*
|
|
726
|
+
* ```ts
|
|
727
|
+
* proxyIP: { mode: 'detect' }
|
|
728
|
+
* proxyIP: { mode: 'specify', header: 'x-forwarded-for', hops: 1 }
|
|
729
|
+
* ```
|
|
730
|
+
*/
|
|
731
|
+
proxyIP: ProxyIPOption;
|
|
732
|
+
/**
|
|
733
|
+
* 请求体解析限制。
|
|
734
|
+
*
|
|
735
|
+
* - `payload`:json / urlencoded / text(整包进内存)
|
|
736
|
+
* - `formData`:`multipart/form-data`(与路由 `body()` 取更严)
|
|
737
|
+
*
|
|
738
|
+
* ```ts
|
|
739
|
+
* body: {
|
|
740
|
+
* payload: { maxSize: '2mb' },
|
|
741
|
+
* formData: {
|
|
742
|
+
* maxFileSize: '20mb',
|
|
743
|
+
* maxFiles: 10,
|
|
744
|
+
* maxFields: 100,
|
|
745
|
+
* },
|
|
746
|
+
* }
|
|
349
747
|
* ```
|
|
350
748
|
*/
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
749
|
+
body?: ParseBodyOptions;
|
|
750
|
+
}
|
|
751
|
+
interface ShutdownOption {
|
|
752
|
+
/**
|
|
753
|
+
* 等待在途请求结束的上限(毫秒)。超时后 `closeAllConnections`。
|
|
754
|
+
* @default 5000
|
|
755
|
+
*/
|
|
756
|
+
timeout?: number;
|
|
757
|
+
}
|
|
758
|
+
type LanguageOption = {
|
|
759
|
+
mode: 'fixed';
|
|
760
|
+
/** 固定使用的语言。 */
|
|
761
|
+
language: I18nLanguage;
|
|
762
|
+
} | {
|
|
763
|
+
mode: 'dynamic';
|
|
764
|
+
/**
|
|
765
|
+
* 读取的请求头。默认 `accept-language`。
|
|
766
|
+
* `accept-language` 按 q 值排序;其它头按逗号分隔、忽略 q。
|
|
767
|
+
*/
|
|
768
|
+
header?: string;
|
|
769
|
+
/** 请求头缺失或无法匹配时的语言。 */
|
|
770
|
+
fallback: I18nLanguage;
|
|
771
|
+
};
|
|
772
|
+
type ProxyIPOption = {
|
|
773
|
+
/** 探测常见代理头(可被伪造)。 */
|
|
774
|
+
mode: 'detect';
|
|
775
|
+
} | {
|
|
776
|
+
/** 按指定头与代理层数严格解析。 */
|
|
777
|
+
mode: 'specify';
|
|
778
|
+
/**
|
|
779
|
+
* 读取的代理 IP 头。
|
|
780
|
+
*/
|
|
781
|
+
header: 'x-forwarded-for' | 'x-real-ip' | 'forwarded' | 'cf-connecting-ip' | 'fastly-client-ip' | 'true-client-ip' | 'x-cluster-client-ip' | 'x-appengine-user-ip' | (string & {});
|
|
782
|
+
/**
|
|
783
|
+
* 前置反向代理层数。
|
|
784
|
+
* - `=0`:忽略代理头,`request.ip` 等于 `socket.remoteAddress`
|
|
785
|
+
* (直连客户端;若经反向代理则多为代理本机 IP)
|
|
786
|
+
* - `>0`:从代理头右侧截取 n 段,再取其中最左的合法 IP(防 `X-Forwarded-For` 左侧伪造)
|
|
787
|
+
*
|
|
788
|
+
* 场景举例:
|
|
789
|
+
* - `0`:本机直连 / 强制不信代理头
|
|
790
|
+
* - `1`:单层 Nginx/Caddy(`proxy_add_x_forwarded_for` 追加)
|
|
791
|
+
* - `2`:Cloudflare + Nginx 两层追加(CF 先写,Nginx 再 `proxy_add_x_forwarded_for`)
|
|
792
|
+
* - `1` + `header: 'cf-connecting-ip'`:Cloudflare + Nginx,且 Nginx 透传
|
|
793
|
+
* `CF-Connecting-IP`(只信任该头,避免读到节点 IP)
|
|
794
|
+
* - `1` + `header: 'x-real-ip'`:反向代理覆盖写入
|
|
795
|
+
* (如 `proxy_set_header X-Real-IP $remote_addr`)
|
|
796
|
+
*/
|
|
797
|
+
hops: number;
|
|
798
|
+
};
|
|
799
|
+
type Infer<T> = T extends WebApp<infer U> ? U extends any[] ? Union2Intersection<Middleware.CollectArrayType<U[number]>> : unknown : unknown;
|
|
800
|
+
interface Props {}
|
|
801
|
+
}
|
|
802
|
+
export declare class WebApp<T extends WebMiddlewareToken[] | [] = any[]> extends stream.EventEmitter<{
|
|
803
|
+
error: [err: HttpError, ctx: WebContext & WebApp.Props];
|
|
804
|
+
}> {
|
|
805
|
+
protected readonly options: WebApp.Option<T>;
|
|
806
|
+
protected readonly middlewareList: WebMiddlewareToken[];
|
|
807
|
+
protected readonly logger: WebApp.Logger;
|
|
808
|
+
constructor(options: WebApp.Option<T>);
|
|
809
|
+
/**
|
|
810
|
+
* `fixed` 直接返回配置语言;`dynamic` 从请求头协商。
|
|
811
|
+
*/
|
|
812
|
+
protected resolveLanguage(ctx: WebContext): string;
|
|
813
|
+
protected readLanguageHeader(ctx: WebContext, name: string): string[];
|
|
814
|
+
protected bindServerLifecycle(server: http.Server | https.Server): void;
|
|
815
|
+
callback(): http.RequestListener<any, any>;
|
|
816
|
+
/**
|
|
817
|
+
* 监听http服务
|
|
818
|
+
* ```typescript
|
|
819
|
+
* app.listen(3000);
|
|
820
|
+
* ```
|
|
821
|
+
*/
|
|
822
|
+
listen: http.Server['listen'];
|
|
823
|
+
/**
|
|
824
|
+
* 监听http服务,可定制参数
|
|
825
|
+
* ```typescript
|
|
826
|
+
* app.http({...}).listen(3000);
|
|
827
|
+
* ```
|
|
828
|
+
*/
|
|
829
|
+
http(options: Omit<http.ServerOptions, 'IncomingMessage' | 'ServerResponse'>): {
|
|
830
|
+
listen: {
|
|
831
|
+
(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
832
|
+
(port?: number, hostname?: string, listeningListener?: () => void): http.Server<any, any>;
|
|
833
|
+
(port?: number, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
834
|
+
(port?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
835
|
+
(path: string, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
836
|
+
(path: string, listeningListener?: () => void): http.Server<any, any>;
|
|
837
|
+
(options: import("net").ListenOptions, listeningListener?: () => void): http.Server<any, any>;
|
|
838
|
+
(handle: any, backlog?: number, listeningListener?: () => void): http.Server<any, any>;
|
|
839
|
+
(handle: any, listeningListener?: () => void): http.Server<any, any>;
|
|
363
840
|
};
|
|
364
|
-
|
|
841
|
+
};
|
|
842
|
+
/**
|
|
843
|
+
* 监听https服务,需提供证书
|
|
844
|
+
* ```typescript
|
|
845
|
+
* app.https({...}).listen(3000);
|
|
846
|
+
* ```
|
|
847
|
+
*/
|
|
848
|
+
https(options: Omit<https.ServerOptions, 'IncomingMessage' | 'ServerResponse'>): {
|
|
849
|
+
listen: {
|
|
850
|
+
(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): https.Server<any, any>;
|
|
851
|
+
(port?: number, hostname?: string, listeningListener?: () => void): https.Server<any, any>;
|
|
852
|
+
(port?: number, backlog?: number, listeningListener?: () => void): https.Server<any, any>;
|
|
853
|
+
(port?: number, listeningListener?: () => void): https.Server<any, any>;
|
|
854
|
+
(path: string, backlog?: number, listeningListener?: () => void): https.Server<any, any>;
|
|
855
|
+
(path: string, listeningListener?: () => void): https.Server<any, any>;
|
|
856
|
+
(options: import("net").ListenOptions, listeningListener?: () => void): https.Server<any, any>;
|
|
857
|
+
(handle: any, backlog?: number, listeningListener?: () => void): https.Server<any, any>;
|
|
858
|
+
(handle: any, listeningListener?: () => void): https.Server<any, any>;
|
|
859
|
+
};
|
|
860
|
+
};
|
|
365
861
|
}
|
|
366
|
-
|
|
367
862
|
/**
|
|
368
|
-
*
|
|
863
|
+
* 从 body schema 收集 multipart 文件白名单与体积/数量上限。
|
|
864
|
+
* 字段名是平铺的,只认对象这一层的名字,不进入嵌套 object。
|
|
865
|
+
*
|
|
866
|
+
* `maxFileSize` 只在出现 `file().maxSize()` 时带出,多个取较大值;
|
|
867
|
+
* 没写则交给 `ensureBody` / 应用 `formData` 上限。
|
|
868
|
+
*
|
|
869
|
+
* 会收集:
|
|
870
|
+
* - `object({ avatar: file() })`:1 个
|
|
871
|
+
* - `object({ photos: array(file()).length({ max }) })`:个数为 `max`,缺省为 `DEFAULT_MAX_FILES`
|
|
872
|
+
* - 同一 object 上多个文件字段:名字都要,个数相加,`maxSize` 取较大值
|
|
873
|
+
* - 字段上的 `oneOf` / `anyOf` / `allOf`(分支是 `file` 或 `array(file)`):收录该字段,个数取各分支较大值
|
|
874
|
+
* `oneOf([file(), array(file()).length({ max: 3 })])` → 3
|
|
875
|
+
* `array(oneOf([file(), string()]))` → 用 array 的 `length.max`
|
|
876
|
+
* - 根是 `oneOf` / `anyOf`,分支是 object(可再套组合):字段名取并集,个数取各分支较大值
|
|
877
|
+
* `anyOf([object({ avatar: file() }), object({ name: string() })])` → `avatar`
|
|
878
|
+
* `oneOf([object({ avatar: file() }), object({ photos: array(file()).length({ max: 3 }) })])` → 3
|
|
879
|
+
* - 根是 `allOf`,分支是 object:字段名取并集(同名只留一次),个数相加
|
|
880
|
+
* `allOf([object({ avatar: file() }), object({ cover: file() })])` → 2
|
|
881
|
+
* - 根是 `array(object({ avatar: file() }))`:收录对象顶层的 `avatar`。
|
|
882
|
+
* 外层 array 的 `length.max` 不参与个数
|
|
883
|
+
*
|
|
884
|
+
* 不收集:
|
|
885
|
+
* - 根不是 object,也没有能展开出文件字段的子节点,如 `string()` / `array(file())` / `file()`
|
|
886
|
+
* - 组合分支里没有带文件字段的 object
|
|
887
|
+
* - 嵌套 object:`object({ profile: object({ avatar: file() }) })`
|
|
888
|
+
* - 字段上的组合或 array 只含 object:`oneOf([object({ f: file() }), string()])`、
|
|
889
|
+
* `array(object({ file: file() }))`
|
|
890
|
+
*/
|
|
891
|
+
export declare const getFileUploadOptions: (fields: ValidatorToken) => EnsureBodyOptions;
|
|
892
|
+
/**
|
|
893
|
+
* 验证请求实体。`multipart` 时按 schema 解析(仅白名单字段收文件)。
|
|
369
894
|
*/
|
|
370
|
-
declare const body: <T extends {
|
|
371
|
-
|
|
372
|
-
}, P extends Validator>(fields: T) => WebMiddleware<{
|
|
373
|
-
readonly body: Validator.Infer<T>;
|
|
895
|
+
export declare const body: <T extends ValidatorToken>(fields: T) => WebMiddleware<{
|
|
896
|
+
readonly body: Validator.Infer<T>;
|
|
374
897
|
}>;
|
|
375
|
-
|
|
376
898
|
/**
|
|
377
899
|
* 验证请求查询字符串
|
|
378
900
|
*/
|
|
379
|
-
declare const query: <T extends {
|
|
380
|
-
|
|
381
|
-
}, P extends Validator>(fields: T) => WebMiddleware<{
|
|
382
|
-
readonly query: Validator.Infer<T>;
|
|
901
|
+
export declare const query: <T extends ValidatorFieldTable | ValidatorSchema<any>>(fields: T) => WebMiddleware<{
|
|
902
|
+
readonly query: Validator.Infer<T>;
|
|
383
903
|
}>;
|
|
384
|
-
|
|
385
904
|
/**
|
|
386
905
|
* 验证请求路径参数
|
|
387
906
|
*/
|
|
388
|
-
declare const params: <T extends {
|
|
389
|
-
|
|
390
|
-
}, P extends Validator>(fields: T) => WebMiddleware<{
|
|
391
|
-
readonly params: Validator.Infer<T>;
|
|
907
|
+
export declare const params: <T extends ValidatorFieldTable | ValidatorSchema<any>>(fields: T) => WebMiddleware<{
|
|
908
|
+
readonly params: Validator.Infer<T>;
|
|
392
909
|
}>;
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
type EmptyStatus = 204 | 205 | 304;
|
|
396
|
-
type RedirectStatus = 300 | 301 | 302 | 303 | 305 | 307 | 308;
|
|
397
|
-
type ClientErrorStatus = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 431 | 451;
|
|
398
|
-
type ServerErrorStatus = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511;
|
|
399
|
-
type HttpStatus = OKStatus | EmptyStatus | RedirectStatus | ClientErrorStatus | ServerErrorStatus;
|
|
400
|
-
interface WebResponseOptions<Code extends HttpStatus, Content extends ValidatorToken> extends Pick<OpenAPI.MediaTypeObject, 'example'> {
|
|
401
|
-
statusCode: Code;
|
|
402
|
-
/**
|
|
403
|
-
* 响应格式,支持简写和完整写法。如果不填,则根据content的结构判断
|
|
404
|
-
*
|
|
405
|
-
* 包括但不限于如下类型:
|
|
406
|
-
* - application/json
|
|
407
|
-
* - application/*
|
|
408
|
-
* - json
|
|
409
|
-
* - text
|
|
410
|
-
* - binary
|
|
411
|
-
* - html
|
|
412
|
-
* - stream
|
|
413
|
-
*/
|
|
414
|
-
contentType?: string;
|
|
415
|
-
/**
|
|
416
|
-
* 响应内容结构
|
|
417
|
-
*/
|
|
418
|
-
content?: Content;
|
|
419
|
-
/**
|
|
420
|
-
* 报文结构
|
|
421
|
-
*/
|
|
422
|
-
headers?: {
|
|
423
|
-
[key: string]: Validator;
|
|
424
|
-
};
|
|
425
|
-
description?: string;
|
|
910
|
+
export interface WebResponseOptions<Code extends HttpStatus, Content extends ValidatorToken> extends WebResponseMediaOptions<Content> {
|
|
911
|
+
statusCode: Code;
|
|
426
912
|
}
|
|
427
|
-
declare class WebResponseMiddleware<Code extends HttpStatus, Content extends ValidatorToken> extends WebMiddleware<Code extends 200 ? unknown extends Validator.Infer<Content> ? {
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
913
|
+
export declare class WebResponseMiddleware<Code extends HttpStatus, Content extends ValidatorToken> extends WebMiddleware<Code extends 200 ? unknown extends Validator.Infer<Content> ? {
|
|
914
|
+
/**
|
|
915
|
+
* 来自response中间件定制的send()方法。200状态码可以忽略不写
|
|
916
|
+
*/
|
|
917
|
+
send(statusCode: Code): void;
|
|
918
|
+
send(): void;
|
|
433
919
|
} : {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
920
|
+
/**
|
|
921
|
+
* 来自response中间件定制的send()方法。200状态码可以忽略不写
|
|
922
|
+
*/
|
|
923
|
+
send(statusCode: Code, body: Extract<Validator.Infer<Content>, Body>): void;
|
|
924
|
+
send(body: Extract<Validator.Infer<Content>, Body>): void;
|
|
439
925
|
} : Code extends OKStatus ? unknown extends Validator.Infer<Content> ? {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
926
|
+
/**
|
|
927
|
+
* 来自response中间件定制的send()方法
|
|
928
|
+
*/
|
|
929
|
+
send(statusCode: Code): void;
|
|
444
930
|
} : {
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
931
|
+
/**
|
|
932
|
+
* 来自response中间件定制的send()方法
|
|
933
|
+
*/
|
|
934
|
+
send(statusCode: Code, body: Extract<Validator.Infer<Content>, Body>): void;
|
|
449
935
|
} : Code extends EmptyStatus ? {
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
936
|
+
/**
|
|
937
|
+
* 来自response中间件定制的send()方法。空状态码无需响应数据
|
|
938
|
+
*/
|
|
939
|
+
send(statusCode: Code): void;
|
|
940
|
+
send(statusCode: Code, body: null): void;
|
|
455
941
|
} : Code extends RedirectStatus ? {
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
942
|
+
/**
|
|
943
|
+
* 来自response中间件定制的redirect()方法
|
|
944
|
+
*/
|
|
945
|
+
redirect(statusCode: Code, url: string): void;
|
|
460
946
|
} : {
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
947
|
+
/**
|
|
948
|
+
* 来自response中间件定制的throw()方法
|
|
949
|
+
*/
|
|
950
|
+
throw(statusCode: Code, message?: string | Error, properties?: HttpErrorProperties): never;
|
|
951
|
+
throw(statusCode: Code, properties?: HttpErrorProperties): never;
|
|
466
952
|
}> {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
953
|
+
protected readonly options: WebResponseOptions<Code, Content>;
|
|
954
|
+
constructor(options: WebResponseOptions<Code, Content>);
|
|
955
|
+
protected openapi(): OpenApiInjector;
|
|
956
|
+
protected getContentType(): string;
|
|
957
|
+
/** 优先读对应状态键,再回退 `x-response-format-default` */
|
|
958
|
+
protected peekResponseFormat(methodItem: OpenAPI.OperationObject, statusCode: number): OpenAPI.ResponseObject | undefined;
|
|
471
959
|
}
|
|
472
960
|
/**
|
|
473
961
|
* 响应数据声明。多个状态码时请多次调用函数。
|
|
474
962
|
* - 生成openapi文档
|
|
475
963
|
* - 静态类型约束,以保证运行时和文档一致
|
|
964
|
+
*
|
|
965
|
+
* 错误状态若只声明 `statusCode`、不写 `content`:整份借用
|
|
966
|
+
* `x-response-format-{code}` / `default`(含 description、content、headers),
|
|
967
|
+
* 再按本中间件显式字段单点覆盖。
|
|
476
968
|
*/
|
|
477
|
-
declare const response: <Code extends HttpStatus, Content extends ValidatorToken>(options: WebResponseOptions<Code, Content>) => WebResponseMiddleware<Code, Content>;
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
969
|
+
export declare const response: <Code extends HttpStatus, Content extends ValidatorToken>(options: WebResponseOptions<Code, Content>) => WebResponseMiddleware<Code, Content>;
|
|
970
|
+
/**
|
|
971
|
+
* OpenAPI 临时约定键前缀。具体键:
|
|
972
|
+
* - `x-response-format-default`:未指定 `statusCodes`(接管全部)
|
|
973
|
+
* - `x-response-format-400` 等:每个声明的状态码各一个
|
|
974
|
+
* 值为完整 `ResponseObject`,供无 `content` 的 `response` 整份借用后单点覆盖;
|
|
975
|
+
* `postMethod` 清理。
|
|
976
|
+
*/
|
|
977
|
+
export declare const X_RESPONSE_FORMAT_PREFIX = "x-response-format-";
|
|
978
|
+
export declare const X_RESPONSE_FORMAT_DEFAULT = "x-response-format-default";
|
|
979
|
+
export declare const responseFormatKey: (statusCode: number | 'default') => string;
|
|
980
|
+
/**
|
|
981
|
+
* 交给 `formatError.handler` 的公开错误视图。
|
|
982
|
+
* 写响应请用 `message` / `code` 等顶层字段(已净化)。
|
|
983
|
+
*/
|
|
984
|
+
export interface FormatErrorPublic {
|
|
985
|
+
statusCode: HttpErrorStatus;
|
|
986
|
+
/** 业务/系统错误码 */
|
|
987
|
+
code?: string;
|
|
988
|
+
/**
|
|
989
|
+
* 已净化文案:
|
|
990
|
+
* - `expose` → 原始 `HttpError.message`
|
|
991
|
+
* - 否则 → statuses 标准文案
|
|
992
|
+
*/
|
|
993
|
+
message: string;
|
|
994
|
+
/** 原始 `HttpError.expose` */
|
|
995
|
+
expose: boolean;
|
|
996
|
+
/**
|
|
997
|
+
* 未净化的完整 {@link HttpError}(特殊旁路)。
|
|
998
|
+
*
|
|
999
|
+
* @deprecated 警告:切勿把 `raw.message` / `raw.stack` / `raw.cause` 写入响应;
|
|
1000
|
+
* 响应文案用顶层 `message`。常规日志请用 `app.on('error')`。
|
|
1001
|
+
*/
|
|
1002
|
+
raw: HttpError;
|
|
500
1003
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
1004
|
+
/** `handler` 返回值:有 `content` 时必须对齐推断;无 `content` 时可任意 Body 或省略 */
|
|
1005
|
+
export type FormatErrorHandlerResult<Content extends ValidatorToken> = unknown extends Validator.Infer<Content> ? Body | void : Validator.Infer<Content>;
|
|
1006
|
+
/**
|
|
1007
|
+
* 禁止对象返回值携带 `Shape` 之外的键(多余字段 → `never`)。
|
|
1008
|
+
* 原始类型 / 数组 / void / 带 string 索引的类型不做键级收紧。
|
|
1009
|
+
*/
|
|
1010
|
+
type NoExcessKeys<T, Shape> = [T] extends [void] ? T : [T] extends [readonly unknown[]] ? T : [T] extends [object] ? string extends keyof T ? T : Exclude<keyof T, keyof Shape | number | symbol> extends never ? T : never : T;
|
|
1011
|
+
export type FormatErrorOptions<Content extends ValidatorToken = ValidatorToken, R extends FormatErrorHandlerResult<Content> = FormatErrorHandlerResult<Content>> = WebResponseMediaOptions<Content> & {
|
|
1012
|
+
/**
|
|
1013
|
+
* 仅处理这些状态码(运行时 + OpenAPI)。
|
|
1014
|
+
* - 省略:接管全部错误,写 `responses.default` + `x-response-format-default`
|
|
1015
|
+
* - 指定:只有列表内状态进入;每个 code 写 `responses[code]` + `x-response-format-{code}`
|
|
1016
|
+
*/
|
|
1017
|
+
statusCodes?: readonly HttpErrorStatus[];
|
|
1018
|
+
/**
|
|
1019
|
+
* 返回响应体;status / `err.headers` 已由中间件写好。
|
|
1020
|
+
* 有 `content` 时返回值不得含声明外的多余字段。
|
|
1021
|
+
* 写响应请用已净化字段;`err.raw` 见 {@link FormatErrorPublic.raw} 警告。
|
|
1022
|
+
*/
|
|
1023
|
+
handler: (err: FormatErrorPublic) => unknown extends Validator.Infer<Content> ? FormatErrorHandlerResult<Content> | Promise<FormatErrorHandlerResult<Content>> : NoExcessKeys<R, Validator.Infer<Content>> | Promise<NoExcessKeys<R, Validator.Infer<Content>>>;
|
|
1024
|
+
};
|
|
1025
|
+
export declare class FormatErrorMiddleware<Content extends ValidatorToken> extends WebMiddleware {
|
|
1026
|
+
protected readonly options: FormatErrorOptions<Content>;
|
|
1027
|
+
constructor(options: FormatErrorOptions<Content>);
|
|
1028
|
+
/** 生成可安全导出的公开视图(与默认 `onError` 同一套 expose 规则) */
|
|
1029
|
+
protected toPublic(err: HttpError): FormatErrorPublic;
|
|
1030
|
+
protected openapi(): OpenApiInjector;
|
|
1031
|
+
protected getContentType(): string;
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* 错误响应格式化:`handler` 返回 body 后重新抛出,
|
|
1035
|
+
* 外侧中间件的 `catch` 仍可执行;已格式化则跳过默认纯文本兜底。
|
|
1036
|
+
*
|
|
1037
|
+
* `statusCodes` 有运行时语义:指定后只有这些状态会进入本中间件。
|
|
1038
|
+
*
|
|
1039
|
+
* ```ts
|
|
1040
|
+
* formatError({
|
|
1041
|
+
* statusCodes: [400, 422],
|
|
1042
|
+
* content: { code: rule.string(), message: rule.string() },
|
|
1043
|
+
* handler(err) {
|
|
1044
|
+
* // 用 err.message(已净化);不要把 err.raw.message / stack 写入响应
|
|
1045
|
+
* return { code: err.code ?? 'HTTP_ERROR', message: err.message };
|
|
1046
|
+
* },
|
|
1047
|
+
* });
|
|
1048
|
+
* ```
|
|
1049
|
+
*/
|
|
1050
|
+
export declare const formatError: <Content extends ValidatorToken = ValidatorToken, R extends FormatErrorHandlerResult<Content> = FormatErrorHandlerResult<Content>>(options: FormatErrorOptions<Content, R>) => FormatErrorMiddleware<Content>;
|
|
1051
|
+
export declare namespace Builder {
|
|
1052
|
+
type DTO<Props extends object | unknown, T extends WebMiddlewareToken[] | []> = Omit<Props & Union2Intersection<Middleware.CollectArrayType<T[number]>>, ResponseMethods>;
|
|
1053
|
+
type Interface<Props extends object | unknown, T extends WebMiddlewareToken[] | []> = Props & Union2Intersection<Middleware.CollectArrayType<T[number]>>;
|
|
1054
|
+
type Context<Props extends object | unknown, T extends WebMiddlewareToken[] | []> = Interface<Props, T> & OverrideWebContext<Interface<Props, T>>;
|
|
1055
|
+
type ResponseMethods = 'send' | 'throw' | 'redirect';
|
|
1056
|
+
type OverrideWebContext<Props extends object | unknown> = 'send' extends keyof Props ? Omit<WebContext, ResponseMethods> : 'throw' extends keyof Props ? Omit<WebContext, ResponseMethods> : 'redirect' extends keyof Props ? Omit<WebContext, ResponseMethods> : WebContext;
|
|
1057
|
+
type Docs = Omit<OpenAPI.OperationObject, 'parameters' | 'requestBody' | 'responses'> & {
|
|
549
1058
|
/**
|
|
550
|
-
*
|
|
1059
|
+
* 生成openapi时是否展示当前路由。默认:`true`
|
|
551
1060
|
*/
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
export
|
|
1061
|
+
showInOpenapi?: boolean;
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
export interface BuilderOptions<Props extends object | unknown, T extends WebMiddlewareToken[] | []> {
|
|
1065
|
+
/**
|
|
1066
|
+
* 禁用当前路由。默认 `false`
|
|
1067
|
+
*/
|
|
1068
|
+
disabled?: boolean;
|
|
1069
|
+
mount?: T;
|
|
1070
|
+
docs?: Builder.Docs;
|
|
1071
|
+
action: (ctx: Builder.Context<Props, T>) => any;
|
|
1072
|
+
}
|
|
1073
|
+
export declare class Builder<Props extends object | unknown = object, T extends WebMiddlewareToken[] | [] = []> {
|
|
1074
|
+
protected readonly methods: readonly (typeof Builder.METHODS)[number][];
|
|
1075
|
+
static METHODS: readonly ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
1076
|
+
readonly uri: string;
|
|
1077
|
+
readonly docs: Builder.Docs;
|
|
1078
|
+
protected readonly middlewareList: WebMiddlewareToken[];
|
|
1079
|
+
protected readonly matchFn: MatchFunction<ParamData>;
|
|
1080
|
+
constructor(prefix: string, uri: string, methods: readonly (typeof Builder.METHODS)[number][], options: BuilderOptions<Props, T>);
|
|
1081
|
+
isPureUri(): boolean;
|
|
1082
|
+
match(pathname: string): Record<string, unknown> | false;
|
|
1083
|
+
}
|
|
1084
|
+
export interface RouterOptions<T extends WebMiddlewareToken[] | [] = any[]> {
|
|
1085
|
+
prefix?: string;
|
|
1086
|
+
mount?: T;
|
|
1087
|
+
docs?: Pick<OpenAPI.OperationObject, 'tags' | 'deprecated'>;
|
|
1088
|
+
}
|
|
1089
|
+
export declare class Router<T extends WebMiddlewareToken[] | [] = any[], Props extends object | unknown = WebApp.Props & Union2Intersection<Middleware.CollectArrayType<T[number]>>> {
|
|
1090
|
+
protected readonly opts: RouterOptions<T>;
|
|
1091
|
+
protected readonly middlewareList: WebMiddlewareToken[];
|
|
1092
|
+
protected readonly prefix: string;
|
|
1093
|
+
protected readonly builders: Builder[];
|
|
1094
|
+
protected readonly docs: RouterOptions['docs'];
|
|
1095
|
+
constructor(opts?: RouterOptions<T>);
|
|
1096
|
+
/**
|
|
1097
|
+
* 接收Get和Head请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1098
|
+
*/
|
|
1099
|
+
get<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1100
|
+
/**
|
|
1101
|
+
* 接收Post请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1102
|
+
*/
|
|
1103
|
+
post<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1104
|
+
/**
|
|
1105
|
+
* 接收Put请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1106
|
+
*/
|
|
1107
|
+
put<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1108
|
+
/**
|
|
1109
|
+
* 接收Patch请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1110
|
+
*/
|
|
1111
|
+
patch<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1112
|
+
/**
|
|
1113
|
+
* 接收Delete请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1114
|
+
*/
|
|
1115
|
+
delete<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1116
|
+
/**
|
|
1117
|
+
* 接收所有请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1118
|
+
*/
|
|
1119
|
+
all<T extends WebMiddlewareToken[] | []>(uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1120
|
+
/**
|
|
1121
|
+
* 接收指定的请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
|
|
1122
|
+
*/
|
|
1123
|
+
customize<T extends WebMiddlewareToken[] | []>(methods: (typeof Builder.METHODS)[number][], uri: string, options: BuilderOptions<Props, T>): Builder.DTO<Props, T>;
|
|
1124
|
+
protected create(uri: string, methods: readonly (typeof Builder.METHODS)[number][], options: BuilderOptions<Props, any[]>): any;
|
|
1125
|
+
protected collect(): Record<"DELETE" | "GET" | "PATCH" | "POST" | "PUT", {
|
|
1126
|
+
uri: string;
|
|
1127
|
+
isPureUri: boolean;
|
|
1128
|
+
match: Builder['match'];
|
|
1129
|
+
route: ComposeFn;
|
|
1130
|
+
}[]>;
|
|
1131
|
+
}
|
|
1132
|
+
export declare const routers: (options: GlobPathOptions | Router[]) => WebMiddleware;
|
|
1133
|
+
export { type ClientErrorStatus, type EmptyStatus, type HttpErrorProperties, type HttpErrorStatus, type HttpStatus, type OKStatus, type RedirectStatus, type ServerErrorStatus, type WebResponseMediaOptions, statuses };
|