@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.js CHANGED
@@ -1,1058 +1,1821 @@
1
- // src/http/app.ts
2
- import http from "http";
3
- import https from "https";
4
- import stream2 from "stream";
5
-
6
- // src/http/request.ts
7
- import { IncomingMessage } from "http";
1
+ import http, { IncomingMessage, ServerResponse } from "node:http";
2
+ import https from "node:https";
3
+ import stream, { Stream } from "node:stream";
4
+ import { isIP } from "node:net";
8
5
  import qs from "qs";
9
6
  import typeIs from "type-is";
10
- import requestIP from "request-ip";
11
7
  import fresh from "fresh";
12
8
  import accepts from "accepts";
13
- import cookie from "cookie";
14
- import { MIMEType } from "util";
9
+ import { parseCookie, stringifySetCookie } from "cookie";
10
+ import { MIMEType } from "node:util";
11
+ import assert from "node:assert";
12
+ import statuses, { default as statuses$1 } from "statuses";
13
+ import mimeTypes from "mime-types";
14
+ import { finished } from "node:stream/promises";
15
+ import destroy from "destroy";
16
+ import { create } from "content-disposition";
17
+ import { basename, extname } from "node:path";
18
+ import { createReadStream } from "node:fs";
19
+ import vary from "vary";
20
+ import { AllOfValidator, ArrayValidator, I18n, Middleware, ObjectValidator, Rule, ValidateDeniedError, ValidateResult, Validator, ValidatorSchema, compose, createI18n, ensureI18nLanguage, internalDestroyServices, middleware, resolveI18nLanguage, sleep, toDocument, toValidator, validate } from "@aomex/common";
21
+ import { bytes, toArray } from "@aomex/internal-tools";
22
+ import formidable, { PersistentFile } from "formidable";
23
+ import coBody from "co-body";
24
+ import { unlink } from "node:fs/promises";
25
+ import { fileTypeFromFile } from "file-type";
26
+ import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
27
+ import { match } from "path-to-regexp";
28
+ // src/http/request.ts
15
29
  var WebRequest = class extends IncomingMessage {
16
- app;
17
- req;
18
- res;
19
- ctx;
20
- params = {};
21
- _accept;
22
- _cookies;
23
- _body;
24
- _rawBody;
25
- _parsedUrl = null;
26
- _query;
27
- get accept() {
28
- return this._accept || (this._accept = accepts(this));
29
- }
30
- get contentType() {
31
- try {
32
- const contentType = this.headers["content-type"];
33
- if (!contentType) return "";
34
- const mime = new MIMEType(contentType);
35
- return mime.essence;
36
- } catch {
37
- return "";
38
- }
39
- }
40
- /**
41
- * 返回从`headers['cookie']`解析后的cookie列表
42
- */
43
- get cookies() {
44
- return this._cookies ||= cookie.parse(this.headers["cookie"] || "");
45
- }
46
- get body() {
47
- return this._body || {};
48
- }
49
- get fresh() {
50
- if (this.method !== "GET" && this.method !== "HEAD") return false;
51
- const status = this.res.statusCode;
52
- if (status < 200) return false;
53
- if (status >= 300 && status !== 304) return false;
54
- return fresh(this.headers, this.res.getHeaders());
55
- }
56
- get host() {
57
- let host = this.headers["x-forwarded-host"];
58
- if (!host) {
59
- if (this.httpVersionMajor >= 2) {
60
- host = this.headers[":authority"];
61
- }
62
- host ||= this.headers["host"];
63
- }
64
- return host && host.split(/\s*,\s*/, 1)[0] || "";
65
- }
66
- /**
67
- * 包括了协议,域名,端口和路径的完整链接
68
- */
69
- get href() {
70
- return this.origin + this.url;
71
- }
72
- get ip() {
73
- return requestIP.getClientIp(this) || "";
74
- }
75
- get origin() {
76
- return `${this.protocol}://${this.host}`;
77
- }
78
- get pathname() {
79
- return this.URL.pathname;
80
- }
81
- get protocol() {
82
- if (this.socket.encrypted) return "https";
83
- const proto = this.headers["x-forwarded-proto"];
84
- return proto && proto.split(/\s*,\s*/, 1)[0] || "http";
85
- }
86
- /**
87
- * 查询字符串对象
88
- */
89
- get query() {
90
- return this._query ||= qs.parse(this.querystring);
91
- }
92
- /**
93
- * 查询字符串
94
- */
95
- get querystring() {
96
- return this.URL.search.slice(1);
97
- }
98
- get rawBody() {
99
- return this._rawBody || "";
100
- }
101
- /**
102
- * 搜索字符串,比查询字符串多了一个开头问号(?)
103
- */
104
- get search() {
105
- return this.URL.search;
106
- }
107
- get secure() {
108
- return this.protocol === "https";
109
- }
110
- get URL() {
111
- return this._parsedUrl ||= new URL(this.href);
112
- }
113
- matchContentType(type, ...types) {
114
- const result = typeIs(this, type, ...types);
115
- return result === false ? null : result;
116
- }
30
+ app;
31
+ req;
32
+ res;
33
+ ctx;
34
+ params = {};
35
+ _accept;
36
+ _cookies;
37
+ _body;
38
+ _rawBody;
39
+ _parsedUrl = null;
40
+ _query;
41
+ _ip;
42
+ get accept() {
43
+ return this._accept || (this._accept = accepts(this));
44
+ }
45
+ get contentType() {
46
+ try {
47
+ const contentType = this.headers["content-type"];
48
+ if (!contentType) return "";
49
+ return new MIMEType(contentType).essence;
50
+ } catch {
51
+ return "";
52
+ }
53
+ }
54
+ /**
55
+ * 返回从`headers['cookie']`解析后的cookie列表
56
+ */
57
+ get cookies() {
58
+ return this._cookies ||= parseCookie(this.headers["cookie"] || "");
59
+ }
60
+ /**
61
+ * 解析后的请求体。若需要原始报文请用 `rawBody`
62
+ */
63
+ get body() {
64
+ return this._body === void 0 ? {} : this._body;
65
+ }
66
+ get fresh() {
67
+ if (this.method !== "GET" && this.method !== "HEAD") return false;
68
+ const status = this.res.statusCode;
69
+ if (status < 200) return false;
70
+ if (status >= 300 && status !== 304) return false;
71
+ return fresh(this.headers, this.res.getHeaders());
72
+ }
73
+ get host() {
74
+ let host = this.headers["x-forwarded-host"];
75
+ if (!host) {
76
+ if (this.httpVersionMajor >= 2) host = this.headers[":authority"];
77
+ host ||= this.headers["host"];
78
+ }
79
+ return host && host.split(/\s*,\s*/, 1)[0] || "";
80
+ }
81
+ /**
82
+ * 包括了协议,域名,端口和路径的完整链接
83
+ */
84
+ get href() {
85
+ return this.origin + this.url;
86
+ }
87
+ /**
88
+ * 客户端 IP。
89
+ * - `proxyIP.mode: 'detect'`:探测常见代理头(可被伪造)
90
+ * - `proxyIP.mode: 'specify'`:按 `hops` / `header` 严格解析
91
+ */
92
+ get ip() {
93
+ if (this._ip !== void 0) return this._ip;
94
+ const splitProxyIps = (value) => {
95
+ return value.split(",").map((part) => {
96
+ let ip = part.trim();
97
+ if (ip.includes(":")) {
98
+ const splitted = ip.split(":");
99
+ if (splitted.length === 2) ip = splitted[0];
100
+ }
101
+ return ip;
102
+ });
103
+ };
104
+ const proxyIP = this.app["options"].proxyIP;
105
+ if (proxyIP.mode === "specify") {
106
+ const { hops, header } = proxyIP;
107
+ if (hops > 0) {
108
+ const raw = this.headers[header.toLowerCase()];
109
+ const value = Array.isArray(raw) ? raw.join(",") : raw;
110
+ if (typeof value === "string") {
111
+ for (const ip of splitProxyIps(value).slice(-hops)) if (isIP(ip) !== 0) return this._ip = ip;
112
+ }
113
+ }
114
+ } else {
115
+ const { headers } = this;
116
+ const forwardedFor = headers["x-forwarded-for"];
117
+ if (typeof forwardedFor === "string") {
118
+ for (const ip of splitProxyIps(forwardedFor)) if (isIP(ip) !== 0) return this._ip = ip;
119
+ }
120
+ for (const key of [
121
+ "x-real-ip",
122
+ "forwarded",
123
+ "cf-connecting-ip",
124
+ "fastly-client-ip",
125
+ "true-client-ip",
126
+ "x-cluster-client-ip",
127
+ "x-appengine-user-ip"
128
+ ]) {
129
+ const value = headers[key];
130
+ if (typeof value === "string" && isIP(value) !== 0) return this._ip = value;
131
+ }
132
+ }
133
+ const { remoteAddress } = this.socket;
134
+ if (typeof remoteAddress === "string" && isIP(remoteAddress) !== 0) return this._ip = remoteAddress;
135
+ return this._ip = "";
136
+ }
137
+ get origin() {
138
+ return `${this.protocol}://${this.host}`;
139
+ }
140
+ get pathname() {
141
+ return this.URL.pathname;
142
+ }
143
+ get protocol() {
144
+ if (this.socket.encrypted) return "https";
145
+ const proto = this.headers["x-forwarded-proto"];
146
+ return proto && proto.split(/\s*,\s*/, 1)[0] || "http";
147
+ }
148
+ /**
149
+ * 查询字符串对象
150
+ */
151
+ get query() {
152
+ return this._query ||= qs.parse(this.querystring);
153
+ }
154
+ /**
155
+ * 查询字符串
156
+ */
157
+ get querystring() {
158
+ return this.URL.search.slice(1);
159
+ }
160
+ /**
161
+ * 原始请求体字符串。解析后的结构化数据请用 `body`
162
+ */
163
+ get rawBody() {
164
+ return this._rawBody || "";
165
+ }
166
+ /**
167
+ * 搜索字符串,比查询字符串多了一个开头问号(?)
168
+ */
169
+ get search() {
170
+ return this.URL.search;
171
+ }
172
+ get secure() {
173
+ return this.protocol === "https";
174
+ }
175
+ get URL() {
176
+ return this._parsedUrl ||= new URL(this.href);
177
+ }
178
+ matchContentType(type, ...types) {
179
+ const result = typeIs(this, type, ...types);
180
+ return result === false ? null : result;
181
+ }
117
182
  };
118
-
119
- // src/http/response.ts
120
- import { ServerResponse } from "http";
121
- import assert from "assert";
122
- import statuses from "statuses";
123
- import { Stream } from "stream";
124
-
125
183
  // src/utils/get-mime-type.ts
126
- import mimeTypes from "mime-types";
127
- var cache = {};
128
- var getMimeType = (filenameOrExt) => {
129
- let mimeType = cache[filenameOrExt];
130
- if (mimeType === void 0) {
131
- mimeType = mimeTypes.contentType(filenameOrExt) || "";
132
- cache[filenameOrExt] = mimeType;
133
- }
134
- return mimeType;
184
+ const cache = {};
185
+ const getMimeType = (filenameOrExt) => {
186
+ let mimeType = cache[filenameOrExt];
187
+ if (mimeType === void 0) {
188
+ mimeType = mimeTypes.contentType(filenameOrExt) || "";
189
+ cache[filenameOrExt] = mimeType;
190
+ }
191
+ return mimeType;
192
+ };
193
+ // src/utils/http-error.ts
194
+ /**
195
+ * HTTP 请求异常。`app.on('error')` 收到的均为本类实例。
196
+ *
197
+ * 业务侧用 `new HttpError` / `ctx.throw` 创建;第三方错误经 {@link HttpError.from} 转换。
198
+ */
199
+ var HttpError = class HttpError extends Error {
200
+ statusCode;
201
+ expose;
202
+ code;
203
+ headers;
204
+ constructor(statusCode, message, properties) {
205
+ const props = properties ? { ...properties } : void 0;
206
+ const cause = props?.cause;
207
+ if (props && "cause" in props) delete props.cause;
208
+ const resolved = props?.code === "ENOENT" ? 404 : statusCode;
209
+ super(message ?? statuses$1.message[resolved] ?? String(resolved), cause !== void 0 ? { cause } : void 0);
210
+ this.name = "HttpError";
211
+ this.statusCode = resolved;
212
+ this.expose = props?.expose ?? resolved < 500;
213
+ if (props?.code !== void 0) this.code = props.code;
214
+ if (props?.headers !== void 0) this.headers = props.headers;
215
+ Error.captureStackTrace?.(this, new.target);
216
+ }
217
+ /** 是否为自制 {@link HttpError}(覆盖 `Error.isError`,类型收窄为本类) */
218
+ static isError(value) {
219
+ return value instanceof HttpError;
220
+ }
221
+ /**
222
+ * 将任意错误转为自制 {@link HttpError}。
223
+ *
224
+ * - 已是本类实例:原样返回
225
+ * - 其余:只迁移有效字段(`statusCode`/`status`、`expose`、`headers`、`code`、`message`、`cause`、`stack`)
226
+ */
227
+ static from(error) {
228
+ if (HttpError.isError(error)) return error;
229
+ if (error == null) return new HttpError(500);
230
+ if (typeof error === "string") return new HttpError(500, error);
231
+ if (Error.isError(error)) return HttpError.fromForeign(error);
232
+ if (typeof error === "object") return HttpError.fromForeign(Object.assign(/* @__PURE__ */ new Error(), error));
233
+ return new HttpError(500);
234
+ }
235
+ /**
236
+ * 从第三方 Error(含类 http-errors 形态)提取字段并生成自制实例。
237
+ */
238
+ static fromForeign(error) {
239
+ const raw = error;
240
+ const code = typeof raw.code === "string" ? raw.code : void 0;
241
+ const statusCode = HttpError.normalizeStatus(code === "ENOENT" ? 404 : HttpError.pickStatus(raw));
242
+ const props = {};
243
+ if (typeof raw.expose === "boolean") props.expose = raw.expose;
244
+ if (code !== void 0) props.code = code;
245
+ const headers = HttpError.pickHeaders(raw.headers);
246
+ if (headers) props.headers = headers;
247
+ if (error.cause !== void 0) props.cause = error.cause;
248
+ const err = new HttpError(statusCode, error.message ? error.message : void 0, props);
249
+ if (error.name && error.name !== "Error") err.name = error.name;
250
+ if (error.stack) err.stack = error.stack;
251
+ return err;
252
+ }
253
+ static pickStatus(raw) {
254
+ if (typeof raw.statusCode === "number") return raw.statusCode;
255
+ if (typeof raw.status === "number") return raw.status;
256
+ return 500;
257
+ }
258
+ static pickHeaders(headers) {
259
+ if (headers === null || typeof headers !== "object" || Array.isArray(headers)) return;
260
+ const out = {};
261
+ for (const [key, value] of Object.entries(headers)) if (typeof value === "string" || typeof value === "number") out[key] = value;
262
+ return Object.keys(out).length ? out : void 0;
263
+ }
264
+ static normalizeStatus(status) {
265
+ if (status >= 400 && status < 600 && statuses$1.message[status]) return status;
266
+ return 500;
267
+ }
135
268
  };
136
-
137
- // src/http/response.ts
138
- import stream from "stream";
139
- import destroy from "destroy";
140
- import createHttpError, { isHttpError } from "http-errors";
141
- import contentDisposition from "content-disposition";
142
- import { extname } from "path";
143
- import { createReadStream } from "fs";
144
- import vary from "vary";
145
- import typeIs2 from "type-is";
146
- import cookie2 from "cookie";
147
- import { MIMEType as MIMEType2 } from "util";
148
-
149
- // src/i18n/index.ts
150
- import { I18n as I18n3 } from "@aomex/common";
151
-
152
269
  // src/i18n/locales/zh-cn.ts
153
- import { I18n } from "@aomex/common";
154
- var zh = I18n.define({
155
- validator: {
156
- file: {
157
- must_be_file: "{{label}}\u5FC5\u987B\u662F\u6587\u4EF6\u7C7B\u578B",
158
- too_large: "{{label}}\u6587\u4EF6\u4F53\u79EF\u592A\u5927",
159
- unsupported_mimetype: "{{label}}\u5305\u542B\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B"
160
- }
161
- },
162
- response: {
163
- redirect: "\u6B63\u5728\u91CD\u5B9A\u5411\u5230 {{url}}"
164
- }
270
+ const zh = I18n.define({
271
+ validator: { file: {
272
+ must_be_file: "{{label}}必须为文件",
273
+ too_large: "{{label}}文件过大",
274
+ unsupported_mimetype: "{{label}}的文件类型不受支持",
275
+ invalid_mimetype_token: "无效的媒体类型或文件扩展名:{{token}}"
276
+ } },
277
+ response: { redirect: "正在重定向到 {{url}}" }
165
278
  });
166
-
167
279
  // src/i18n/locales/en-us.ts
168
- import { I18n as I18n2 } from "@aomex/common";
169
- var en = I18n2.satisfies(zh).define({
170
- validator: {
171
- file: {
172
- must_be_file: "{{label}} must be file",
173
- too_large: "{{label}} file size too large",
174
- unsupported_mimetype: "{{label}} contains unsupported file mimetype"
175
- }
176
- },
177
- response: {
178
- redirect: "Redirecting to {{url}}"
179
- }
280
+ const en = I18n.satisfies(zh).define({
281
+ validator: { file: {
282
+ must_be_file: "{{label}} must be a file",
283
+ too_large: "{{label}} is too large",
284
+ unsupported_mimetype: "{{label}} has an unsupported file type",
285
+ invalid_mimetype_token: "Invalid media type or file extension: {{token}}"
286
+ } },
287
+ response: { redirect: "Redirecting to {{url}}" }
180
288
  });
181
-
182
- // src/i18n/locales/index.ts
183
- var locales = {
184
- zh_CN: zh,
185
- en_US: en
186
- };
187
-
188
289
  // src/i18n/index.ts
189
- var i18n = new I18n3({
190
- resources: locales,
191
- defaultLanguage: "zh_CN"
290
+ const i18n = createI18n({
291
+ zh,
292
+ en,
293
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
192
294
  });
193
-
295
+ // src/http/envelope.ts
296
+ /** 内置槽位:success / payload / statusCode */
297
+ var EnvelopeBuiltinSlot = class {
298
+ kind;
299
+ constructor(kind) {
300
+ this.kind = kind;
301
+ }
302
+ };
303
+ /** 自定义槽位:OpenAPI 用 schema,运行时用 get */
304
+ var EnvelopeCustomSlot = class {
305
+ schema;
306
+ get;
307
+ constructor(schema, get) {
308
+ this.schema = schema;
309
+ this.get = get;
310
+ }
311
+ };
312
+ const ENVELOPE_HTTP_STATUS = 200;
313
+ const isRedirectStatus = (code) => code >= 300 && code < 400;
314
+ /** 无响应体状态码:204 / 205 / 304(与 `statuses.empty` 对齐) */
315
+ const isEmptyStatus = (code) => !!statuses$1.empty[code];
316
+ const parseResponseStatusKey = (key) => {
317
+ if (key === "default") return "default";
318
+ if (/^[1-5]XX$/i.test(key)) return "range";
319
+ const n = Number(key);
320
+ return Number.isInteger(n) && n >= 100 && n <= 599 ? n : null;
321
+ };
322
+ const isSuccessStatusKey = (key) => {
323
+ const parsed = parseResponseStatusKey(key);
324
+ if (parsed === "default") return false;
325
+ if (parsed === "range") return /^2XX$/i.test(key);
326
+ if (parsed == null) return false;
327
+ if (isEmptyStatus(parsed)) return false;
328
+ return parsed >= 200 && parsed < 300;
329
+ };
330
+ const isErrorStatusKey = (key) => {
331
+ const parsed = parseResponseStatusKey(key);
332
+ if (parsed === "default") return true;
333
+ if (parsed === "range") return /^[45]XX$/i.test(key);
334
+ if (parsed == null) return false;
335
+ return parsed >= 400 && parsed < 600;
336
+ };
337
+ const isRedirectStatusKey = (key) => {
338
+ const parsed = parseResponseStatusKey(key);
339
+ if (parsed === "range") return /^3XX$/i.test(key);
340
+ if (typeof parsed !== "number") return false;
341
+ return isRedirectStatus(parsed);
342
+ };
343
+ const isEmptyStatusKey = (key) => {
344
+ const parsed = parseResponseStatusKey(key);
345
+ if (typeof parsed !== "number") return false;
346
+ return isEmptyStatus(parsed);
347
+ };
348
+ const pickMediaSchema = (response) => {
349
+ if (!response || "$ref" in response) return void 0;
350
+ const content = response.content;
351
+ if (!content) return void 0;
352
+ const json = content["application/json"];
353
+ if (json?.schema && !("$ref" in json.schema)) return json.schema;
354
+ for (const media of Object.values(content)) if (media?.schema && !("$ref" in media.schema)) return media.schema;
355
+ };
356
+ const mergeSchemas = (schemas) => {
357
+ if (schemas.length === 0) return void 0;
358
+ if (schemas.length === 1) return structuredClone(schemas[0]);
359
+ return { oneOf: schemas.map((s) => structuredClone(s)) };
360
+ };
361
+ /** 将声明树转为运行时 body */
362
+ const resolveRuntimeNode = (node, vars) => {
363
+ if (node instanceof EnvelopeBuiltinSlot) switch (node.kind) {
364
+ case "success": return vars.success;
365
+ case "payload": return vars.payload;
366
+ case "statusCode": return vars.statusCode;
367
+ default: node.kind;
368
+ }
369
+ if (node instanceof EnvelopeCustomSlot) return node.get(vars);
370
+ const out = {};
371
+ for (const [key, child] of Object.entries(node)) out[key] = resolveRuntimeNode(child, vars);
372
+ return out;
373
+ };
374
+ /**
375
+ * 将声明树转为 OpenAPI schema。
376
+ * - `success`:可带 `enum: [true|false]` 区分成败支
377
+ * - `payload`:替换为收集到的内层 schema
378
+ * - `statusCode`:integer
379
+ * - 自定义槽:用其 schema
380
+ */
381
+ const resolveOpenApiNode = (node, payloadSchema, successConst) => {
382
+ if (node instanceof EnvelopeBuiltinSlot) switch (node.kind) {
383
+ case "success": return successConst === void 0 ? { type: "boolean" } : {
384
+ type: "boolean",
385
+ enum: [successConst]
386
+ };
387
+ case "payload": return structuredClone(payloadSchema);
388
+ case "statusCode": return { type: "integer" };
389
+ default: node.kind;
390
+ }
391
+ if (node instanceof EnvelopeCustomSlot) {
392
+ const schema = toDocument(node.schema).schema;
393
+ if (!schema || "$ref" in schema) return {};
394
+ return structuredClone(schema);
395
+ }
396
+ const properties = {};
397
+ const required = [];
398
+ for (const [key, child] of Object.entries(node)) {
399
+ properties[key] = resolveOpenApiNode(child, payloadSchema, successConst);
400
+ required.push(key);
401
+ }
402
+ return {
403
+ type: "object",
404
+ properties,
405
+ required,
406
+ additionalProperties: false
407
+ };
408
+ };
409
+ const canWrapResponse = (res) => {
410
+ if (res.headersSent) return false;
411
+ if (isRedirectStatus(res.statusCode)) return false;
412
+ if (isEmptyStatus(res.statusCode)) return false;
413
+ if (res.contentType.includes("text/event-stream")) return false;
414
+ const bodyType = res["_bodyType"];
415
+ return bodyType === "json" || bodyType === "string" || bodyType === "null";
416
+ };
417
+ /**
418
+ * 运行时套壳:在 `flush` 写出前调用。
419
+ * 固定 HTTP `200`;跳过 stream、buffer、SSE、3xx、无内容状态码(204/205/304)。
420
+ */
421
+ const applyResponseEnvelope = (res, options) => {
422
+ if (!canWrapResponse(res)) return;
423
+ const statusCode = res.statusCode;
424
+ const payload = res["_bodyType"] === "null" ? null : res.body;
425
+ const vars = {
426
+ success: statusCode < 400,
427
+ payload,
428
+ statusCode
429
+ };
430
+ res.removeHeader("Content-Type");
431
+ res.body = resolveRuntimeNode(options.content, vars);
432
+ res.statusCode = ENVELOPE_HTTP_STATUS;
433
+ };
434
+ /**
435
+ * OpenAPI:在其它中间件的 `postMethod` 之后调用,将 2xx / 4xx·5xx·default 收成 `200`。
436
+ * 保留 3xx 与无内容状态码(204/205/304),与运行时跳过规则一致。
437
+ */
438
+ const createEnvelopeOpenApiInjector = (options) => ({ postMethod: (methodItem) => {
439
+ methodItem.responses ||= {};
440
+ const prev = methodItem.responses;
441
+ const successSchemas = [];
442
+ const errorSchemas = [];
443
+ const kept = {};
444
+ for (const [key, response] of Object.entries(prev)) {
445
+ if (isRedirectStatusKey(key) || isEmptyStatusKey(key)) {
446
+ kept[key] = response;
447
+ continue;
448
+ }
449
+ const schema = pickMediaSchema(response);
450
+ if (schema) {
451
+ if (isSuccessStatusKey(key)) successSchemas.push(schema);
452
+ else if (isErrorStatusKey(key)) errorSchemas.push(schema);
453
+ }
454
+ }
455
+ const branches = [];
456
+ const successPayload = mergeSchemas(successSchemas) ?? {};
457
+ const errorPayload = mergeSchemas(errorSchemas) ?? {};
458
+ if (successSchemas.length > 0 || Object.keys(prev).some(isSuccessStatusKey)) branches.push(resolveOpenApiNode(options.content, successPayload, true));
459
+ if (errorSchemas.length > 0 || Object.keys(prev).some(isErrorStatusKey)) branches.push(resolveOpenApiNode(options.content, errorPayload, false));
460
+ if (branches.length === 0) {
461
+ if (Object.keys(kept).length > 0) {
462
+ methodItem.responses = kept;
463
+ return;
464
+ }
465
+ branches.push(resolveOpenApiNode(options.content, {}, void 0));
466
+ }
467
+ const schema = branches.length === 1 ? branches[0] : { oneOf: branches };
468
+ kept[String(ENVELOPE_HTTP_STATUS)] = {
469
+ description: options.description ?? "",
470
+ content: { "application/json": { schema } }
471
+ };
472
+ methodItem.responses = kept;
473
+ } });
474
+ /**
475
+ * 响应体套壳槽位(配置给 `WebApp.envelope`)。
476
+ *
477
+ * - 内置:`envelope.success` / `envelope.payload` / `envelope.statusCode`
478
+ * - 自定义:`envelope.slot(schema, get)`,`get` 只读 `{ success, payload, statusCode }`
479
+ *
480
+ * ```ts
481
+ * new WebApp({
482
+ * envelope: {
483
+ * content: {
484
+ * success: envelope.success,
485
+ * statusCode: envelope.statusCode,
486
+ * data: envelope.payload,
487
+ * version: envelope.slot(rule.string(), () => '1.0'),
488
+ * },
489
+ * },
490
+ * mount: [formatError({ ... })],
491
+ * // ...
492
+ * });
493
+ * ```
494
+ */
495
+ const envelope = {
496
+ /** 原请求是否业务成功(`statusCode < 400`);OpenAPI 成败支分别固定为 `true` / `false` */
497
+ success: new EnvelopeBuiltinSlot("success"),
498
+ /** 套壳前的响应 body(仅 json / string / null);OpenAPI 替换为对应状态支的内层 schema */
499
+ payload: new EnvelopeBuiltinSlot("payload"),
500
+ /** 套壳前的 HTTP 状态码(写出后仍固定为 200) */
501
+ statusCode: new EnvelopeBuiltinSlot("statusCode"),
502
+ /**
503
+ * 自定义槽位:`schema` 供 OpenAPI;`get(vars)` 供运行时取值。
504
+ * `vars` 仅含 `{ success, payload, statusCode }`,勿依赖其它上下文。
505
+ */
506
+ slot: (schema, get) => new EnvelopeCustomSlot(schema, get)
507
+ };
508
+ // src/http/sse.ts
509
+ var ServerSentEvents = class {
510
+ ctx;
511
+ closed = false;
512
+ teardowns = [];
513
+ abortController = new AbortController();
514
+ heartbeatTimer;
515
+ constructor(ctx, options = {}) {
516
+ this.ctx = ctx;
517
+ const { response, request } = ctx;
518
+ if (response.headersSent) throw new Error("ServerSentEvents: response headers already sent");
519
+ response.statusCode = 200;
520
+ response.setHeader("Content-Type", "text/event-stream; charset=utf-8");
521
+ response.setHeader("Cache-Control", "no-cache, no-transform");
522
+ response.setHeader("Connection", "keep-alive");
523
+ response.setHeader("X-Accel-Buffering", "no");
524
+ response.removeHeader("Content-Length");
525
+ response.flushHeaders();
526
+ if (options.retry != null) {
527
+ this.writeField("retry", String(options.retry));
528
+ this.writeRaw("\n");
529
+ }
530
+ const heartbeat = options.heartbeat === false ? 0 : options.heartbeat ?? 15e3;
531
+ if (heartbeat > 0) {
532
+ this.heartbeatTimer = setInterval(() => {
533
+ this.writeRaw(": \n\n");
534
+ }, heartbeat);
535
+ this.heartbeatTimer.unref?.();
536
+ }
537
+ const onClose = () => this.close();
538
+ request.on("close", onClose);
539
+ response.on("close", onClose);
540
+ this.teardowns.push(() => {
541
+ request.off("close", onClose);
542
+ response.off("close", onClose);
543
+ });
544
+ }
545
+ /**
546
+ * 客户端带来的 `Last-Event-ID`(若有)。
547
+ * 发送事件时带上 `id` 后,浏览器断线重连会自动带上该请求头;首次连接或未发过 id 时为 `undefined`。
548
+ *
549
+ * ```typescript
550
+ * const sse = ctx.sse();
551
+ * const after = sse.lastEventId;
552
+ * await sse.stream(async (emit, signal) => {
553
+ * for await (const item of events.watch({ after, signal })) {
554
+ * emit({ id: String(item.id), data: item });
555
+ * }
556
+ * });
557
+ * ```
558
+ */
559
+ get lastEventId() {
560
+ const value = this.ctx.request.headers["last-event-id"];
561
+ if (Array.isArray(value)) return value[0] || void 0;
562
+ return value || void 0;
563
+ }
564
+ /**
565
+ * 与本连接绑定的 `AbortSignal`。连接 `close`(含客户端断开)时会 abort,
566
+ * 可传给异步源(如 `watch({ signal })`)以便自动取消;`stream` 的第二参数是同一个 signal。
567
+ */
568
+ get signal() {
569
+ return this.abortController.signal;
570
+ }
571
+ get writable() {
572
+ return !this.closed && this.ctx.response.writable;
573
+ }
574
+ /**
575
+ * 发送一条 SSE 事件
576
+ */
577
+ send(message) {
578
+ if (!this.writable) return;
579
+ const chunks = [];
580
+ if (message.id != null) chunks.push(`id: ${this.escapeBreak(String(message.id))}\n`);
581
+ if (message.event != null) chunks.push(`event: ${this.escapeBreak(String(message.event))}\n`);
582
+ if (message.retry != null) chunks.push(`retry: ${Number(message.retry)}\n`);
583
+ if (message.data !== void 0) {
584
+ const raw = typeof message.data === "string" ? message.data : JSON.stringify(message.data);
585
+ for (const line of raw.split(/\r?\n/)) chunks.push(`data: ${line}\n`);
586
+ }
587
+ chunks.push("\n");
588
+ this.writeRaw(chunks.join(""));
589
+ }
590
+ /**
591
+ * 连接关闭时回调(若已关闭则立即执行)
592
+ */
593
+ onClose(fn) {
594
+ if (this.closed) fn();
595
+ else this.teardowns.push(fn);
596
+ return this;
597
+ }
598
+ /**
599
+ * 跟随异步源推送;结束或中断时自动 `close()`。
600
+ * 第二参数 `signal` 即 `this.signal`,连接关闭时 abort。
601
+ */
602
+ async stream(fn) {
603
+ try {
604
+ await fn((message) => this.send(message), this.signal);
605
+ } finally {
606
+ this.close();
607
+ }
608
+ }
609
+ /**
610
+ * 结束 SSE 连接并执行 teardown。
611
+ *
612
+ * 客户端断开或 request/response `close` 时会自动调用,一般不必手动关;
613
+ * 服务端主动收尾(推送结束、`stream` 跑完)时再调用。
614
+ */
615
+ close() {
616
+ if (this.closed) return;
617
+ this.closed = true;
618
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
619
+ if (!this.abortController.signal.aborted) this.abortController.abort();
620
+ const tasks = this.teardowns.splice(0);
621
+ for (const task of tasks) try {
622
+ task();
623
+ } catch {}
624
+ const { response } = this.ctx;
625
+ if (response.writable) response.end();
626
+ }
627
+ writeField(name, value) {
628
+ this.writeRaw(`${name}: ${this.escapeBreak(value)}\n`);
629
+ }
630
+ writeRaw(chunk) {
631
+ if (this.closed) return;
632
+ const { response } = this.ctx;
633
+ if (!response.writable) {
634
+ this.close();
635
+ return;
636
+ }
637
+ response.write(chunk);
638
+ }
639
+ escapeBreak(value) {
640
+ return value.replace(/[\r\n]/g, "");
641
+ }
642
+ };
194
643
  // src/http/response.ts
195
644
  var WebResponse = class extends ServerResponse {
196
- app;
197
- res;
198
- ctx;
199
- _body = null;
200
- _bodyType = "null";
201
- _jsonString = "";
202
- /**
203
- * 是否明确设置过内容
204
- */
205
- _explicitBody = false;
206
- /**
207
- * 是否明确设置过状态码
208
- */
209
- _explicitStatus = false;
210
- _statusCode = 404;
211
- _updatingContentType = false;
212
- constructor(req) {
213
- super(req);
214
- Object.defineProperty(this, "statusCode", {
215
- get: () => {
216
- return this._statusCode;
217
- },
218
- set: (code) => {
219
- this.setStatus(code);
220
- }
221
- });
222
- this.onError = this.onError.bind(this);
223
- this.flush = this.flush.bind(this);
224
- }
225
- get contentLength() {
226
- const length = this.getHeader("Content-Length");
227
- return length ? Number(length) : 0;
228
- }
229
- set contentLength(length) {
230
- if (!this.hasHeader("Transfer-Encoding")) {
231
- this.setHeader("Content-Length", length);
232
- }
233
- }
234
- get contentType() {
235
- try {
236
- const contentType = this.getHeader("Content-Type");
237
- if (!contentType) return "";
238
- const mime = new MIMEType2(contentType);
239
- return mime.essence;
240
- } catch {
241
- return "";
242
- }
243
- }
244
- set contentType(typeOrFilenameOrExt) {
245
- const mimeType = getMimeType(typeOrFilenameOrExt);
246
- const msg = `\u4E0D\u5408\u6CD5\u7684\u7C7B\u578B\uFF1A'${typeOrFilenameOrExt}'`;
247
- if (!mimeType) throw new TypeError(msg);
248
- this.setHeader("Content-Type", mimeType);
249
- this.updateContentType();
250
- }
251
- get body() {
252
- return this._body;
253
- }
254
- set body(val) {
255
- val = this._body = val == null ? null : val;
256
- this._explicitBody = true;
257
- this._bodyType = this.getBodyType(val);
258
- if (this._bodyType === "json") {
259
- this._jsonString = JSON.stringify(val);
260
- }
261
- if (!this._explicitStatus) {
262
- this.statusCode = 200;
263
- }
264
- this.updateContentType();
265
- }
266
- /**
267
- * 下载文件
268
- *
269
- * @param filePath 路径
270
- * @param type 附件类型。默认值:`attachment`
271
- *
272
- * @link https://developer.mozilla.org/zh_CN/docs/Web/HTTP/Headers/Content-Disposition
273
- *
274
- */
275
- download(filePath, type = "attachment") {
276
- this.contentType = extname(filePath);
277
- this.setHeader("content-disposition", contentDisposition(filePath, { type }));
278
- this.body = createReadStream(filePath);
279
- }
280
- flush() {
281
- if (!this.writable || this.headersSent) return;
282
- if (this.body === null) {
283
- if (this.contentType === "application/json") {
284
- this.body = String(null);
285
- } else if (this._explicitBody) {
286
- this.body = "";
287
- } else {
288
- this.statusCode = this.statusCode;
289
- this.body = String(this.statusMessage || statuses.message[this.statusCode]);
290
- }
291
- }
292
- const { _bodyType } = this;
293
- if (statuses.empty[this.statusCode]) return void this.end();
294
- if (this.req.method === "HEAD") return void this.end();
295
- if (_bodyType === "json") return void this.end(this._jsonString);
296
- if (_bodyType === "string") return void this.end(this.body);
297
- if (_bodyType === "buffer") return void this.end(this.body);
298
- if (_bodyType === "stream") {
299
- const output = this.body;
300
- if (!output.listenerCount("error")) {
301
- output.once("error", this.onError);
302
- }
303
- stream.finished(this, () => {
304
- destroy(output);
305
- });
306
- return void output.pipe(this);
307
- }
308
- }
309
- isJSON(value) {
310
- return value === this.body ? this._bodyType === "json" : this.getBodyType(value) === "json";
311
- }
312
- matchContentType(type, ...types) {
313
- const result = typeIs2.is(this.contentType, type, ...types);
314
- return result === false ? null : result;
315
- }
316
- onError(error) {
317
- if (error == null) return;
318
- const err = isHttpError(error) ? error : createHttpError(error);
319
- this.removeHeaders(...this.getHeaderNames());
320
- err.headers && this.setHeaders(err.headers);
321
- const code = err.status || err.statusCode;
322
- if (err["code"] === "ENOENT") {
323
- this.statusCode = 404;
324
- } else if (typeof code !== "number" || !statuses.message[code]) {
325
- this.statusCode = 500;
326
- } else {
327
- this.statusCode = code;
328
- }
329
- this.body = this.app.debug || err.expose ? err.message : statuses.message[this.statusCode];
330
- this.app.emit("error", err, this.ctx);
331
- this.flush();
332
- }
333
- redirect(status, url) {
334
- url = typeof url === "string" ? url : status.toString();
335
- this.statusCode = typeof status === "string" ? 302 : status;
336
- const href = new URL(url).href;
337
- this.setHeader("location", href);
338
- if (this.req.accept.types("text/html")) {
339
- this.contentType = "text/html";
340
- this.body = i18n.t("response.redirect", {
341
- url: `<a href="${href}">${url.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;")}</a>`
342
- });
343
- } else {
344
- this.contentType = "text/plain";
345
- this.body = i18n.t("response.redirect", { url });
346
- }
347
- }
348
- removeCookie(name, options) {
349
- return this.setCookie(name, "", {
350
- ...options,
351
- maxAge: void 0,
352
- expires: /* @__PURE__ */ new Date(0)
353
- });
354
- }
355
- removeHeaders(...headers) {
356
- headers.forEach(this.removeHeader.bind(this));
357
- }
358
- setCookie(name, value, options) {
359
- const cookies = this.getHeader("Set-Cookie") || [];
360
- cookies.push(
361
- cookie2.serialize(name, value, {
362
- path: "/",
363
- sameSite: true,
364
- httpOnly: true,
365
- secure: this.req.secure,
366
- ...options
367
- })
368
- );
369
- this.setHeader("Set-Cookie", cookies);
370
- }
371
- setHeaders(headers) {
372
- if (headers instanceof Headers || headers instanceof Map) {
373
- return super.setHeaders(headers);
374
- }
375
- return super.setHeaders(new Map(Object.entries(headers)));
376
- }
377
- vary(field) {
378
- vary(this, field);
379
- return this.getHeader("Vary");
380
- }
381
- setStatus(code) {
382
- assert(code >= 100 && code <= 999);
383
- this._statusCode = code;
384
- this._explicitStatus = true;
385
- this.statusMessage = String(statuses.message[code] || code);
386
- if (statuses.empty[code]) {
387
- this.body = null;
388
- } else {
389
- this.updateContentType();
390
- }
391
- }
392
- updateContentType() {
393
- if (this._updatingContentType) return;
394
- this._updatingContentType = true;
395
- const { _bodyType } = this;
396
- const missType = !this.hasHeader("Content-Type");
397
- if (_bodyType === "json") {
398
- this.contentLength = Buffer.byteLength(this._jsonString);
399
- if (missType) {
400
- this.contentType = "application/json";
401
- }
402
- } else if (_bodyType === "string") {
403
- const body2 = this.body;
404
- this.contentLength = Buffer.byteLength(body2);
405
- if (missType) {
406
- this.contentType = /^\s*</.test(body2) ? "text/html" : "text/plain";
407
- }
408
- } else if (_bodyType === "null") {
409
- if (statuses.empty[this.statusCode]) {
410
- this.removeHeaders("Content-Type", "Content-Length", "Transfer-Encoding");
411
- } else if (this.contentType === "application/json") {
412
- this.contentLength = Buffer.byteLength(String(null));
413
- } else {
414
- }
415
- } else if (_bodyType === "buffer") {
416
- const body2 = this.body;
417
- this.contentLength = body2.length;
418
- if (missType) {
419
- this.contentType = "application/octet-stream";
420
- }
421
- } else if (_bodyType === "stream") {
422
- if (missType) {
423
- this.contentType = "application/octet-stream";
424
- }
425
- }
426
- this._updatingContentType = false;
427
- }
428
- getBodyType(body2) {
429
- if (body2 == null) return "null";
430
- if (typeof body2 === "string") return "string";
431
- if (Buffer.isBuffer(body2)) return "buffer";
432
- if (body2 instanceof Stream) return "stream";
433
- return "json";
434
- }
645
+ app;
646
+ res;
647
+ ctx;
648
+ _body = null;
649
+ _bodyType = "null";
650
+ _jsonString = "";
651
+ /**
652
+ * 是否明确设置过内容
653
+ */
654
+ _explicitBody = false;
655
+ /**
656
+ * 是否明确设置过状态码
657
+ */
658
+ _explicitStatus = false;
659
+ /**
660
+ * `formatError` 已写过错误响应;`onError` 跳过默认纯文本兜底
661
+ */
662
+ _errorHandled = false;
663
+ _statusCode = 404;
664
+ _updatingContentType = false;
665
+ constructor(req) {
666
+ super(req);
667
+ Object.defineProperty(this, "statusCode", {
668
+ get: () => {
669
+ return this._statusCode;
670
+ },
671
+ set: (code) => {
672
+ this.setStatus(code);
673
+ }
674
+ });
675
+ this.onError = this.onError.bind(this);
676
+ this.flush = this.flush.bind(this);
677
+ }
678
+ get contentLength() {
679
+ const length = this.getHeader("Content-Length");
680
+ return length ? Number(length) : 0;
681
+ }
682
+ set contentLength(length) {
683
+ if (!this.hasHeader("Transfer-Encoding")) this.setHeader("Content-Length", length);
684
+ }
685
+ get contentType() {
686
+ try {
687
+ const contentType = this.getHeader("Content-Type");
688
+ if (!contentType) return "";
689
+ return new MIMEType(contentType).essence;
690
+ } catch {
691
+ return "";
692
+ }
693
+ }
694
+ set contentType(typeOrFilenameOrExt) {
695
+ const mimeType = getMimeType(typeOrFilenameOrExt);
696
+ const msg = `不合法的类型:'${typeOrFilenameOrExt}'`;
697
+ if (!mimeType) throw new TypeError(msg);
698
+ this.setHeader("Content-Type", mimeType);
699
+ this.updateContentType();
700
+ }
701
+ get body() {
702
+ return this._body;
703
+ }
704
+ set body(val) {
705
+ val = this._body = val == null ? null : val;
706
+ this._explicitBody = true;
707
+ this._bodyType = this.getBodyType(val);
708
+ if (this._bodyType === "json") this._jsonString = JSON.stringify(val);
709
+ if (!this._explicitStatus) this.statusCode = 200;
710
+ this.updateContentType();
711
+ }
712
+ /**
713
+ * 下载文件。
714
+ * 返回的 Promise 在响应结束(发送完成或关闭)后 settled,便于清理临时文件。
715
+ *
716
+ * @param filePath 路径
717
+ * @param type 附件类型。默认值:`attachment`
718
+ *
719
+ * @link https://developer.mozilla.org/zh_CN/docs/Web/HTTP/Headers/Content-Disposition
720
+ *
721
+ */
722
+ download(filePath, type = "attachment") {
723
+ this.contentType = extname(filePath);
724
+ this.setHeader("content-disposition", create(basename(filePath), { type }));
725
+ this.body = createReadStream(filePath);
726
+ return finished(this);
727
+ }
728
+ /**
729
+ * 打开 SSE(Server-Sent Events)连接。
730
+ *
731
+ * ```typescript
732
+ * const sse = ctx.response.sse();
733
+ * // 或 ctx.sse()
734
+ * sse.send({ event: 'ready', data: { ok: true } });
735
+ * ```
736
+ */
737
+ sse(options) {
738
+ return new ServerSentEvents(this.ctx, options);
739
+ }
740
+ flush() {
741
+ if (!this.writable || this.headersSent) return;
742
+ const envelope = this.app["options"].envelope;
743
+ if (envelope) applyResponseEnvelope(this, envelope);
744
+ if (this.body === null) {
745
+ if (this.contentType === "application/json") this.body = String(null);
746
+ else if (this._explicitBody) this.body = "";
747
+ else {
748
+ this.statusCode = this.statusCode;
749
+ this.body = String(this.statusMessage || statuses$1.message[this.statusCode]);
750
+ }
751
+ }
752
+ const { _bodyType } = this;
753
+ if (statuses$1.empty[this.statusCode]) return void this.end();
754
+ if (this.req.method === "HEAD") return void this.end();
755
+ if (_bodyType === "json") return void this.end(this._jsonString);
756
+ if (_bodyType === "string") return void this.end(this.body);
757
+ if (_bodyType === "buffer") return void this.end(this.body);
758
+ if (_bodyType === "stream") {
759
+ const output = this.body;
760
+ if (!output.listenerCount("error")) output.once("error", this.onError);
761
+ stream.finished(this, () => {
762
+ destroy(output);
763
+ });
764
+ output.pipe(this);
765
+ return;
766
+ }
767
+ }
768
+ isJSON(value) {
769
+ return value === this.body ? this._bodyType === "json" : this.getBodyType(value) === "json";
770
+ }
771
+ matchContentType(type, ...types) {
772
+ const result = typeIs.is(this.contentType, type, ...types);
773
+ return result === false ? null : result;
774
+ }
775
+ onError(error) {
776
+ if (error == null) return;
777
+ const err = HttpError.from(error);
778
+ const ctx = this.ctx;
779
+ if (this._errorHandled) err.headers && this.setHeaders(err.headers);
780
+ else {
781
+ this.removeHeaders(...this.getHeaderNames());
782
+ err.headers && this.setHeaders(err.headers);
783
+ this.statusCode = err.statusCode;
784
+ this.ctx.send(err.expose ? err.message : statuses$1.message[this.statusCode] ?? "Error");
785
+ }
786
+ this.app.emit("error", err, ctx);
787
+ this.flush();
788
+ }
789
+ redirect(status, url) {
790
+ url = typeof url === "string" ? url : status.toString();
791
+ this.statusCode = typeof status === "string" ? 302 : status;
792
+ const href = new URL(url).href;
793
+ this.setHeader("location", href);
794
+ if (this.req.accept.types("text/html")) {
795
+ this.contentType = "text/html";
796
+ this.body = i18n.t("response.redirect", { url: `<a href="${href}">${url.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;")}</a>` });
797
+ } else {
798
+ this.contentType = "text/plain";
799
+ this.body = i18n.t("response.redirect", { url });
800
+ }
801
+ }
802
+ removeCookie(name, options) {
803
+ return this.setCookie(name, "", {
804
+ ...options,
805
+ maxAge: void 0,
806
+ expires: /* @__PURE__ */ new Date(0)
807
+ });
808
+ }
809
+ removeHeaders(...headers) {
810
+ headers.forEach(this.removeHeader.bind(this));
811
+ }
812
+ setCookie(name, value, options) {
813
+ const { encode, ...attrs } = options ?? {};
814
+ const cookies = this.getHeader("Set-Cookie") || [];
815
+ cookies.push(stringifySetCookie({
816
+ name,
817
+ value,
818
+ path: "/",
819
+ sameSite: true,
820
+ httpOnly: true,
821
+ secure: this.req.secure,
822
+ ...attrs
823
+ }, encode ? { encode } : void 0));
824
+ this.setHeader("Set-Cookie", cookies);
825
+ }
826
+ setHeaders(headers) {
827
+ if (headers instanceof Headers || headers instanceof Map) return super.setHeaders(headers);
828
+ return super.setHeaders(new Map(Object.entries(headers)));
829
+ }
830
+ vary(field) {
831
+ vary(this, field);
832
+ return this.getHeader("Vary");
833
+ }
834
+ setStatus(code) {
835
+ assert(code >= 100 && code <= 999);
836
+ this._statusCode = code;
837
+ this._explicitStatus = true;
838
+ this.statusMessage = String(statuses$1.message[code] || code);
839
+ if (statuses$1.empty[code]) this.body = null;
840
+ else this.updateContentType();
841
+ }
842
+ updateContentType() {
843
+ if (this._updatingContentType) return;
844
+ this._updatingContentType = true;
845
+ const { _bodyType } = this;
846
+ const missType = !this.hasHeader("Content-Type");
847
+ if (_bodyType === "json") {
848
+ this.contentLength = Buffer.byteLength(this._jsonString);
849
+ if (missType) this.contentType = "application/json";
850
+ } else if (_bodyType === "string") {
851
+ const body = this.body;
852
+ this.contentLength = Buffer.byteLength(body);
853
+ if (missType) this.contentType = /^\s*</.test(body) ? "text/html" : "text/plain";
854
+ } else if (_bodyType === "null") {
855
+ if (statuses$1.empty[this.statusCode]) this.removeHeaders("Content-Type", "Content-Length", "Transfer-Encoding");
856
+ else if (this.contentType === "application/json") this.contentLength = Buffer.byteLength(String(null));
857
+ } else if (_bodyType === "buffer") {
858
+ const body = this.body;
859
+ this.contentLength = body.length;
860
+ if (missType) this.contentType = "application/octet-stream";
861
+ } else if (_bodyType === "stream") {
862
+ if (missType) this.contentType = "application/octet-stream";
863
+ }
864
+ this._updatingContentType = false;
865
+ }
866
+ getBodyType(body) {
867
+ if (body == null) return "null";
868
+ if (typeof body === "string") return "string";
869
+ if (Buffer.isBuffer(body)) return "buffer";
870
+ if (body instanceof Stream) return "stream";
871
+ return "json";
872
+ }
435
873
  };
436
-
437
- // src/http/app.ts
438
- import { I18n as I18n4, compose, middleware as middleware2 } from "@aomex/common";
439
-
440
874
  // src/http/context.ts
441
- import createHttpError2 from "http-errors";
442
875
  var WebContext = class {
443
- constructor(app, request, response2) {
444
- this.app = app;
445
- this.request = request;
446
- this.response = response2;
447
- request.app = response2.app = app;
448
- request.res = response2.res = response2;
449
- request.req = response2.req = request;
450
- request.ctx = response2.ctx = this;
451
- this.redirect = response2.redirect.bind(response2);
452
- this.download = response2.download.bind(response2);
453
- }
454
- redirect;
455
- download;
456
- send(statusOrBody, body2) {
457
- if (typeof statusOrBody === "number") {
458
- this.response.statusCode = statusOrBody;
459
- } else {
460
- body2 = statusOrBody;
461
- }
462
- if (body2 !== void 0) {
463
- this.response.body = body2;
464
- }
465
- }
466
- throw(arg, ...args) {
467
- throw createHttpError2(arg, ...args);
468
- }
876
+ app;
877
+ request;
878
+ response;
879
+ redirect;
880
+ download;
881
+ sse;
882
+ constructor(app, request, response) {
883
+ this.app = app;
884
+ this.request = request;
885
+ this.response = response;
886
+ request.app = response.app = app;
887
+ request.res = response.res = response;
888
+ request.req = response.req = request;
889
+ request.ctx = response.ctx = this;
890
+ this.redirect = response.redirect.bind(response);
891
+ this.download = response.download.bind(response);
892
+ this.sse = response.sse.bind(response);
893
+ }
894
+ /** 与构造时传入的 `logger` 相同,取自 app */
895
+ get logger() {
896
+ return this.app["logger"];
897
+ }
898
+ send(statusOrBody, body) {
899
+ if (typeof statusOrBody === "number") this.response.statusCode = statusOrBody;
900
+ else body = statusOrBody;
901
+ if (body !== void 0) this.response.body = body;
902
+ }
903
+ throw(statusCode, messageOrProperties, properties) {
904
+ if (messageOrProperties instanceof Error) {
905
+ const foreign = Object.assign(new Error(messageOrProperties.message), {
906
+ statusCode,
907
+ status: statusCode,
908
+ name: messageOrProperties.name,
909
+ stack: messageOrProperties.stack,
910
+ cause: properties?.cause ?? messageOrProperties,
911
+ ...properties
912
+ });
913
+ throw HttpError.from(foreign);
914
+ }
915
+ if (messageOrProperties !== void 0 && typeof messageOrProperties === "object") throw new HttpError(statusCode, void 0, messageOrProperties);
916
+ throw new HttpError(statusCode, messageOrProperties, properties);
917
+ }
469
918
  };
470
-
471
- // src/http/app.ts
472
- import { EOL } from "os";
473
- import { styleText } from "util";
474
-
475
919
  // src/middleware/parse-body.ts
476
- import { middleware } from "@aomex/common";
477
- import formidable from "formidable";
478
- import coBody from "co-body";
479
- var jsonTypes = ["json", "application/*+json", "application/csp-report"];
480
- var formTypes = ["urlencoded"];
481
- var textTypes = ["text"];
482
- var parseBody = () => {
483
- return middleware.web(async (ctx, next) => {
484
- const { request } = ctx;
485
- if (!request.contentType) return next();
486
- const methodName = request.matchContentType(...jsonTypes) ? "json" : request.matchContentType(...formTypes) ? "form" : request.matchContentType(...textTypes) ? "text" : false;
487
- if (methodName) {
488
- const { parsed, raw } = await coBody[methodName](request, {
489
- // 默认值:1mb for json and 56kb for form-urlencoded
490
- limit: "32mb",
491
- returnRawBody: true,
492
- // @ts-expect-error
493
- onProtoPoisoning: "remove"
494
- });
495
- request["_body"] = parsed;
496
- request["_rawBody"] = raw;
497
- } else if (request.matchContentType("multipart/*")) {
498
- const form = formidable({
499
- hashAlgorithm: "md5",
500
- keepExtensions: true,
501
- maxFileSize: 1e3 * 1024 * 1024,
502
- allowEmptyFiles: true
503
- });
504
- const [fields, files] = await form.parse(request);
505
- const fixedFields = Object.fromEntries(
506
- Object.entries(fields).map(([key, values]) => {
507
- return [key, values == void 0 || values.length > 1 ? values : values[0]];
508
- })
509
- );
510
- request["_body"] = { ...fixedFields, ...files };
511
- }
512
- return next();
513
- });
920
+ const jsonTypes = [
921
+ "json",
922
+ "application/*+json",
923
+ "application/csp-report"
924
+ ];
925
+ const formTypes = ["urlencoded"];
926
+ const textTypes = ["text"];
927
+ /**
928
+ * 包内 Symbol:由 `parseBody` 注入到 ctx,仅供 `body()` 调用。
929
+ */
930
+ const internalEnsureBodyKey = Symbol("internalEnsureBody");
931
+ const ensureBody = async (ctx, options) => {
932
+ const { request, response } = ctx;
933
+ if (request["_body"] !== void 0) return;
934
+ if (!request.contentType) {
935
+ request["_body"] = {};
936
+ return;
937
+ }
938
+ if (!request.matchContentType("multipart/form-data")) {
939
+ request["_body"] = {};
940
+ return;
941
+ }
942
+ const allowFileFields = new Set(options.allowFileFields);
943
+ const maxFileSize = Math.max(0, options.maxFileSize ?? 52428800);
944
+ const maxFiles = Math.max(0, options.maxFiles);
945
+ const maxFields = Math.max(0, options.maxFields ?? 100);
946
+ const filepaths = [];
947
+ const form = formidable({
948
+ hashAlgorithm: "md5",
949
+ keepExtensions: true,
950
+ maxFileSize,
951
+ maxFiles,
952
+ maxFields,
953
+ allowEmptyFiles: false,
954
+ filter: ({ name }) => !!name && allowFileFields.has(name)
955
+ });
956
+ form.on("fileBegin", (_name, file) => {
957
+ filepaths.push(file.filepath);
958
+ });
959
+ const cleanupFiles = () => {
960
+ for (const filepath of filepaths) (async () => {
961
+ for (let i = 0; i < 5; i++) try {
962
+ await unlink(filepath);
963
+ return;
964
+ } catch (e) {
965
+ const code = e && typeof e === "object" && "code" in e ? e.code : void 0;
966
+ if (code === "ENOENT") return;
967
+ if (code !== "EBUSY" && code !== "EPERM") return;
968
+ await sleep(20 * (i + 1));
969
+ }
970
+ })();
971
+ };
972
+ const onRequestCloseDuringParse = () => {
973
+ if (!request.complete) cleanupFiles();
974
+ };
975
+ request.once("close", onRequestCloseDuringParse);
976
+ try {
977
+ const [fields, files] = await form.parse(request);
978
+ request.off("close", onRequestCloseDuringParse);
979
+ request["_body"] = {
980
+ ...Object.fromEntries(Object.entries(fields).map(([key, values]) => {
981
+ return [key, values == void 0 || values.length > 1 ? values : values[0]];
982
+ })),
983
+ ...files
984
+ };
985
+ if (filepaths.length) {
986
+ let cleaned = false;
987
+ const cleanup = () => {
988
+ if (cleaned) return;
989
+ cleaned = true;
990
+ cleanupFiles();
991
+ };
992
+ response.once("finish", cleanup);
993
+ response.once("close", cleanup);
994
+ }
995
+ } catch (e) {
996
+ cleanupFiles();
997
+ request.once("close", cleanupFiles);
998
+ throw e;
999
+ }
1000
+ };
1001
+ /**
1002
+ * 将路由上传选项与应用 `formData` 上限合并(取更严)。
1003
+ */
1004
+ const mergeUploadCeilings = (opts, formData) => {
1005
+ if (!formData) return opts;
1006
+ const ceilingFileSize = formData.maxFileSize !== void 0 ? Math.max(0, typeof formData.maxFileSize === "number" ? formData.maxFileSize : bytes(formData.maxFileSize)) : void 0;
1007
+ const ceilingFiles = formData.maxFiles !== void 0 ? Math.max(0, formData.maxFiles) : void 0;
1008
+ const ceilingFields = formData.maxFields !== void 0 ? Math.max(0, formData.maxFields) : void 0;
1009
+ return {
1010
+ ...opts,
1011
+ maxFiles: ceilingFiles !== void 0 && opts.maxFiles > 0 ? Math.min(opts.maxFiles, ceilingFiles) : opts.maxFiles,
1012
+ ...ceilingFileSize !== void 0 ? { maxFileSize: Math.min(opts.maxFileSize ?? 52428800, ceilingFileSize) } : null,
1013
+ ...ceilingFields !== void 0 ? { maxFields: Math.min(opts.maxFields ?? 100, ceilingFields) } : null
1014
+ };
1015
+ };
1016
+ /**
1017
+ * 全局请求体中间件:
1018
+ * - 解析 `payload` 适用的 Content-Type
1019
+ * - 向 ctx 注入 `internalEnsureBody`,供 `body()` 按需解析 `multipart/form-data`
1020
+ * - 若无人解析 multipart,则在 `next` 之后丢弃请求流
1021
+ */
1022
+ const parseBody = (options = {}) => {
1023
+ const maxPayloadSize = options.payload?.maxSize ?? "2mb";
1024
+ return middleware.web({ fn: async (ctx, next) => {
1025
+ ctx[internalEnsureBodyKey] = (opts) => ensureBody(ctx, mergeUploadCeilings(opts, options.formData));
1026
+ const { request } = ctx;
1027
+ if (!request.contentType) return next();
1028
+ const methodName = request.matchContentType(...jsonTypes) ? "json" : request.matchContentType(...formTypes) ? "form" : request.matchContentType(...textTypes) ? "text" : false;
1029
+ if (methodName) {
1030
+ const { parsed, raw } = await coBody[methodName](request, {
1031
+ limit: maxPayloadSize,
1032
+ returnRawBody: true,
1033
+ ...methodName === "json" ? { strict: false } : null,
1034
+ onProtoPoisoning: "remove"
1035
+ });
1036
+ request["_body"] = methodName === "json" && typeof raw === "string" && raw.trim() === "" ? {} : parsed;
1037
+ request["_rawBody"] = raw;
1038
+ return next();
1039
+ }
1040
+ if (!request.matchContentType("multipart/form-data")) return next();
1041
+ await next();
1042
+ if (request["_body"] === void 0 && !request.readableEnded && !request.destroyed) {
1043
+ request.resume();
1044
+ try {
1045
+ await finished(request);
1046
+ } catch {}
1047
+ }
1048
+ } });
514
1049
  };
515
-
516
1050
  // src/http/app.ts
517
- var WebApp = class extends stream2.EventEmitter {
518
- constructor(options = {}) {
519
- super();
520
- this.options = options;
521
- this.middlewareList = [];
522
- this.middlewareList = options.mount || [];
523
- }
524
- point;
525
- middlewareList;
526
- get debug() {
527
- return this.options.debug ?? process.env["NODE_ENV"] !== "production";
528
- }
529
- callback() {
530
- const fn = compose([
531
- middleware2.mixin((_, next) => {
532
- return this.options.language ? I18n4.provider(this.options.language, next) : next();
533
- }),
534
- parseBody(),
535
- ...this.middlewareList
536
- ]);
537
- if (!this.listenerCount("error")) {
538
- this.on("error", this.log.bind(this));
539
- }
540
- return (req, res) => {
541
- return fn(new WebContext(this, req, res)).then(res.flush).catch(res.onError);
542
- };
543
- }
544
- /**
545
- * 监听http服务
546
- * ```typescript
547
- * app.listen(3000);
548
- * ```
549
- */
550
- listen = (...args) => {
551
- return this.http({}).listen(...args);
552
- };
553
- /**
554
- * 监听http服务,可定制参数
555
- * ```typescript
556
- * app.http({...}).listen(3000);
557
- * ```
558
- */
559
- http(options) {
560
- const server = http.createServer(
561
- {
562
- ...options,
563
- IncomingMessage: WebRequest,
564
- ServerResponse: WebResponse
565
- },
566
- this.callback()
567
- );
568
- return { listen: server.listen.bind(server) };
569
- }
570
- /**
571
- * 监听https服务,需提供证书
572
- * ```typescript
573
- * app.https({...}).listen(3000);
574
- * ```
575
- */
576
- https(options) {
577
- const server = https.createServer(
578
- {
579
- ...options,
580
- IncomingMessage: WebRequest,
581
- ServerResponse: WebResponse
582
- },
583
- this.callback()
584
- );
585
- return { listen: server.listen.bind(server) };
586
- }
587
- log(err, ctx) {
588
- if (ctx.response.statusCode === 404 || err.expose) return;
589
- const msgs = (err.stack || err.toString()).split(EOL);
590
- console.error(["", styleText("bgRed", msgs.shift()), msgs.join(EOL), ""].join(EOL));
591
- }
1051
+ var WebApp = class extends stream.EventEmitter {
1052
+ options;
1053
+ middlewareList;
1054
+ logger;
1055
+ constructor(options) {
1056
+ super();
1057
+ this.options = options;
1058
+ this.middlewareList = [];
1059
+ this.middlewareList = options.mount || [];
1060
+ this.logger = options.logger;
1061
+ }
1062
+ /**
1063
+ * `fixed` 直接返回配置语言;`dynamic` 从请求头协商。
1064
+ */
1065
+ resolveLanguage(ctx) {
1066
+ const option = this.options.language;
1067
+ if (option.mode === "fixed") return option.language;
1068
+ const headerName = (option.header ?? "accept-language").toLowerCase();
1069
+ const accepted = headerName === "accept-language" ? ctx.request.accept.languages() : this.readLanguageHeader(ctx, headerName);
1070
+ const tags = Array.isArray(accepted) ? accepted : [];
1071
+ for (const tag of tags) {
1072
+ if (!tag || tag === "*") continue;
1073
+ const resolved = resolveI18nLanguage(tag);
1074
+ if (resolved) return resolved;
1075
+ }
1076
+ return option.fallback;
1077
+ }
1078
+ readLanguageHeader(ctx, name) {
1079
+ const raw = ctx.request.headers[name];
1080
+ if (!raw) return [];
1081
+ return (Array.isArray(raw) ? raw.join(",") : raw).split(",").map((part) => part.split(";")[0]?.trim() ?? "").filter((tag) => tag.length > 0);
1082
+ }
1083
+ bindServerLifecycle(server) {
1084
+ const services = toArray(this.options.services);
1085
+ const timeout = Math.max(0, this.options.shutdown?.timeout ?? 5e3);
1086
+ server.once("close", () => {
1087
+ internalDestroyServices(services);
1088
+ });
1089
+ let stopping = false;
1090
+ const stop = () => {
1091
+ if (stopping) return;
1092
+ stopping = true;
1093
+ (async () => {
1094
+ let forceTimer;
1095
+ try {
1096
+ await new Promise((resolve) => {
1097
+ server.close(() => resolve());
1098
+ forceTimer = setTimeout(() => server.closeAllConnections(), timeout);
1099
+ });
1100
+ } finally {
1101
+ if (forceTimer) clearTimeout(forceTimer);
1102
+ }
1103
+ await internalDestroyServices(services);
1104
+ process.exit(0);
1105
+ })();
1106
+ };
1107
+ process.once("SIGTERM", stop);
1108
+ process.once("SIGINT", stop);
1109
+ }
1110
+ callback() {
1111
+ const fn = compose([
1112
+ middleware.web(async (ctx, next) => {
1113
+ const language = this.resolveLanguage(ctx);
1114
+ await ensureI18nLanguage(language);
1115
+ return I18n.provider(language, next);
1116
+ }),
1117
+ parseBody(this.options.body),
1118
+ ...this.middlewareList
1119
+ ]);
1120
+ if (!this.listenerCount("error")) this.on("error", (err) => {
1121
+ if (err.expose) return;
1122
+ this.logger.error(err);
1123
+ });
1124
+ return (req, res) => {
1125
+ return fn(new WebContext(this, req, res)).then(res.flush).catch(res.onError);
1126
+ };
1127
+ }
1128
+ /**
1129
+ * 监听http服务
1130
+ * ```typescript
1131
+ * app.listen(3000);
1132
+ * ```
1133
+ */
1134
+ listen = (...args) => {
1135
+ return this.http({}).listen(...args);
1136
+ };
1137
+ /**
1138
+ * 监听http服务,可定制参数
1139
+ * ```typescript
1140
+ * app.http({...}).listen(3000);
1141
+ * ```
1142
+ */
1143
+ http(options) {
1144
+ const server = http.createServer({
1145
+ ...options,
1146
+ IncomingMessage: WebRequest,
1147
+ ServerResponse: WebResponse
1148
+ }, this.callback());
1149
+ this.bindServerLifecycle(server);
1150
+ return { listen: server.listen.bind(server) };
1151
+ }
1152
+ /**
1153
+ * 监听https服务,需提供证书
1154
+ * ```typescript
1155
+ * app.https({...}).listen(3000);
1156
+ * ```
1157
+ */
1158
+ https(options) {
1159
+ const server = https.createServer({
1160
+ ...options,
1161
+ IncomingMessage: WebRequest,
1162
+ ServerResponse: WebResponse
1163
+ }, this.callback());
1164
+ this.bindServerLifecycle(server);
1165
+ return { listen: server.listen.bind(server) };
1166
+ }
592
1167
  };
593
-
594
1168
  // src/override/web-middleware.ts
595
- import { Middleware as Middleware2 } from "@aomex/common";
596
- var WebMiddleware = class extends Middleware2 {
597
- openapiInjector;
598
- constructor(args) {
599
- const { fn, openapi = {} } = typeof args === "function" ? { fn: args } : args;
600
- super(fn);
601
- this.openapiInjector = openapi;
602
- }
603
- openapi() {
604
- return this.openapiInjector;
605
- }
1169
+ var WebMiddleware = class extends Middleware {
1170
+ openapiInjector;
1171
+ constructor(args) {
1172
+ const { fn, openapi = {} } = typeof args === "function" ? { fn: args } : args;
1173
+ super(fn);
1174
+ this.openapiInjector = openapi;
1175
+ }
1176
+ openapi() {
1177
+ return this.openapiInjector;
1178
+ }
606
1179
  };
607
- Middleware2.register("web", WebMiddleware);
608
-
1180
+ Middleware.register("web", WebMiddleware);
609
1181
  // src/override/file.validator.ts
610
- import { PersistentFile } from "formidable";
611
- import mimeTypes2 from "mime-types";
612
- import {
613
- Validator,
614
- ValidateResult,
615
- Rule
616
- } from "@aomex/common";
617
- import { bytes } from "@aomex/internal-tools";
618
- import typeIs3 from "type-is";
619
1182
  var FileValidator = class extends Validator {
620
- /**
621
- * 允许的最大体积
622
- *
623
- * 可选格式:
624
- * - 1024
625
- * - 2048
626
- * - '15KB'
627
- * - '20MB'
628
- */
629
- maxSize(byte) {
630
- const validator = this.copy();
631
- validator.config.maxSize = typeof byte === "number" ? byte : bytes(byte);
632
- return validator;
633
- }
634
- mimeTypes(mineOrExt, ...others) {
635
- const validator = this.copy();
636
- validator.config.mimeTypes = [
637
- ...new Set(
638
- [].concat(mineOrExt).concat(others).map(mimeTypes2.lookup).filter(Boolean)
639
- )
640
- ];
641
- return validator;
642
- }
643
- isEmpty(value) {
644
- return super.isEmpty(value) || Array.isArray(value) && !value.length;
645
- }
646
- validateValue(file, _key, label) {
647
- const { maxSize, mimeTypes: mimeTypes3 } = this.config;
648
- if (Array.isArray(file)) file = file[0];
649
- if (!(file instanceof PersistentFile)) {
650
- return ValidateResult.deny(i18n.t("validator.file.must_be_file", { label }));
651
- }
652
- if (maxSize !== void 0 && file.size > maxSize) {
653
- return ValidateResult.deny(i18n.t("validator.file.too_large", { label }));
654
- }
655
- const hasMimeTypeLimitation = mimeTypes3 && mimeTypes3.length;
656
- if (hasMimeTypeLimitation && (!file.mimetype || !typeIs3.is(file.mimetype, ...mimeTypes3))) {
657
- return ValidateResult.deny(
658
- i18n.t("validator.file.unsupported_mimetype", { label })
659
- );
660
- }
661
- return ValidateResult.accept(file);
662
- }
663
- toDocument() {
664
- return {
665
- type: "string",
666
- format: "binary"
667
- };
668
- }
1183
+ /**
1184
+ * 允许的最大体积
1185
+ *
1186
+ * 可选格式:
1187
+ * - 1024
1188
+ * - 2048
1189
+ * - '15KB'
1190
+ * - '20MB'
1191
+ */
1192
+ maxSize(byte) {
1193
+ const validator = this.copy();
1194
+ validator.config.maxSize = typeof byte === "number" ? byte : bytes(byte);
1195
+ return validator;
1196
+ }
1197
+ mimeTypes(mineOrExt, ...others) {
1198
+ const tokens = [].concat(mineOrExt).concat(others);
1199
+ const validator = this.copy();
1200
+ validator.config.mimeTypes = [...new Set(tokens.map((token) => this.resolveMimeType(token)))];
1201
+ return validator;
1202
+ }
1203
+ /**
1204
+ * 认不出文件签名时,改用客户端声明的 Content-Type 对照 `mimeTypes()`。
1205
+ * 不调用则仍然拒绝。参数默认值:`true`。
1206
+ *
1207
+ * 没有稳定文件签名、允许时要打开:纯文本、CSV、Markdown、CSS、JSON、
1208
+ * JavaScript 源码、HTML,以及不以 `<?xml` 开头的 SVG。
1209
+ * 带 `<?xml` 的 XML 会被认成 `application/xml`,不必开;同样开头的 SVG
1210
+ * 也会被认成 XML,`image/svg+xml` 仍然对不上。
1211
+ */
1212
+ fallbackToMimetype(enable = true) {
1213
+ const validator = this.copy();
1214
+ validator.config.fallbackToMimetype = enable;
1215
+ return validator;
1216
+ }
1217
+ isEmpty(value) {
1218
+ return super.isEmpty(value) || Array.isArray(value) && !value.length;
1219
+ }
1220
+ async validateValue(file, _key, label) {
1221
+ const { maxSize, mimeTypes, fallbackToMimetype } = this.config;
1222
+ if (Array.isArray(file)) file = file[0];
1223
+ if (!(file instanceof PersistentFile)) return ValidateResult.deny(i18n.t("validator.file.must_be_file", { label }));
1224
+ if (maxSize !== void 0 && file.size > maxSize) return ValidateResult.deny(i18n.t("validator.file.too_large", { label }));
1225
+ const detected = file.filepath ? await this.detectMimeType(file.filepath) : void 0;
1226
+ if (detected) file.mimetype = detected;
1227
+ const hasMimeTypeLimitation = mimeTypes && mimeTypes.length;
1228
+ const actual = detected ?? (fallbackToMimetype ? file.mimetype : null);
1229
+ if (hasMimeTypeLimitation && (!actual || !typeIs.is(actual, ...mimeTypes))) return ValidateResult.deny(i18n.t("validator.file.unsupported_mimetype", { label }));
1230
+ return ValidateResult.accept(file);
1231
+ }
1232
+ /** 读取文件头中的文件签名。认不出时返回 `undefined`。 */
1233
+ async detectMimeType(filepath) {
1234
+ return (await fileTypeFromFile(filepath))?.mime;
1235
+ }
1236
+ /**
1237
+ * 把扩展名查成媒体类型;已是 `type/subtype`(subtype 可为 `*`)则原样返回。
1238
+ * 无法识别时抛错,避免允许列表被悄悄清空。
1239
+ */
1240
+ resolveMimeType(token) {
1241
+ if (token.includes("/")) {
1242
+ if (/^[\w!#$&^.+-]+\/(\*|[\w!#$&^.+-]+)$/i.test(token)) return token;
1243
+ throw new Error(i18n.t("validator.file.invalid_mimetype_token", { token }));
1244
+ }
1245
+ const resolved = mimeTypes.lookup(token);
1246
+ if (!resolved) throw new Error(i18n.t("validator.file.invalid_mimetype_token", { token }));
1247
+ return resolved;
1248
+ }
1249
+ toDocument() {
1250
+ return {
1251
+ type: "string",
1252
+ format: "binary"
1253
+ };
1254
+ }
669
1255
  };
670
1256
  Rule.register("file", FileValidator);
671
-
672
1257
  // src/middleware/body.ts
673
- import {
674
- validate,
675
- Validator as Validator2,
676
- rule,
677
- ValidateDeniedError,
678
- middleware as middleware3
679
- } from "@aomex/common";
680
- var body = (fields) => {
681
- return middleware3.web({
682
- fn: async (ctx, next) => {
683
- try {
684
- ctx.body = await validate(ctx.request.body, fields);
685
- return next();
686
- } catch (e) {
687
- ctx.throw(e instanceof ValidateDeniedError ? 400 : 500, e);
688
- }
689
- },
690
- openapi: {
691
- onMethod(methodItem) {
692
- const schema = Validator2.toDocument(rule.object(fields)).schema;
693
- const contentType = JSON.stringify(schema).includes('"format":"binary"') ? "multipart/form-data" : "application/json";
694
- methodItem.requestBody = {
695
- content: {
696
- [contentType]: { schema }
697
- },
698
- required: Object.values(fields).some(
699
- (validator) => Validator2.toDocument(validator).required
700
- )
701
- };
702
- }
703
- }
704
- });
1258
+ /**
1259
+ * 字段上的文件配额。进入 `array` / `oneOf` / `anyOf` / `allOf`,不进入嵌套 `object`。
1260
+ * 组合分支的个数取较大值;`array` 的个数用自身 `length.max`。
1261
+ */
1262
+ const getFileQuota = (validator) => {
1263
+ if (validator instanceof FileValidator) {
1264
+ const maxSize = validator["config"].maxSize;
1265
+ return {
1266
+ maxFiles: 1,
1267
+ ...maxSize !== void 0 ? { maxSize } : null
1268
+ };
1269
+ }
1270
+ if (validator instanceof ObjectValidator) return null;
1271
+ if (validator instanceof ArrayValidator) {
1272
+ const item = validator["config"].itemValidator;
1273
+ if (!item) return null;
1274
+ const inner = getFileQuota(item);
1275
+ if (!inner) return null;
1276
+ return {
1277
+ maxFiles: validator["config"].lengthRange.max ?? 10,
1278
+ ...inner.maxSize !== void 0 ? { maxSize: inner.maxSize } : null
1279
+ };
1280
+ }
1281
+ let found = false;
1282
+ let maxFiles = 0;
1283
+ let maxSize;
1284
+ for (const child of validator["nested"]()) {
1285
+ const quota = getFileQuota(child);
1286
+ if (!quota) continue;
1287
+ found = true;
1288
+ maxFiles = Math.max(maxFiles, quota.maxFiles);
1289
+ if (quota.maxSize !== void 0) maxSize = Math.max(maxSize ?? 0, quota.maxSize);
1290
+ }
1291
+ if (!found) return null;
1292
+ return {
1293
+ maxFiles: Math.max(1, maxFiles),
1294
+ ...maxSize !== void 0 ? { maxSize } : null
1295
+ };
1296
+ };
1297
+ const emptyUploadOptions = () => ({
1298
+ allowFileFields: [],
1299
+ maxFiles: 0
1300
+ });
1301
+ /** 只扫这一层 object 的字段,不进入嵌套 object。 */
1302
+ const getObjectUploadOptions = (root) => {
1303
+ const properties = root["config"].properties ?? {};
1304
+ const allowFileFields = [];
1305
+ let maxFileSize;
1306
+ let maxFiles = 0;
1307
+ for (const [key, validator] of Object.entries(properties)) {
1308
+ const quota = getFileQuota(validator);
1309
+ if (!quota) continue;
1310
+ allowFileFields.push(key);
1311
+ maxFiles += quota.maxFiles;
1312
+ if (quota.maxSize !== void 0) maxFileSize = Math.max(maxFileSize ?? 0, quota.maxSize);
1313
+ }
1314
+ if (!allowFileFields.length) return emptyUploadOptions();
1315
+ return {
1316
+ allowFileFields,
1317
+ maxFiles: Math.max(1, maxFiles),
1318
+ ...maxFileSize !== void 0 ? { maxFileSize } : null
1319
+ };
1320
+ };
1321
+ /**
1322
+ * 合并多个分支的上传选项。字段名取并集。
1323
+ * `sumFiles` 为真时个数相加(`allOf`),否则取较大值(`oneOf` / `anyOf`)。
1324
+ */
1325
+ const mergeBranchUploadOptions = (branches, sumFiles) => {
1326
+ const allowFileFields = [];
1327
+ const seen = /* @__PURE__ */ new Set();
1328
+ let maxFileSize;
1329
+ let maxFiles = 0;
1330
+ for (const branch of branches) {
1331
+ for (const field of branch.allowFileFields) {
1332
+ if (seen.has(field)) continue;
1333
+ seen.add(field);
1334
+ allowFileFields.push(field);
1335
+ }
1336
+ if (branch.maxFileSize !== void 0) maxFileSize = Math.max(maxFileSize ?? 0, branch.maxFileSize);
1337
+ maxFiles = sumFiles ? maxFiles + branch.maxFiles : Math.max(maxFiles, branch.maxFiles);
1338
+ }
1339
+ if (!allowFileFields.length) return emptyUploadOptions();
1340
+ return {
1341
+ allowFileFields,
1342
+ maxFiles: Math.max(1, maxFiles),
1343
+ ...maxFileSize !== void 0 ? { maxFileSize } : null
1344
+ };
1345
+ };
1346
+ /**
1347
+ * 根为 object 时扫顶层字段。
1348
+ * 其余有 `nested()` 子节点就展开,包括 `array` / `oneOf` / `anyOf` / `allOf`。
1349
+ * `oneOf` / `anyOf` / `array` 个数取较大值,`allOf` 个数相加。
1350
+ */
1351
+ const getRootUploadOptions = (validator) => {
1352
+ if (validator instanceof ObjectValidator) return getObjectUploadOptions(validator);
1353
+ const children = validator["nested"]();
1354
+ if (!children.length) return emptyUploadOptions();
1355
+ return mergeBranchUploadOptions(children.map(getRootUploadOptions).filter((branch) => branch.allowFileFields.length > 0), validator instanceof AllOfValidator);
1356
+ };
1357
+ /**
1358
+ * 从 body schema 收集 multipart 文件白名单与体积/数量上限。
1359
+ * 字段名是平铺的,只认对象这一层的名字,不进入嵌套 object。
1360
+ *
1361
+ * `maxFileSize` 只在出现 `file().maxSize()` 时带出,多个取较大值;
1362
+ * 没写则交给 `ensureBody` / 应用 `formData` 上限。
1363
+ *
1364
+ * 会收集:
1365
+ * - `object({ avatar: file() })`:1 个
1366
+ * - `object({ photos: array(file()).length({ max }) })`:个数为 `max`,缺省为 `DEFAULT_MAX_FILES`
1367
+ * - 同一 object 上多个文件字段:名字都要,个数相加,`maxSize` 取较大值
1368
+ * - 字段上的 `oneOf` / `anyOf` / `allOf`(分支是 `file` 或 `array(file)`):收录该字段,个数取各分支较大值
1369
+ * `oneOf([file(), array(file()).length({ max: 3 })])` → 3
1370
+ * `array(oneOf([file(), string()]))` → 用 array 的 `length.max`
1371
+ * - 根是 `oneOf` / `anyOf`,分支是 object(可再套组合):字段名取并集,个数取各分支较大值
1372
+ * `anyOf([object({ avatar: file() }), object({ name: string() })])` → `avatar`
1373
+ * `oneOf([object({ avatar: file() }), object({ photos: array(file()).length({ max: 3 }) })])` → 3
1374
+ * - 根是 `allOf`,分支是 object:字段名取并集(同名只留一次),个数相加
1375
+ * `allOf([object({ avatar: file() }), object({ cover: file() })])` → 2
1376
+ * - 根是 `array(object({ avatar: file() }))`:收录对象顶层的 `avatar`。
1377
+ * 外层 array 的 `length.max` 不参与个数
1378
+ *
1379
+ * 不收集:
1380
+ * - 根不是 object,也没有能展开出文件字段的子节点,如 `string()` / `array(file())` / `file()`
1381
+ * - 组合分支里没有带文件字段的 object
1382
+ * - 嵌套 object:`object({ profile: object({ avatar: file() }) })`
1383
+ * - 字段上的组合或 array 只含 object:`oneOf([object({ f: file() }), string()])`、
1384
+ * `array(object({ file: file() }))`
1385
+ */
1386
+ const getFileUploadOptions = (fields) => getRootUploadOptions(toValidator(fields));
1387
+ /**
1388
+ * 验证请求实体。`multipart` 时按 schema 解析(仅白名单字段收文件)。
1389
+ */
1390
+ const body = (fields) => {
1391
+ return middleware.web({
1392
+ fn: async (ctx, next) => {
1393
+ try {
1394
+ await ctx[internalEnsureBodyKey](getFileUploadOptions(fields));
1395
+ ctx.body = await validate(ctx.request.body, fields);
1396
+ return next();
1397
+ } catch (e) {
1398
+ ctx.throw(e instanceof ValidateDeniedError ? 400 : 500, e);
1399
+ }
1400
+ },
1401
+ openapi: { onMethod(methodItem) {
1402
+ const docs = toDocument(fields);
1403
+ const schema = docs.schema;
1404
+ methodItem.requestBody = {
1405
+ content: { [Validator.has(toValidator(fields), FileValidator) ? "multipart/form-data" : "application/json"]: { schema } },
1406
+ required: schema.type === "object" ? !!schema.required?.length : !!docs.required
1407
+ };
1408
+ } }
1409
+ });
705
1410
  };
706
-
707
1411
  // src/middleware/query.ts
708
- import { middleware as middleware4, validate as validate2, Validator as Validator3, ValidateDeniedError as ValidateDeniedError2 } from "@aomex/common";
709
- var query = (fields) => {
710
- return middleware4.web({
711
- fn: async (ctx, next) => {
712
- try {
713
- ctx.query = await validate2(ctx.request.query, fields);
714
- return next();
715
- } catch (e) {
716
- ctx.throw(e instanceof ValidateDeniedError2 ? 400 : 500, e);
717
- }
718
- },
719
- openapi: {
720
- onMethod(methodItem) {
721
- methodItem.parameters ||= [];
722
- Object.entries(fields).forEach(([name, validator]) => {
723
- methodItem.parameters.push({
724
- name,
725
- in: "query",
726
- ...Validator3.toDocument(validator)
727
- });
728
- });
729
- }
730
- }
731
- });
1412
+ /**
1413
+ * 验证请求查询字符串
1414
+ */
1415
+ const query = (fields) => {
1416
+ return middleware.web({
1417
+ fn: async (ctx, next) => {
1418
+ try {
1419
+ ctx.query = await validate(ctx.request.query, fields);
1420
+ return next();
1421
+ } catch (e) {
1422
+ ctx.throw(e instanceof ValidateDeniedError ? 400 : 500, e);
1423
+ }
1424
+ },
1425
+ openapi: { onMethod(methodItem) {
1426
+ methodItem.parameters ||= [];
1427
+ Object.entries(fields instanceof ValidatorSchema ? fields["rules"] : fields).forEach(([name, validator]) => {
1428
+ methodItem.parameters.push({
1429
+ name,
1430
+ in: "query",
1431
+ ...toDocument(validator)
1432
+ });
1433
+ });
1434
+ } }
1435
+ });
732
1436
  };
733
-
734
1437
  // src/middleware/params.ts
735
- import { middleware as middleware5, validate as validate3, Validator as Validator4, ValidateDeniedError as ValidateDeniedError3 } from "@aomex/common";
736
- var params = (fields) => {
737
- return middleware5.web({
738
- fn: async (ctx, next) => {
739
- try {
740
- ctx.params = await validate3(ctx.request.params, fields);
741
- return next();
742
- } catch (e) {
743
- ctx.throw(e instanceof ValidateDeniedError3 ? 400 : 500, e);
744
- }
745
- },
746
- openapi: {
747
- onMethod(methodItem) {
748
- methodItem.parameters ||= [];
749
- Object.entries(fields).forEach(([name, validator]) => {
750
- const validatorDocument = Validator4.toDocument(validator);
751
- methodItem.parameters.push({
752
- name,
753
- in: "path",
754
- ...validatorDocument,
755
- // path必填参数
756
- required: validatorDocument.required === true
757
- });
758
- });
759
- }
760
- }
761
- });
1438
+ /**
1439
+ * 验证请求路径参数
1440
+ */
1441
+ const params = (fields) => {
1442
+ return middleware.web({
1443
+ fn: async (ctx, next) => {
1444
+ try {
1445
+ ctx.params = await validate(ctx.request.params, fields);
1446
+ return next();
1447
+ } catch (e) {
1448
+ ctx.throw(e instanceof ValidateDeniedError ? 400 : 500, e);
1449
+ }
1450
+ },
1451
+ openapi: { onMethod(methodItem) {
1452
+ methodItem.parameters ||= [];
1453
+ Object.entries(fields instanceof ValidatorSchema ? fields["rules"] : fields).forEach(([name, validator]) => {
1454
+ const validatorDocument = toDocument(validator);
1455
+ methodItem.parameters.push({
1456
+ name,
1457
+ in: "path",
1458
+ ...validatorDocument,
1459
+ required: validatorDocument.required === true
1460
+ });
1461
+ });
1462
+ } }
1463
+ });
1464
+ };
1465
+ // src/middleware/response-media.ts
1466
+ /** 由 `content` / `contentType` 解析 OpenAPI media type */
1467
+ const resolveResponseContentType = (options) => {
1468
+ let { contentType, content } = options;
1469
+ if (!contentType) {
1470
+ const docs = toValidator(content)["toDocument"]();
1471
+ switch (docs.type) {
1472
+ case "array":
1473
+ case "object":
1474
+ contentType = getMimeType("json");
1475
+ break;
1476
+ case "boolean":
1477
+ case "integer":
1478
+ case "number":
1479
+ contentType = getMimeType("text");
1480
+ break;
1481
+ case "string":
1482
+ if (docs.format === "binary") contentType = getMimeType("bin");
1483
+ else contentType = getMimeType("text");
1484
+ break;
1485
+ default: contentType = "*/*";
1486
+ }
1487
+ } else if (!contentType.includes("*")) contentType = getMimeType(contentType);
1488
+ return contentType.split(";")[0];
1489
+ };
1490
+ // src/middleware/format-error.ts
1491
+ /**
1492
+ * OpenAPI 临时约定键前缀。具体键:
1493
+ * - `x-response-format-default`:未指定 `statusCodes`(接管全部)
1494
+ * - `x-response-format-400` 等:每个声明的状态码各一个
1495
+ * 值为完整 `ResponseObject`,供无 `content` 的 `response` 整份借用后单点覆盖;
1496
+ * `postMethod` 清理。
1497
+ */
1498
+ const X_RESPONSE_FORMAT_PREFIX = "x-response-format-";
1499
+ const X_RESPONSE_FORMAT_DEFAULT = `${X_RESPONSE_FORMAT_PREFIX}default`;
1500
+ const responseFormatKey = (statusCode) => `${X_RESPONSE_FORMAT_PREFIX}${statusCode}`;
1501
+ var FormatErrorMiddleware = class extends WebMiddleware {
1502
+ options;
1503
+ constructor(options) {
1504
+ super(async (ctx, next) => {
1505
+ try {
1506
+ await next();
1507
+ } catch (e) {
1508
+ const res = ctx.response;
1509
+ if (res["_errorHandled"]) throw e;
1510
+ const err = HttpError.from(e);
1511
+ const { statusCodes } = options;
1512
+ if (statusCodes && !statusCodes.includes(err.statusCode)) throw err;
1513
+ res.removeHeaders(...res.getHeaderNames());
1514
+ err.headers && res.setHeaders(err.headers);
1515
+ res.statusCode = err.statusCode;
1516
+ res["_errorHandled"] = true;
1517
+ const body = await options.handler(this.toPublic(err));
1518
+ if (body !== void 0) ctx.send(body);
1519
+ throw err;
1520
+ }
1521
+ });
1522
+ this.options = options;
1523
+ }
1524
+ /** 生成可安全导出的公开视图(与默认 `onError` 同一套 expose 规则) */
1525
+ toPublic(err) {
1526
+ return {
1527
+ statusCode: err.statusCode,
1528
+ code: err.code,
1529
+ message: err.expose ? err.message : statuses$1.message[err.statusCode] ?? "Error",
1530
+ expose: err.expose,
1531
+ raw: err
1532
+ };
1533
+ }
1534
+ openapi() {
1535
+ return {
1536
+ onMethod: (methodItem) => {
1537
+ methodItem.responses ||= {};
1538
+ const { content, headers, example, description = "", statusCodes } = this.options;
1539
+ if (statusCodes && statusCodes.length === 0) return;
1540
+ const keys = statusCodes?.length ? statusCodes.map(String) : ["default"];
1541
+ let contentMap;
1542
+ if (content) contentMap = { [resolveResponseContentType(this.options)]: {
1543
+ schema: toDocument(content).schema,
1544
+ example
1545
+ } };
1546
+ const ext = methodItem;
1547
+ for (const key of keys) {
1548
+ const resItem = { description };
1549
+ if (contentMap) resItem.content = structuredClone(contentMap);
1550
+ if (headers) resItem.headers = Object.fromEntries(Object.entries(headers).map(([name, header]) => [name, toDocument(header)]));
1551
+ methodItem.responses[key] = resItem;
1552
+ ext[key === "default" ? X_RESPONSE_FORMAT_DEFAULT : responseFormatKey(Number(key))] = structuredClone(resItem);
1553
+ }
1554
+ },
1555
+ postMethod: (methodItem) => {
1556
+ const ext = methodItem;
1557
+ for (const key of Object.keys(ext)) if (key.startsWith("x-response-format-")) delete ext[key];
1558
+ }
1559
+ };
1560
+ }
1561
+ getContentType() {
1562
+ return resolveResponseContentType(this.options);
1563
+ }
1564
+ };
1565
+ /**
1566
+ * 错误响应格式化:`handler` 返回 body 后重新抛出,
1567
+ * 外侧中间件的 `catch` 仍可执行;已格式化则跳过默认纯文本兜底。
1568
+ *
1569
+ * `statusCodes` 有运行时语义:指定后只有这些状态会进入本中间件。
1570
+ *
1571
+ * ```ts
1572
+ * formatError({
1573
+ * statusCodes: [400, 422],
1574
+ * content: { code: rule.string(), message: rule.string() },
1575
+ * handler(err) {
1576
+ * // 用 err.message(已净化);不要把 err.raw.message / stack 写入响应
1577
+ * return { code: err.code ?? 'HTTP_ERROR', message: err.message };
1578
+ * },
1579
+ * });
1580
+ * ```
1581
+ */
1582
+ const formatError = (options) => {
1583
+ return new FormatErrorMiddleware(options);
762
1584
  };
763
-
764
1585
  // src/middleware/response.ts
765
- import { toValidator, Validator as Validator5 } from "@aomex/common";
766
1586
  var WebResponseMiddleware = class extends WebMiddleware {
767
- constructor(options) {
768
- super(async (_, next) => next());
769
- this.options = options;
770
- }
771
- openapi() {
772
- return {
773
- onMethod: (methodItem) => {
774
- methodItem.responses ||= {};
775
- const { statusCode, content, headers, example, description = "" } = this.options;
776
- const resItem = methodItem.responses[statusCode] = {
777
- description
778
- };
779
- if (content) {
780
- resItem.content = {
781
- [this.getContentType()]: {
782
- schema: Validator5.toDocument(toValidator(content)).schema,
783
- example
784
- }
785
- };
786
- }
787
- if (headers) {
788
- resItem.headers = Object.fromEntries(
789
- Object.entries(headers).map(([key, header]) => [
790
- key,
791
- Validator5.toDocument(header)
792
- ])
793
- );
794
- }
795
- }
796
- };
797
- }
798
- getContentType() {
799
- let { contentType, content } = this.options;
800
- if (!contentType) {
801
- const validator = toValidator(content);
802
- const docs = validator["toDocument"]();
803
- switch (docs.type) {
804
- case "array":
805
- case "object":
806
- contentType = getMimeType("json");
807
- break;
808
- case "boolean":
809
- case "integer":
810
- case "number":
811
- contentType = getMimeType("text");
812
- break;
813
- case "string":
814
- if (docs.format === "binary") {
815
- contentType = getMimeType("bin");
816
- } else {
817
- contentType = getMimeType("text");
818
- }
819
- break;
820
- default:
821
- contentType = "*/*";
822
- }
823
- } else if (!contentType.includes("*")) {
824
- contentType = getMimeType(contentType);
825
- }
826
- return contentType.split(";")[0];
827
- }
1587
+ options;
1588
+ constructor(options) {
1589
+ super(async (_, next) => next());
1590
+ this.options = options;
1591
+ }
1592
+ openapi() {
1593
+ return { onMethod: (methodItem) => {
1594
+ methodItem.responses ||= {};
1595
+ const { statusCode, content, headers, example } = this.options;
1596
+ const prev = methodItem.responses[statusCode];
1597
+ if (!content) {
1598
+ const borrowed = this.peekResponseFormat(methodItem, statusCode);
1599
+ const resItem = prev && !("$ref" in prev) ? prev : borrowed ? structuredClone(borrowed) : { description: "" };
1600
+ if (this.options.description !== void 0) resItem.description = this.options.description;
1601
+ else if (!resItem.description) resItem.description = "";
1602
+ if (headers) resItem.headers = Object.fromEntries(Object.entries(headers).map(([key, header]) => [key, toDocument(header)]));
1603
+ methodItem.responses[statusCode] = resItem;
1604
+ return;
1605
+ }
1606
+ const resItem = methodItem.responses[statusCode] = { description: this.options.description ?? "" };
1607
+ resItem.content = { [resolveResponseContentType(this.options)]: {
1608
+ schema: toDocument(content).schema,
1609
+ example
1610
+ } };
1611
+ if (headers) resItem.headers = Object.fromEntries(Object.entries(headers).map(([key, header]) => [key, toDocument(header)]));
1612
+ } };
1613
+ }
1614
+ getContentType() {
1615
+ return resolveResponseContentType(this.options);
1616
+ }
1617
+ /** 优先读对应状态键,再回退 `x-response-format-default` */
1618
+ peekResponseFormat(methodItem, statusCode) {
1619
+ const ext = methodItem;
1620
+ const specific = ext[responseFormatKey(statusCode)];
1621
+ if (specific) return specific;
1622
+ return ext[X_RESPONSE_FORMAT_DEFAULT];
1623
+ }
828
1624
  };
829
- var response = (options) => {
830
- return new WebResponseMiddleware(options);
1625
+ /**
1626
+ * 响应数据声明。多个状态码时请多次调用函数。
1627
+ * - 生成openapi文档
1628
+ * - 静态类型约束,以保证运行时和文档一致
1629
+ *
1630
+ * 错误状态若只声明 `statusCode`、不写 `content`:整份借用
1631
+ * `x-response-format-{code}` / `default`(含 description、content、headers),
1632
+ * 再按本中间件显式字段单点覆盖。
1633
+ */
1634
+ const response = (options) => {
1635
+ return new WebResponseMiddleware(options);
831
1636
  };
832
-
833
- // src/router/routers.ts
834
- import { middleware as middleware7 } from "@aomex/common";
835
- import {
836
- pathToFiles,
837
- getFileValues
838
- } from "@aomex/internal-file-import";
839
-
840
- // src/router/router.ts
841
- import { compose as compose2 } from "@aomex/common";
842
-
843
1637
  // src/router/builder.ts
844
- import { middleware as middleware6 } from "@aomex/common";
845
- import { match } from "path-to-regexp";
846
- var pureUriPattern = /^[\/a-z0-9-_]+$/i;
847
- var duplicatedSlash = /\/{2,}/g;
848
- var sideSlash = /(^\/|\/$)/g;
1638
+ const pureUriPattern = /^[\/a-z0-9-_]+$/i;
1639
+ const duplicatedSlash = /\/{2,}/g;
1640
+ const sideSlash = /(^\/|\/$)/g;
849
1641
  var Builder = class {
850
- constructor(prefix, uri, methods, options) {
851
- this.methods = methods;
852
- this.uri = "/" + (prefix + uri).replaceAll(duplicatedSlash, "/").replaceAll(sideSlash, "");
853
- this.docs = options.docs || {};
854
- this.docs.showInOpenapi ??= true;
855
- this.middlewareList = [
856
- ...options.mount || [],
857
- middleware6.web((ctx, _) => options.action(ctx))
858
- ];
859
- this.matchFn = match(this.uri);
860
- }
861
- static METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
862
- uri;
863
- docs;
864
- middlewareList;
865
- matchFn;
866
- isPureUri() {
867
- return pureUriPattern.test(this.uri);
868
- }
869
- match(pathname) {
870
- const matchResult = this.matchFn(pathname);
871
- return matchResult ? matchResult.params : false;
872
- }
1642
+ methods;
1643
+ static METHODS = [
1644
+ "GET",
1645
+ "POST",
1646
+ "PUT",
1647
+ "PATCH",
1648
+ "DELETE"
1649
+ ];
1650
+ uri;
1651
+ docs;
1652
+ middlewareList;
1653
+ matchFn;
1654
+ constructor(prefix, uri, methods, options) {
1655
+ this.methods = methods;
1656
+ this.uri = "/" + (prefix + uri).replaceAll(duplicatedSlash, "/").replaceAll(sideSlash, "");
1657
+ this.docs = options.docs || {};
1658
+ this.docs.showInOpenapi ??= true;
1659
+ this.middlewareList = [...options.mount || [], middleware.web((ctx, _) => options.action(ctx))];
1660
+ this.matchFn = match(this.uri);
1661
+ }
1662
+ isPureUri() {
1663
+ return pureUriPattern.test(this.uri);
1664
+ }
1665
+ match(pathname) {
1666
+ const matchResult = this.matchFn(pathname);
1667
+ return matchResult ? matchResult.params : false;
1668
+ }
873
1669
  };
874
-
875
1670
  // src/router/router.ts
876
1671
  var Router = class {
877
- constructor(opts = {}) {
878
- this.opts = opts;
879
- this.prefix = opts.prefix || "";
880
- this.middlewareList = opts.mount || [];
881
- this.docs = opts.docs || {};
882
- }
883
- middlewareList;
884
- prefix;
885
- builders = [];
886
- docs;
887
- /**
888
- * 接收Get和Head请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
889
- */
890
- get(uri, options) {
891
- return this.create(uri, ["GET"], options);
892
- }
893
- /**
894
- * 接收Post请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
895
- */
896
- post(uri, options) {
897
- return this.create(uri, ["POST"], options);
898
- }
899
- /**
900
- * 接收Put请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
901
- */
902
- put(uri, options) {
903
- return this.create(uri, ["PUT"], options);
904
- }
905
- /**
906
- * 接收Patch请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
907
- */
908
- patch(uri, options) {
909
- return this.create(uri, ["PATCH"], options);
910
- }
911
- /**
912
- * 接收Delete请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
913
- */
914
- delete(uri, options) {
915
- return this.create(uri, ["DELETE"], options);
916
- }
917
- /**
918
- * 接收所有请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
919
- */
920
- all(uri, options) {
921
- return this.create(uri, Builder.METHODS, options);
922
- }
923
- /**
924
- * 接收指定的请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
925
- */
926
- customize(methods, uri, options) {
927
- return this.create(uri, methods, options);
928
- }
929
- create(uri, methods, options) {
930
- options.docs = { ...this.docs, ...options.docs };
931
- const builder = new Builder(this.prefix, uri, methods, options);
932
- options.disable !== true && this.builders.push(builder);
933
- }
934
- collect() {
935
- const collections = {
936
- GET: [],
937
- POST: [],
938
- PUT: [],
939
- PATCH: [],
940
- DELETE: []
941
- };
942
- for (let i = 0; i < this.builders.length; ++i) {
943
- const builder = this.builders[i];
944
- const handler = {
945
- uri: builder.uri,
946
- isPureUri: builder.isPureUri(),
947
- match: builder.match.bind(builder),
948
- route: compose2(this.middlewareList.concat(builder["middlewareList"]))
949
- };
950
- for (const method of builder["methods"]) {
951
- collections[method].push(handler);
952
- }
953
- }
954
- return collections;
955
- }
1672
+ opts;
1673
+ middlewareList;
1674
+ prefix;
1675
+ builders = [];
1676
+ docs;
1677
+ constructor(opts = {}) {
1678
+ this.opts = opts;
1679
+ this.prefix = opts.prefix || "";
1680
+ this.middlewareList = opts.mount || [];
1681
+ this.docs = opts.docs || {};
1682
+ }
1683
+ /**
1684
+ * 接收Get和Head请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1685
+ */
1686
+ get(uri, options) {
1687
+ return this.create(uri, ["GET"], options);
1688
+ }
1689
+ /**
1690
+ * 接收Post请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1691
+ */
1692
+ post(uri, options) {
1693
+ return this.create(uri, ["POST"], options);
1694
+ }
1695
+ /**
1696
+ * 接收Put请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1697
+ */
1698
+ put(uri, options) {
1699
+ return this.create(uri, ["PUT"], options);
1700
+ }
1701
+ /**
1702
+ * 接收Patch请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1703
+ */
1704
+ patch(uri, options) {
1705
+ return this.create(uri, ["PATCH"], options);
1706
+ }
1707
+ /**
1708
+ * 接收Delete请求,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1709
+ */
1710
+ delete(uri, options) {
1711
+ return this.create(uri, ["DELETE"], options);
1712
+ }
1713
+ /**
1714
+ * 接收所有请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1715
+ */
1716
+ all(uri, options) {
1717
+ return this.create(uri, Builder.METHODS, options);
1718
+ }
1719
+ /**
1720
+ * 接收指定的请求方法,路径规则请参考:https://www.npmjs.com/package/path-to-regexp
1721
+ */
1722
+ customize(methods, uri, options) {
1723
+ return this.create(uri, methods, options);
1724
+ }
1725
+ create(uri, methods, options) {
1726
+ options.docs = {
1727
+ ...this.docs,
1728
+ ...options.docs
1729
+ };
1730
+ const builder = new Builder(this.prefix, uri, methods, options);
1731
+ options.disabled !== true && this.builders.push(builder);
1732
+ }
1733
+ collect() {
1734
+ const collections = {
1735
+ GET: [],
1736
+ POST: [],
1737
+ PUT: [],
1738
+ PATCH: [],
1739
+ DELETE: []
1740
+ };
1741
+ for (let i = 0; i < this.builders.length; ++i) {
1742
+ const builder = this.builders[i];
1743
+ const handler = {
1744
+ uri: builder.uri,
1745
+ isPureUri: builder.isPureUri(),
1746
+ match: builder.match.bind(builder),
1747
+ route: compose(this.middlewareList.concat(builder["middlewareList"]))
1748
+ };
1749
+ for (const method of builder["methods"]) collections[method].push(handler);
1750
+ }
1751
+ return collections;
1752
+ }
956
1753
  };
957
-
958
1754
  // src/router/routers.ts
959
- var routers = (options) => {
960
- let initialized = false;
961
- const staticCollections = {
962
- GET: {},
963
- POST: {},
964
- PUT: {},
965
- PATCH: {},
966
- DELETE: {},
967
- OPTIONS: {},
968
- HEAD: {}
969
- };
970
- const dynamicCollections = {
971
- GET: [],
972
- POST: [],
973
- PUT: [],
974
- PATCH: [],
975
- DELETE: [],
976
- OPTIONS: [],
977
- HEAD: []
978
- };
979
- staticCollections.HEAD = staticCollections.GET;
980
- dynamicCollections.HEAD = dynamicCollections.GET;
981
- let routers2;
982
- let promise = Promise.resolve();
983
- if (isRouters(options)) {
984
- routers2 = options;
985
- } else {
986
- promise = pathToFiles(options).then(async (files) => {
987
- routers2 = await getFileValues(
988
- files,
989
- (item) => !!item && item instanceof Router
990
- );
991
- });
992
- }
993
- const initialize = () => {
994
- for (let i = 0; i < routers2.length; ++i) {
995
- const router = routers2[i];
996
- const subCollections = router["collect"]();
997
- const methods = Object.keys(
998
- subCollections
999
- );
1000
- methods.forEach((method) => {
1001
- subCollections[method].forEach((item) => {
1002
- if (item.isPureUri) {
1003
- if (!Object.hasOwn(staticCollections[method], item.uri)) {
1004
- staticCollections[method][item.uri] = item.route;
1005
- }
1006
- } else {
1007
- dynamicCollections[method].push({ match: item.match, route: item.route });
1008
- }
1009
- });
1010
- });
1011
- }
1012
- initialized = true;
1013
- };
1014
- return middleware7.web(async (ctx, next) => {
1015
- if (!routers2) await promise;
1016
- if (!initialized) initialize();
1017
- const { method, pathname } = ctx.request;
1018
- const staticCollection = staticCollections[method] || {};
1019
- if (Object.hasOwn(staticCollection, pathname)) {
1020
- return staticCollection[pathname](ctx, next);
1021
- }
1022
- const dynamicCollection = dynamicCollections[method] || [];
1023
- for (let i = 0, len = dynamicCollection.length; i < len; ++i) {
1024
- const params2 = dynamicCollection[i].match(pathname);
1025
- if (params2) {
1026
- ctx.request.params = params2;
1027
- return dynamicCollection[i].route(ctx, next);
1028
- }
1029
- }
1030
- return next();
1031
- });
1755
+ const routers = (options) => {
1756
+ let initialized = false;
1757
+ const staticCollections = {
1758
+ GET: {},
1759
+ POST: {},
1760
+ PUT: {},
1761
+ PATCH: {},
1762
+ DELETE: {},
1763
+ OPTIONS: {},
1764
+ HEAD: {}
1765
+ };
1766
+ const dynamicCollections = {
1767
+ GET: [],
1768
+ POST: [],
1769
+ PUT: [],
1770
+ PATCH: [],
1771
+ DELETE: [],
1772
+ OPTIONS: [],
1773
+ HEAD: []
1774
+ };
1775
+ staticCollections.HEAD = staticCollections.GET;
1776
+ dynamicCollections.HEAD = dynamicCollections.GET;
1777
+ let routers;
1778
+ let promise = Promise.resolve();
1779
+ if (isRouters(options)) routers = options;
1780
+ else promise = pathToFiles(options).then(async (files) => {
1781
+ routers = await getFileValues(files, (item) => !!item && item instanceof Router);
1782
+ });
1783
+ const initialize = () => {
1784
+ for (let i = 0; i < routers.length; ++i) {
1785
+ const subCollections = routers[i]["collect"]();
1786
+ Object.keys(subCollections).forEach((method) => {
1787
+ subCollections[method].forEach((item) => {
1788
+ if (item.isPureUri) {
1789
+ if (!Object.hasOwn(staticCollections[method], item.uri)) staticCollections[method][item.uri] = item.route;
1790
+ } else dynamicCollections[method].push({
1791
+ match: item.match,
1792
+ route: item.route
1793
+ });
1794
+ });
1795
+ });
1796
+ }
1797
+ initialized = true;
1798
+ };
1799
+ return middleware.web(async (ctx, next) => {
1800
+ if (!routers) await promise;
1801
+ if (!initialized) initialize();
1802
+ const { method, pathname } = ctx.request;
1803
+ const staticCollection = staticCollections[method] || {};
1804
+ if (Object.hasOwn(staticCollection, pathname)) return staticCollection[pathname](ctx, next);
1805
+ const dynamicCollection = dynamicCollections[method] || [];
1806
+ for (let i = 0, len = dynamicCollection.length; i < len; ++i) {
1807
+ const params = dynamicCollection[i].match(pathname);
1808
+ if (params) {
1809
+ ctx.request.params = params;
1810
+ return dynamicCollection[i].route(ctx, next);
1811
+ }
1812
+ }
1813
+ return next();
1814
+ });
1032
1815
  };
1033
- var isRouters = (options) => {
1034
- return Array.isArray(options) && options.some((item) => item instanceof Router);
1816
+ const isRouters = (options) => {
1817
+ return Array.isArray(options) && options.some((item) => item instanceof Router);
1035
1818
  };
1819
+ export { Builder, EnvelopeBuiltinSlot, EnvelopeCustomSlot, FileValidator, FormatErrorMiddleware, HttpError, Router, ServerSentEvents, WebApp, WebContext, WebMiddleware, WebRequest, WebResponse, WebResponseMiddleware, X_RESPONSE_FORMAT_DEFAULT, X_RESPONSE_FORMAT_PREFIX, applyResponseEnvelope, body, createEnvelopeOpenApiInjector, envelope, formatError, getFileUploadOptions, params, query, response, responseFormatKey, routers, statuses };
1036
1820
 
1037
- // src/index.ts
1038
- import { default as default2 } from "http-errors";
1039
- import { default as default3 } from "statuses";
1040
- export {
1041
- Builder,
1042
- FileValidator,
1043
- Router,
1044
- WebApp,
1045
- WebContext,
1046
- WebMiddleware,
1047
- WebRequest,
1048
- WebResponse,
1049
- WebResponseMiddleware,
1050
- body,
1051
- default2 as createHttpError,
1052
- params,
1053
- query,
1054
- response,
1055
- routers,
1056
- default3 as statuses
1057
- };
1058
1821
  //# sourceMappingURL=index.js.map