@aomex/openapi 3.30.6 → 3.30.8-alpha.1030873.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,462 +1,518 @@
1
- // src/openapi.ts
2
- import { middleware } from "@aomex/common";
3
-
4
- // src/lib/generate-document-with-spinner.ts
5
- import "@aomex/common";
6
-
7
- // ../../node_modules/.pnpm/sleep-promise@9.1.0/node_modules/sleep-promise/build/esm.mjs
8
- var e = setTimeout;
9
- function t(t2, n2) {
10
- var u = n2.useCachedSetTimeout ? e : setTimeout;
11
- return new Promise(function(e2) {
12
- u(e2, t2);
13
- });
14
- }
15
- function n(e2) {
16
- var n2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, u = n2.useCachedSetTimeout, r = t(e2, { useCachedSetTimeout: u });
17
- function o(e3) {
18
- return r.then(function() {
19
- return e3;
20
- });
21
- }
22
- return o.then = function() {
23
- return r.then.apply(r, arguments);
24
- }, o.catch = Promise.resolve().catch, o;
25
- }
26
- var esm_default = n;
27
-
28
- // src/lib/generate-document-with-spinner.ts
29
- import { pathToFiles } from "@aomex/internal-file-import";
30
- import path4 from "path";
31
-
1
+ import { createRequire } from "node:module";
2
+ import { I18n, createI18n, middleware } from "@aomex/common";
3
+ import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
4
+ import path from "node:path";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import YAML from "yaml";
7
+ import { bytes } from "@aomex/internal-tools";
8
+ import { Router, WebMiddleware, createEnvelopeOpenApiInjector } from "@aomex/web";
9
+ import snakeCase from "lodash.snakecase";
10
+ import { terminal } from "@aomex/console";
11
+ // \0rolldown/runtime.js
12
+ var __create = Object.create;
13
+ var __defProp = Object.defineProperty;
14
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
+ var __getOwnPropNames = Object.getOwnPropertyNames;
16
+ var __getProtoOf = Object.getPrototypeOf;
17
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
18
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
21
+ key = keys[i];
22
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
23
+ get: ((k) => from[k]).bind(null, key),
24
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
25
+ });
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
32
33
  // src/lib/validate-openapi.ts
33
- import { createRequire } from "module";
34
- var requireCJS = createRequire(import.meta.url);
35
- var _spectral = null;
36
- var initSpectral = () => {
37
- if (!_spectral) {
38
- const { Spectral } = requireCJS("@stoplight/spectral-core");
39
- const { oas } = requireCJS("@stoplight/spectral-rulesets");
40
- _spectral = new Spectral();
41
- _spectral.setRuleset({
42
- extends: oas,
43
- // https://github.com/stoplightio/spectral/blob/develop/packages/rulesets/src/oas/index.ts
44
- rules: {
45
- "info-contact": "off",
46
- "info-description": "off"
47
- }
48
- });
49
- }
50
- return _spectral;
34
+ var import_cjs = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
35
+ var e = setTimeout;
36
+ function t(t, n) {
37
+ var u = n.useCachedSetTimeout ? e : setTimeout;
38
+ return new Promise((function(e) {
39
+ u(e, t);
40
+ }));
41
+ }
42
+ module.exports = function(e) {
43
+ var u = (arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}).useCachedSetTimeout, r = t(e, { useCachedSetTimeout: u });
44
+ function o(e) {
45
+ return r.then((function() {
46
+ return e;
47
+ }));
48
+ }
49
+ return o.then = function() {
50
+ return r.then.apply(r, arguments);
51
+ }, o.catch = Promise.resolve().catch, o;
52
+ };
53
+ })))(), 1);
54
+ const requireCJS = createRequire(import.meta.url);
55
+ let _spectral = null;
56
+ const initSpectral = () => {
57
+ if (!_spectral) {
58
+ const { Spectral } = requireCJS("@stoplight/spectral-core");
59
+ const { oas } = requireCJS("@stoplight/spectral-rulesets");
60
+ _spectral = new Spectral();
61
+ _spectral.setRuleset({
62
+ extends: oas,
63
+ rules: {
64
+ "info-contact": "off",
65
+ "info-description": "off"
66
+ }
67
+ });
68
+ }
69
+ return _spectral;
51
70
  };
52
- var validateOpenapi = async (document) => {
53
- const result = { warnings: [], errors: [] };
54
- const spectral = initSpectral();
55
- const originResult = await spectral.run(document);
56
- originResult.forEach((item) => {
57
- result[item.severity === 0 /* Error */ ? "errors" : "warnings"].push({
58
- path: item.path.map(String),
59
- message: item.message
60
- });
61
- });
62
- return result;
71
+ const validateOpenapi = async (document) => {
72
+ const result = {
73
+ warnings: [],
74
+ errors: []
75
+ };
76
+ (await initSpectral().run(document)).forEach((item) => {
77
+ result[item.severity === 0 ? "errors" : "warnings"].push({
78
+ path: item.path.map(String),
79
+ message: item.message
80
+ });
81
+ });
82
+ return result;
63
83
  };
64
-
65
84
  // src/lib/methods.ts
66
- var methods = [
67
- "get",
68
- "post",
69
- "put",
70
- "patch",
71
- "delete",
72
- "options",
73
- "head",
74
- "trace"
85
+ const methods = [
86
+ "get",
87
+ "post",
88
+ "put",
89
+ "patch",
90
+ "delete",
91
+ "options",
92
+ "head",
93
+ "trace"
75
94
  ];
76
-
77
95
  // src/lib/hoist-parameter.ts
78
- var methodParameterToPathParameter = (document) => {
79
- pathLoop: for (const path5 of Object.values(document.paths)) {
80
- const parametersHandler = {};
81
- let methodCounter = 0;
82
- for (const method of methods) {
83
- const methodItem = path5[method];
84
- if (!methodItem) continue;
85
- if (!methodItem.parameters?.length) continue pathLoop;
86
- ++methodCounter;
87
- methodItem.parameters.forEach((parameter, index, arr) => {
88
- const uniqueKey = JSON.stringify(parameter);
89
- parameter = arr[index] = JSON.parse(uniqueKey);
90
- const handler = () => {
91
- arr.splice(
92
- arr.findIndex((item) => item === parameter),
93
- 1
94
- );
95
- if (!arr.length) {
96
- delete methodItem.parameters;
97
- }
98
- };
99
- parametersHandler[uniqueKey] ||= [];
100
- parametersHandler[uniqueKey].push(handler);
101
- });
102
- }
103
- if (methodCounter < 2) continue pathLoop;
104
- Object.entries(parametersHandler).forEach(([uniqueKey, handlers]) => {
105
- if (handlers.length !== methodCounter) return;
106
- path5.parameters ||= [];
107
- path5.parameters.push(JSON.parse(uniqueKey));
108
- handlers.forEach((fn) => fn());
109
- });
110
- if (path5.parameters && !path5.parameters.length) {
111
- delete path5.parameters;
112
- }
113
- }
96
+ /**
97
+ * 同一个路径下,所有方法都有相同的parameter时,可以往上提取,这样能减小生成产物
98
+ */
99
+ const methodParameterToPathParameter = (document) => {
100
+ pathLoop: for (const path of Object.values(document.paths)) {
101
+ const parametersHandler = {};
102
+ let methodCounter = 0;
103
+ for (const method of methods) {
104
+ const methodItem = path[method];
105
+ if (!methodItem) continue;
106
+ if (!methodItem.parameters?.length) continue pathLoop;
107
+ ++methodCounter;
108
+ methodItem.parameters.forEach((parameter, index, arr) => {
109
+ const uniqueKey = JSON.stringify(parameter);
110
+ parameter = arr[index] = JSON.parse(uniqueKey);
111
+ const handler = () => {
112
+ arr.splice(arr.findIndex((item) => item === parameter), 1);
113
+ if (!arr.length) delete methodItem.parameters;
114
+ };
115
+ parametersHandler[uniqueKey] ||= [];
116
+ parametersHandler[uniqueKey].push(handler);
117
+ });
118
+ }
119
+ if (methodCounter < 2) continue pathLoop;
120
+ Object.entries(parametersHandler).forEach(([uniqueKey, handlers]) => {
121
+ if (handlers.length !== methodCounter) return;
122
+ path.parameters ||= [];
123
+ path.parameters.push(JSON.parse(uniqueKey));
124
+ handlers.forEach((fn) => fn());
125
+ });
126
+ if (path.parameters && !path.parameters.length) delete path.parameters;
127
+ }
128
+ };
129
+ // src/lib/hoist-schema-ref.ts
130
+ /**
131
+ * 识别 schema 上的 `x-ref`,提取到 `components.schemas`,并替换为 `$ref`。
132
+ * 自底向上处理,保证嵌套 object 先变成 `$ref` 再被父级收录。
133
+ */
134
+ const hoistSchemaRef = (document) => {
135
+ document.components ||= {};
136
+ document.components.schemas ||= {};
137
+ const seen = /* @__PURE__ */ new Map();
138
+ const resolveName = (base, canonical, schema) => {
139
+ let name = base;
140
+ let suffix = 2;
141
+ while (true) {
142
+ const existing = document.components.schemas[name];
143
+ if (!existing) {
144
+ document.components.schemas[name] = schema;
145
+ seen.set(name, canonical);
146
+ return name;
147
+ }
148
+ if ((seen.get(name) ?? JSON.stringify(existing)) === canonical) return name;
149
+ if (name === base) console.warn(`OpenAPI schema component name conflict: "${base}" refers to different schemas, renaming to "${base}-duplicated-${suffix}"`);
150
+ name = `${base}-duplicated-${suffix++}`;
151
+ }
152
+ };
153
+ const visit = (node) => {
154
+ if (!node || typeof node !== "object") return;
155
+ if (Array.isArray(node)) {
156
+ node.forEach(visit);
157
+ return;
158
+ }
159
+ const obj = node;
160
+ for (const value of Object.values(obj)) visit(value);
161
+ const refName = obj["x-ref"];
162
+ if (typeof refName !== "string" || "$ref" in obj) return;
163
+ const { "x-ref": _, ...rest } = obj;
164
+ const cleaned = JSON.parse(JSON.stringify(rest));
165
+ const canonical = JSON.stringify(cleaned);
166
+ const name = resolveName(refName, canonical, cleaned);
167
+ for (const key of Object.keys(obj)) delete obj[key];
168
+ obj["$ref"] = `#/components/schemas/${name}`;
169
+ };
170
+ visit(document.paths);
171
+ if (!Object.keys(document.components.schemas).length) {
172
+ delete document.components.schemas;
173
+ if (!Object.keys(document.components).length) delete document.components;
174
+ }
114
175
  };
115
-
116
176
  // src/lib/save-to-file.ts
117
- import path from "path";
118
- import { mkdir, writeFile } from "fs/promises";
119
- import YAML from "yaml";
120
- import { bytes } from "@aomex/internal-tools";
121
- var saveToFile = async (document, filename, fileMode) => {
122
- const dest = path.resolve(filename || "openapi.json");
123
- const ext = path.extname(dest);
124
- const content = ext.endsWith(".yaml") || ext.endsWith(".yml") ? YAML.stringify(document) : JSON.stringify(document);
125
- const size = bytes(Buffer.byteLength(content), { unitSeparator: "" });
126
- await mkdir(path.dirname(dest), { recursive: true });
127
- await writeFile(dest, content, { mode: fileMode, flush: true });
128
- return { dest, size };
177
+ const saveToFile = async (document, filename, fileMode) => {
178
+ const dest = path.resolve(filename || "openapi.json");
179
+ const ext = path.extname(dest);
180
+ const content = ext.endsWith(".yaml") || ext.endsWith(".yml") ? YAML.stringify(document) : JSON.stringify(document);
181
+ const size = bytes(Buffer.byteLength(content), { unitSeparator: "" });
182
+ await mkdir(path.dirname(dest), { recursive: true });
183
+ await writeFile(dest, content, {
184
+ mode: fileMode,
185
+ flush: true
186
+ });
187
+ return {
188
+ dest,
189
+ size
190
+ };
129
191
  };
130
-
131
192
  // src/lib/initialize-document.ts
132
- import { readFile } from "fs/promises";
133
- import path2 from "path";
134
- var initializeDocument = async (basic) => {
135
- const document = JSON.parse(JSON.stringify(basic || {}));
136
- document.openapi ||= "3.0.3";
137
- document.tags ||= [];
138
- document.info ||= { title: "", version: "" };
139
- document.paths = {};
140
- document.info.title ||= (await readPackageJson()).name || "OpenAPI";
141
- document.info.version ||= (await readPackageJson()).version || "0.0.0";
142
- return document;
193
+ const initializeDocument = async (basic) => {
194
+ const document = JSON.parse(JSON.stringify(basic || {}));
195
+ document.openapi ||= "3.0.3";
196
+ document.tags ||= [];
197
+ document.info ||= {
198
+ title: "",
199
+ version: ""
200
+ };
201
+ document.paths = {};
202
+ document.info.title ||= (await readPackageJson()).name || "OpenAPI";
203
+ document.info.version ||= (await readPackageJson()).version || "0.0.0";
204
+ return document;
143
205
  };
144
- var readPackageJson = async () => {
145
- try {
146
- const content = await readFile(path2.resolve("package.json"), "utf8");
147
- const json = JSON.parse(content);
148
- return json && typeof json === "object" ? json : {};
149
- } catch {
150
- return {};
151
- }
206
+ const readPackageJson = async () => {
207
+ try {
208
+ const content = await readFile(path.resolve("package.json"), "utf8");
209
+ const json = JSON.parse(content);
210
+ return json && typeof json === "object" ? json : {};
211
+ } catch {
212
+ return {};
213
+ }
152
214
  };
153
-
154
- // src/lib/parse-files.ts
155
- import { getFileValues } from "@aomex/internal-file-import";
156
- import { Router, WebMiddleware } from "@aomex/web";
157
- import path3 from "path";
158
-
159
215
  // src/lib/method-to-verb.ts
160
- var methodToVerb = (method, uri) => {
161
- method = method.toLowerCase();
162
- if (method === "get") return uri.includes(":") ? "retrieve" : "list";
163
- if (method === "post") return "create";
164
- if (method === "put") return "replace";
165
- if (method === "patch") return "update";
166
- return method;
216
+ const methodToVerb = (method, uri) => {
217
+ method = method.toLowerCase();
218
+ if (method === "get") return uri.includes(":") ? "retrieve" : "list";
219
+ if (method === "post") return "create";
220
+ if (method === "put") return "replace";
221
+ if (method === "patch") return "update";
222
+ return method;
167
223
  };
168
-
169
224
  // src/lib/parse-files.ts
170
- import snakeCase from "lodash.snakecase";
171
- var parseFiles = async (document, files) => {
172
- const usedTags = [];
173
- const data = [];
174
- for (const file of files) {
175
- const routers = await getFileValues(
176
- [file],
177
- (item) => !!item && item instanceof Router
178
- );
179
- for (const router of routers) {
180
- const groupMiddlewareList = router["middlewareList"];
181
- const builders = router["builders"];
182
- for (const builder of builders) {
183
- if (builder.docs.showInOpenapi === false) continue;
184
- delete builder.docs.showInOpenapi;
185
- const builderMiddlewareList = groupMiddlewareList.concat(builder["middlewareList"]).filter((middleware2) => middleware2 instanceof WebMiddleware);
186
- const uri = builder["uri"];
187
- const pathName = normalizePath(uri);
188
- const pathItem = document.paths[pathName] ||= {};
189
- for (const method of builder["methods"]) {
190
- const methodName = method.toLowerCase();
191
- const methodItem = pathItem[methodName] = {
192
- ...builder.docs,
193
- responses: {}
194
- };
195
- data.push(
196
- ...builderMiddlewareList.map((item) => {
197
- return {
198
- injector: item["openapi"](),
199
- pathItem,
200
- pathName,
201
- methodItem,
202
- methodName,
203
- file,
204
- uri
205
- };
206
- })
207
- );
208
- }
209
- }
210
- }
211
- }
212
- for (const { injector } of data) {
213
- injector.onDocument?.(document);
214
- }
215
- for (const { injector, pathItem, pathName } of data) {
216
- injector.onPath?.(pathItem, { document, pathName });
217
- }
218
- for (const { injector, pathItem, pathName, methodItem, methodName } of data) {
219
- injector.onMethod?.(methodItem, {
220
- document,
221
- pathItem,
222
- pathName,
223
- methodName
224
- });
225
- }
226
- for (const { injector, pathItem, pathName, methodItem, methodName } of data) {
227
- injector.postMethod?.(methodItem, {
228
- document,
229
- pathItem,
230
- pathName,
231
- methodName
232
- });
233
- }
234
- for (const { injector, pathItem, pathName } of data) {
235
- injector.postPath?.(pathItem, { document, pathName });
236
- }
237
- for (const { injector } of data) {
238
- injector.postDocument?.(document);
239
- }
240
- for (const { methodItem, methodName, file, uri } of data) {
241
- methodItem.tags ||= [getTagByFilename(file)];
242
- methodItem.operationId ||= snakeCase(
243
- methodToVerb(methodName, uri) + " " + uri.replaceAll(":", "_by_")
244
- );
245
- if (methodName === "post") {
246
- methodItem["x-codegen-request-body-name"] = "body";
247
- }
248
- if (!Object.keys(methodItem.responses).length) {
249
- methodItem.responses = { default: { description: "" } };
250
- }
251
- usedTags.push(...methodItem.tags);
252
- }
253
- return [...new Set(usedTags)];
225
+ const parseFiles = async (document, files, options = {}) => {
226
+ const mount = options.mount ?? [];
227
+ const envelopeInjector = options.envelope ? createEnvelopeOpenApiInjector(options.envelope) : void 0;
228
+ const usedTags = [];
229
+ const data = [];
230
+ /** 每个 operation 只出现一次,供 envelope 收口与标签补齐 */
231
+ const operations = [];
232
+ for (const file of files) {
233
+ const routers = await getFileValues([file], (item) => !!item && item instanceof Router);
234
+ for (const router of routers) {
235
+ const groupMiddlewareList = router["middlewareList"];
236
+ const builders = router["builders"];
237
+ for (const builder of builders) {
238
+ if (builder.docs.showInOpenapi === false) continue;
239
+ delete builder.docs.showInOpenapi;
240
+ const builderMiddlewareList = mount.concat(groupMiddlewareList).concat(builder["middlewareList"]).filter((middleware) => middleware instanceof WebMiddleware);
241
+ const uri = builder["uri"];
242
+ const pathName = normalizePath(uri);
243
+ const pathItem = document.paths[pathName] ||= {};
244
+ for (const method of builder["methods"]) {
245
+ const methodName = method.toLowerCase();
246
+ const methodItem = pathItem[methodName] = {
247
+ ...builder.docs,
248
+ responses: {}
249
+ };
250
+ operations.push({
251
+ pathItem,
252
+ pathName,
253
+ methodItem,
254
+ methodName,
255
+ file,
256
+ uri
257
+ });
258
+ data.push(...builderMiddlewareList.map((item) => {
259
+ return {
260
+ injector: item["openapi"](),
261
+ pathItem,
262
+ pathName,
263
+ methodItem,
264
+ methodName,
265
+ file,
266
+ uri
267
+ };
268
+ }));
269
+ }
270
+ }
271
+ }
272
+ }
273
+ for (const { injector } of data) injector.onDocument?.(document);
274
+ for (const { injector, pathItem, pathName } of data) injector.onPath?.(pathItem, {
275
+ document,
276
+ pathName
277
+ });
278
+ for (const { injector, pathItem, pathName, methodItem, methodName } of data) injector.onMethod?.(methodItem, {
279
+ document,
280
+ pathItem,
281
+ pathName,
282
+ methodName
283
+ });
284
+ for (const { injector, pathItem, pathName, methodItem, methodName } of data) injector.postMethod?.(methodItem, {
285
+ document,
286
+ pathItem,
287
+ pathName,
288
+ methodName
289
+ });
290
+ if (envelopeInjector?.postMethod) for (const { pathItem, pathName, methodItem, methodName } of operations) envelopeInjector.postMethod(methodItem, {
291
+ document,
292
+ pathItem,
293
+ pathName,
294
+ methodName
295
+ });
296
+ for (const { injector, pathItem, pathName } of data) injector.postPath?.(pathItem, {
297
+ document,
298
+ pathName
299
+ });
300
+ for (const { injector } of data) injector.postDocument?.(document);
301
+ for (const { methodItem, methodName, file, uri } of operations) {
302
+ methodItem.tags ||= [getTagByFilename(file)];
303
+ methodItem.operationId ||= snakeCase(methodToVerb(methodName, uri) + " " + uri.replaceAll(":", "_by_"));
304
+ if (methodName === "post") methodItem["x-codegen-request-body-name"] = "body";
305
+ if (!Object.keys(methodItem.responses).length) methodItem.responses = { default: { description: "" } };
306
+ usedTags.push(...methodItem.tags);
307
+ }
308
+ return [...new Set(usedTags)];
254
309
  };
255
- var normalizePath = (uri) => {
256
- return uri.replace(/:([a-z0-9_?]+)/gi, (_, $1) => {
257
- return `{${$1.replace(/[?]/g, "")}}`;
258
- });
310
+ const normalizePath = (uri) => {
311
+ return uri.replace(/:([a-z0-9_?]+)/gi, (_, $1) => {
312
+ return `{${$1.replace(/[?]/g, "")}}`;
313
+ });
259
314
  };
260
- var getTagByFilename = (file) => {
261
- return path3.basename(file).replace(/\..+$/, "");
315
+ const getTagByFilename = (file) => {
316
+ return path.basename(file).replace(/\..+$/, "");
262
317
  };
263
-
264
318
  // src/lib/append-tag.ts
265
- var appendTag = (document, usedTags) => {
266
- const tags = document.tags ||= [];
267
- const definedTags = tags.map((item) => item.name);
268
- const undefinedTags = usedTags.filter((tag) => !definedTags.includes(tag)).sort();
269
- for (const tag of undefinedTags) {
270
- tags.push({ name: tag });
271
- }
272
- return undefinedTags;
319
+ const appendTag = (document, usedTags) => {
320
+ const tags = document.tags ||= [];
321
+ const definedTags = tags.map((item) => item.name);
322
+ const undefinedTags = usedTags.filter((tag) => !definedTags.includes(tag)).sort();
323
+ for (const tag of undefinedTags) tags.push({ name: tag });
324
+ return undefinedTags;
273
325
  };
274
-
275
- // src/lib/generate-document-with-spinner.ts
276
- import { terminal } from "@aomex/console";
277
-
278
- // src/i18n/index.ts
279
- import { I18n as I18n3 } from "@aomex/common";
280
-
281
326
  // src/i18n/locales/zh-cn.ts
282
- import { I18n } from "@aomex/common";
283
- var zh = I18n.define({
284
- initialize: "\u521D\u59CB\u5316\u6587\u6863",
285
- search_routers_files: "\u641C\u7D22\u8DEF\u7531\u6587\u4EF6",
286
- parse_routers: "\u89E3\u6790\u8DEF\u7531",
287
- add_tag: "\u589E\u52A0\u6807\u7B7E",
288
- hand_fix_documentation: "\u624B\u52A8\u4FEE\u590D\u6587\u6863",
289
- optimize_parameter: "\u4F18\u5316\u53C2\u6570",
290
- save_to_file: "\u4FDD\u5B58\u5230\u6587\u4EF6",
291
- validate: "\u9A8C\u8BC1\u6587\u6863",
292
- help_summary: "openapi v3 \u6587\u6863\u751F\u6210\u5668",
293
- has_error: "{{error_count}}\u6761\u62A5\u9519\uFF0C{{warning_count}}\u6761\u8B66\u544A",
294
- no_error: "\u6CA1\u6709\u62A5\u9519"
327
+ const zh = I18n.define({
328
+ initialize: "初始化文档",
329
+ search_routers_files: "搜索路由文件",
330
+ parse_routers: "解析路由",
331
+ add_tag: "添加标签",
332
+ hand_fix_documentation: "手动修复文档",
333
+ optimize_parameter: "优化参数",
334
+ save_to_file: "保存到文件",
335
+ validate: "验证文档",
336
+ help_summary: "OpenAPI v3 文档生成器",
337
+ help_app_listen_tip: "请将 new WebApp 与 app.listen 拆开(或仅在入口 listen),避免 CLI import 时副作用起服",
338
+ has_error: "{{error_count}} 个错误,{{warning_count}} 条警告",
339
+ no_error: "没有错误"
295
340
  });
296
-
297
341
  // src/i18n/locales/en-us.ts
298
- import { I18n as I18n2 } from "@aomex/common";
299
- var en = I18n2.satisfies(zh).define({
300
- initialize: "initialize document",
301
- search_routers_files: "search web routers files",
302
- parse_routers: "parse routers",
303
- add_tag: "append tags",
304
- hand_fix_documentation: "fix documentation by manual",
305
- optimize_parameter: "optimize parameters",
306
- save_to_file: "save to file",
307
- validate: "validate document",
308
- help_summary: "openapi v3 documentation generator",
309
- has_error: "{{error_count}} errors, {{warning_count}} warnings",
310
- no_error: "No errors"
342
+ const en = I18n.satisfies(zh).define({
343
+ initialize: "initialize document",
344
+ search_routers_files: "search web routers files",
345
+ parse_routers: "parse routers",
346
+ add_tag: "Add tags",
347
+ hand_fix_documentation: "fix documentation by manual",
348
+ optimize_parameter: "optimize parameters",
349
+ save_to_file: "save to file",
350
+ validate: "validate document",
351
+ help_summary: "OpenAPI v3 documentation generator",
352
+ help_app_listen_tip: "Keep new WebApp separate from app.listen (or listen only in the entry file) so CLI imports do not start the server as a side effect",
353
+ has_error: "{{error_count}} errors, {{warning_count}} warnings",
354
+ no_error: "No errors"
311
355
  });
312
-
313
- // src/i18n/locales/index.ts
314
- var locales = {
315
- zh_CN: zh,
316
- en_US: en
317
- };
318
-
319
356
  // src/i18n/index.ts
320
- var i18n = new I18n3({
321
- resources: locales,
322
- defaultLanguage: "zh_CN"
357
+ const i18n = createI18n({
358
+ zh,
359
+ en,
360
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
323
361
  });
324
-
325
362
  // src/lib/generate-document-with-spinner.ts
326
- var generateOpenapiWithSpinner = async (config) => {
327
- const { error, context } = await terminal.runTasks([
328
- {
329
- title: i18n.t("initialize"),
330
- task: async (ctx) => {
331
- ctx.document = await initializeDocument(config.docs);
332
- }
333
- },
334
- {
335
- title: i18n.t("search_routers_files"),
336
- task: async (ctx) => {
337
- ctx.files = await pathToFiles(config.routers);
338
- await esm_default(500);
339
- }
340
- },
341
- {
342
- title: i18n.t("parse_routers"),
343
- task: async (ctx) => {
344
- ctx.usedTags = await parseFiles(ctx.document, ctx.files);
345
- await esm_default(500);
346
- }
347
- },
348
- {
349
- title: i18n.t("add_tag"),
350
- task: async (ctx, task) => {
351
- const undefinedTags = appendTag(ctx.document, ctx.usedTags);
352
- if (undefinedTags.length) {
353
- task.suffix = terminal.style("gray", undefinedTags.join(","));
354
- } else {
355
- task.status = "skip";
356
- }
357
- }
358
- },
359
- {
360
- title: i18n.t("hand_fix_documentation"),
361
- skip: !config.fix,
362
- task: async (ctx) => {
363
- await config.fix(ctx.document);
364
- await esm_default(500);
365
- }
366
- },
367
- {
368
- title: i18n.t("optimize_parameter"),
369
- task: async (ctx) => {
370
- methodParameterToPathParameter(ctx.document);
371
- await esm_default(500);
372
- }
373
- },
374
- {
375
- title: i18n.t("save_to_file"),
376
- task: async (ctx, task) => {
377
- const result = await saveToFile(ctx.document, config.saveToFile, config.fileMode);
378
- task.suffix = terminal.style(
379
- ["blue", "underline"],
380
- path4.relative(process.cwd(), result.dest)
381
- ) + terminal.style("green", ` [${result.size}]`);
382
- }
383
- },
384
- {
385
- title: i18n.t("validate"),
386
- task: async (ctx, task) => {
387
- const result = ctx.validateResult = await validateOpenapi(ctx.document);
388
- await esm_default(500);
389
- if (result.errors.length || result.warnings.length) {
390
- task.suffix = terminal.style(
391
- "yellow",
392
- i18n.t("has_error", {
393
- error_count: result.errors.length,
394
- warning_count: result.warnings.length
395
- })
396
- );
397
- } else {
398
- task.suffix = terminal.style("green", i18n.t("no_error"));
399
- }
400
- }
401
- }
402
- ]);
403
- if (error) return null;
404
- const logSession = terminal.createSession();
405
- const { errors, warnings } = context.validateResult;
406
- for (const error2 of errors) {
407
- logSession.update(` %error% ${formatValidateMessage(error2)}`);
408
- logSession.commit();
409
- }
410
- for (const warning of warnings) {
411
- logSession.update(` %warning% ${formatValidateMessage(warning)}`);
412
- logSession.commit();
413
- }
414
- return JSON.parse(JSON.stringify(context.document));
363
+ /**
364
+ * 1. 生成openapi文档
365
+ * 2. 保存文档到文件
366
+ * 3. 验证
367
+ * 4. 控制台输出执行步骤和验证结果
368
+ *
369
+ * 如果是主动调用,则应使用 generateOpenapi()
370
+ * @see generateOpenapi
371
+ */
372
+ const generateOpenapiWithSpinner = async (config) => {
373
+ const { error, context } = await terminal.runTasks([
374
+ {
375
+ title: i18n.t("initialize"),
376
+ task: async (ctx) => {
377
+ ctx.document = await initializeDocument(config.docs);
378
+ }
379
+ },
380
+ {
381
+ title: i18n.t("search_routers_files"),
382
+ task: async (ctx) => {
383
+ ctx.files = await pathToFiles(config.routers);
384
+ await (0, import_cjs.default)(500);
385
+ }
386
+ },
387
+ {
388
+ title: i18n.t("parse_routers"),
389
+ task: async (ctx) => {
390
+ const app = config.app;
391
+ ctx.usedTags = await parseFiles(ctx.document, ctx.files, {
392
+ mount: app?.["middlewareList"],
393
+ envelope: app?.["options"].envelope
394
+ });
395
+ await (0, import_cjs.default)(500);
396
+ }
397
+ },
398
+ {
399
+ title: i18n.t("add_tag"),
400
+ task: async (ctx, task) => {
401
+ const undefinedTags = appendTag(ctx.document, ctx.usedTags);
402
+ if (undefinedTags.length) task.suffix = terminal.style("gray", undefinedTags.join(","));
403
+ else task.status = "skip";
404
+ }
405
+ },
406
+ {
407
+ title: i18n.t("hand_fix_documentation"),
408
+ skip: !config.fix,
409
+ task: async (ctx) => {
410
+ await config.fix(ctx.document);
411
+ await (0, import_cjs.default)(500);
412
+ }
413
+ },
414
+ {
415
+ title: i18n.t("optimize_parameter"),
416
+ task: async (ctx) => {
417
+ hoistSchemaRef(ctx.document);
418
+ methodParameterToPathParameter(ctx.document);
419
+ await (0, import_cjs.default)(500);
420
+ }
421
+ },
422
+ {
423
+ title: i18n.t("save_to_file"),
424
+ task: async (ctx, task) => {
425
+ const result = await saveToFile(ctx.document, config.saveToFile, config.fileMode);
426
+ task.suffix = terminal.style(["blue", "underline"], path.relative(process.cwd(), result.dest)) + terminal.style("green", ` [${result.size}]`);
427
+ }
428
+ },
429
+ {
430
+ title: i18n.t("validate"),
431
+ task: async (ctx, task) => {
432
+ const result = ctx.validateResult = await validateOpenapi(ctx.document);
433
+ await (0, import_cjs.default)(500);
434
+ if (result.errors.length || result.warnings.length) task.suffix = terminal.style("yellow", i18n.t("has_error", {
435
+ error_count: result.errors.length,
436
+ warning_count: result.warnings.length
437
+ }));
438
+ else task.suffix = terminal.style("green", i18n.t("no_error"));
439
+ }
440
+ }
441
+ ]);
442
+ if (error) return null;
443
+ const logSession = terminal.createSession();
444
+ const { errors, warnings } = context.validateResult;
445
+ for (const error of errors) {
446
+ logSession.update(` %error% ${formatValidateMessage(error)}`);
447
+ logSession.commit();
448
+ }
449
+ for (const warning of warnings) {
450
+ logSession.update(` %warning% ${formatValidateMessage(warning)}`);
451
+ logSession.commit();
452
+ }
453
+ return JSON.parse(JSON.stringify(context.document));
415
454
  };
416
- var formatValidateMessage = (item) => {
417
- let pathname = item.path.length ? item.path.join(".") : "";
418
- return `${terminal.style("gray", `[${pathname || "."}]`)} ${item.message}`;
455
+ const formatValidateMessage = (item) => {
456
+ let pathname = item.path.length ? item.path.join(".") : "";
457
+ return `${terminal.style("gray", `[${pathname || "."}]`)} ${item.message}`;
419
458
  };
420
-
421
459
  // src/openapi.ts
422
- var openapi = (options) => {
423
- const { commandName = "openapi" } = options;
424
- return middleware.console({
425
- fn: async (ctx, next) => {
426
- if (ctx.input.command !== commandName) return next();
427
- ctx.commandMatched = true;
428
- await generateOpenapiWithSpinner(options);
429
- },
430
- help: {
431
- onDocument(doc) {
432
- doc[commandName] = { summary: i18n.t("help_summary") };
433
- }
434
- }
435
- });
460
+ /**
461
+ * Console 中间件:生成 OpenAPI 文档。
462
+ *
463
+ * 请把 `new WebApp(...)` 与 `app.listen(...)` 拆开(或仅在入口 listen),
464
+ * 否则 CLI `import` 同一模块会副作用起服、抢端口。
465
+ *
466
+ * ```ts
467
+ * // app.ts
468
+ * export const app = new WebApp({ envelope: { ... }, mount: [...] });
469
+ *
470
+ * // main.ts
471
+ * import { app } from './app.js';
472
+ * app.listen(3000);
473
+ *
474
+ * // console mount
475
+ * openapi({
476
+ * commandName: 'openapi',
477
+ * routers: './src/routers',
478
+ * app, // 与运行时同一实例
479
+ * });
480
+ * ```
481
+ */
482
+ const openapi = (options) => {
483
+ const { commandName = "openapi" } = options;
484
+ return middleware.console({
485
+ fn: async (ctx, next) => {
486
+ if (ctx.input.command !== commandName) return next();
487
+ ctx.commandMatched = true;
488
+ await generateOpenapiWithSpinner(options);
489
+ },
490
+ help: { onDocument(doc) {
491
+ doc[commandName] = {
492
+ summary: i18n.t("help_summary"),
493
+ description: i18n.t("help_app_listen_tip")
494
+ };
495
+ } }
496
+ });
436
497
  };
437
-
438
498
  // src/lib/generate-openapi.ts
439
- import "@aomex/common";
440
- import { pathToFiles as pathToFiles2 } from "@aomex/internal-file-import";
441
- var generateOpenapi = async (config) => {
442
- const document = await initializeDocument(config.docs);
443
- const files = await pathToFiles2(config.routers);
444
- const usedTags = await parseFiles(document, files);
445
- appendTag(document, usedTags);
446
- await config.fix?.(document);
447
- methodParameterToPathParameter(document);
448
- return JSON.parse(JSON.stringify(document));
449
- };
450
- export {
451
- generateOpenapi,
452
- generateOpenapiWithSpinner,
453
- initializeDocument,
454
- methodParameterToPathParameter,
455
- methodToVerb,
456
- methods,
457
- openapi,
458
- parseFiles,
459
- saveToFile,
460
- validateOpenapi
499
+ /**
500
+ * 生成openapi文档
501
+ */
502
+ const generateOpenapi = async (config) => {
503
+ const document = await initializeDocument(config.docs);
504
+ const files = await pathToFiles(config.routers);
505
+ const app = config.app;
506
+ const usedTags = await parseFiles(document, files, {
507
+ mount: app["middlewareList"],
508
+ envelope: app["options"].envelope
509
+ });
510
+ appendTag(document, usedTags);
511
+ await config.fix?.(document);
512
+ hoistSchemaRef(document);
513
+ methodParameterToPathParameter(document);
514
+ return JSON.parse(JSON.stringify(document));
461
515
  };
516
+ export { generateOpenapi, generateOpenapiWithSpinner, hoistSchemaRef, initializeDocument, methodParameterToPathParameter, methodToVerb, methods, openapi, parseFiles, saveToFile, validateOpenapi };
517
+
462
518
  //# sourceMappingURL=index.js.map