dsh-postapi 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +139 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dist/client.js +5651 -0
  5. package/docs/DETAIL.md +27 -0
  6. package/docs/apifox-design-spec.md +101 -0
  7. package/docs/apifox-research/analysis.md +254 -0
  8. package/docs/apifox-ui-delivery.md +150 -0
  9. package/docs/apifox-visual-parity-spec.md +353 -0
  10. package/docs/feature-matrix.md +112 -0
  11. package/docs/flow-reference/sequence-reference.html +163 -0
  12. package/docs/interface-contract-v2.md +175 -0
  13. package/docs/interface-contract.md +105 -0
  14. package/docs/nav-layout-v2-spec.md +107 -0
  15. package/docs/preview.svg +9 -0
  16. package/docs/probe-client.legacy.js +31 -0
  17. package/docs/rootcause-sidebar-vanish.md +95 -0
  18. package/docs/rootcause.md +86 -0
  19. package/docs/sidebar-notes.md +153 -0
  20. package/docs/ui-audit.md +197 -0
  21. package/docs/ui-notes.md +98 -0
  22. package/docs/v2-delivery.md +99 -0
  23. package/icon.svg +4 -0
  24. package/index.js +5 -0
  25. package/locale/en.json +7 -0
  26. package/locale/zh.json +7 -0
  27. package/package.json +73 -4
  28. package/src/client/index.js +132 -0
  29. package/src/client/jsx-shim.js +9 -0
  30. package/src/client/pages/__tests__/heights.test.js +135 -0
  31. package/src/client/pages/components/AssertTable.jsx +122 -0
  32. package/src/client/pages/components/BodyEditor.jsx +91 -0
  33. package/src/client/pages/components/EmptyState.jsx +52 -0
  34. package/src/client/pages/components/FolderTree.jsx +109 -0
  35. package/src/client/pages/components/JsonEditor.jsx +45 -0
  36. package/src/client/pages/components/ParamTable.jsx +226 -0
  37. package/src/client/pages/components/ResponsePanel.jsx +278 -0
  38. package/src/client/pages/components/ScriptPanel.jsx +99 -0
  39. package/src/client/pages/components/StatusPill.jsx +35 -0
  40. package/src/client/pages/components/__tests__/apifox-ui.test.js +291 -0
  41. package/src/client/pages/components/__tests__/pages-a.test.js +392 -0
  42. package/src/client/pages/components/__tests__/tree.test.js +379 -0
  43. package/src/client/pages/components/headerPresets.js +63 -0
  44. package/src/client/pages/debug.jsx +576 -0
  45. package/src/client/pages/design-tokens.css +2604 -0
  46. package/src/client/pages/doc.jsx +552 -0
  47. package/src/client/pages/env.jsx +378 -0
  48. package/src/client/pages/flow.jsx +349 -0
  49. package/src/client/pages/history.jsx +238 -0
  50. package/src/client/pages/import.jsx +396 -0
  51. package/src/client/pages/mock.jsx +316 -0
  52. package/src/client/pages/overview.jsx +348 -0
  53. package/src/client/pages/schema.jsx +317 -0
  54. package/src/client/pages/search.jsx +216 -0
  55. package/src/client/pages/sequence.jsx +344 -0
  56. package/src/client/pages/settings.jsx +205 -0
  57. package/src/client/pages/test.jsx +470 -0
  58. package/src/client/pages/theme.js +27 -0
  59. package/src/client/pages-entry.js +20 -0
  60. package/src/client/shell/ApiTitle.js +19 -0
  61. package/src/client/shell/Body.js +492 -0
  62. package/src/client/shell/definition.js +57 -0
  63. package/src/client/shell/locales.js +185 -0
  64. package/src/client/shell/menu.js +174 -0
  65. package/src/client/shell/registry.js +530 -0
  66. package/src/host/bridge.js +407 -0
  67. package/src/host/codegen.js +356 -0
  68. package/src/host/import-export.js +1044 -0
  69. package/src/host/index.js +102 -0
  70. package/src/host/mock-server.js +303 -0
  71. package/src/host/request.js +336 -0
  72. package/src/host/script-sandbox.js +272 -0
  73. package/src/host/storage.js +803 -0
  74. package/src/host/test-runner.js +126 -0
  75. package/src/host/variables.js +108 -0
@@ -0,0 +1,1044 @@
1
+ /**
2
+ * 导入导出(契约 §3 / feature-matrix 14、15):全部纯函数,不落盘、不依赖 storage。
3
+ * 导入返回 { folders, endpoints, schemas } 骨架(id 稳定且可预测,便于重复导入幂等);
4
+ * 导出返回可 JSON.stringify 的对象或 Markdown 字符串。
5
+ */
6
+
7
+ /** 导入产物里的稳定 id:前缀 + 三位序号(重复导入同一文档得到同一批 id)。 */
8
+ function seqId(prefix, i) {
9
+ return prefix + String(i + 1).padStart(3, '0')
10
+ }
11
+
12
+ function str(v) {
13
+ return typeof v === 'string' ? v : v == null ? '' : String(v)
14
+ }
15
+
16
+ function asArray(v) {
17
+ return Array.isArray(v) ? v : []
18
+ }
19
+
20
+ /** baseUrl 与 path 拼接:单斜杠归一,baseUrl 为空则原样返回 path。 */
21
+ export function joinUrl(base, p) {
22
+ const b = str(base).replace(/\/+$/, '')
23
+ const path = str(p)
24
+ if (b === '') return path
25
+ return b + (path.startsWith('/') ? path : '/' + path)
26
+ }
27
+
28
+ const EMPTY_ENDPOINT = {
29
+ folderId: null,
30
+ order: 0,
31
+ protocol: 'http',
32
+ method: 'GET',
33
+ url: '',
34
+ params: [],
35
+ pathParams: [],
36
+ headers: [],
37
+ cookies: [],
38
+ body: { type: 'none', content: '', schema: null, examples: [] },
39
+ auth: { type: 'none', token: '', username: '', password: '', key: '', value: '', addTo: 'header' },
40
+ responses: [],
41
+ preProcessors: [],
42
+ postProcessors: [],
43
+ mock: { enabled: false, delayMs: 0, rules: [] },
44
+ description: '',
45
+ tags: [],
46
+ status: 'developing',
47
+ }
48
+
49
+ /** 导入骨架统一出口:补全 endpoint 默认字段,避免下游页面拿不到结构。 */
50
+ function makeEndpoint(patch) {
51
+ const p = patch || {}
52
+ return {
53
+ ...EMPTY_ENDPOINT,
54
+ ...p,
55
+ body: { ...EMPTY_ENDPOINT.body, ...(p.body || {}) },
56
+ auth: { ...EMPTY_ENDPOINT.auth, ...(p.auth || {}) },
57
+ mock: { ...EMPTY_ENDPOINT.mock, ...(p.mock || {}) },
58
+ }
59
+ }
60
+
61
+ /** 参数行统一形态(契约 §2.2 params/pathParams/headers/cookies 同构)。 */
62
+ function makeParam(key, value, extra) {
63
+ const e = extra || {}
64
+ return {
65
+ key: str(key),
66
+ value: str(value),
67
+ enabled: e.enabled === undefined ? true : !!e.enabled,
68
+ description: str(e.description),
69
+ required: !!e.required,
70
+ type: str(e.type) || 'string',
71
+ }
72
+ }
73
+
74
+ function looksJson(text) {
75
+ const t = str(text).trim()
76
+ if (t === '') return false
77
+ try {
78
+ JSON.parse(t)
79
+ return true
80
+ } catch {
81
+ return false
82
+ }
83
+ }
84
+
85
+ /* ── 导入:OpenAPI 3 / Swagger 2 ───────────────────────────────────────── */
86
+
87
+ const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace']
88
+
89
+ function schemaToBodyType(contentType) {
90
+ const ct = str(contentType).toLowerCase()
91
+ if (ct.includes('json')) return 'json'
92
+ if (ct.includes('x-www-form-urlencoded')) return 'urlencoded'
93
+ if (ct.includes('multipart/form-data')) return 'form'
94
+ if (ct.includes('xml')) return 'xml'
95
+ if (ct.includes('graphql')) return 'graphql'
96
+ if (ct === '') return 'none'
97
+ return 'raw'
98
+ }
99
+
100
+ function exampleOf(media) {
101
+ const m = media || {}
102
+ if (m.example !== undefined) return m.example
103
+ const ex = m.examples && typeof m.examples === 'object' ? Object.values(m.examples)[0] : undefined
104
+ if (ex && typeof ex === 'object' && ex.value !== undefined) return ex.value
105
+ return undefined
106
+ }
107
+
108
+ /** 从 parameters 拆出 pathParams/params/headers/cookies。 */
109
+ function splitParameters(parameters) {
110
+ const out = { pathParams: [], params: [], headers: [], cookies: [] }
111
+ for (const raw of asArray(parameters)) {
112
+ const p = raw && typeof raw === 'object' ? raw : {}
113
+ const name = p.name
114
+ if (!name) continue
115
+ const schema = p.schema && typeof p.schema === 'object' ? p.schema : {}
116
+ const value = p.example !== undefined
117
+ ? p.example
118
+ : (schema.example !== undefined ? schema.example : (schema.default !== undefined ? schema.default : ''))
119
+ const row = makeParam(name, value, {
120
+ description: p.description,
121
+ required: p.required,
122
+ type: schema.type,
123
+ })
124
+ const where = str(p.in)
125
+ if (where === 'path') out.pathParams.push(row)
126
+ else if (where === 'header') out.headers.push(row)
127
+ else if (where === 'cookie') out.cookies.push(row)
128
+ else out.params.push(row)
129
+ }
130
+ return out
131
+ }
132
+
133
+ function buildRequestBody(requestBody) {
134
+ const rb = requestBody && typeof requestBody === 'object' ? requestBody : null
135
+ if (!rb || !rb.content || typeof rb.content !== 'object') {
136
+ return { type: 'none', content: '', schema: null, examples: [] }
137
+ }
138
+ const entries = Object.entries(rb.content)
139
+ if (entries.length === 0) return { type: 'none', content: '', schema: null, examples: [] }
140
+ const [contentType, media] = entries[0]
141
+ const type = schemaToBodyType(contentType)
142
+ const example = exampleOf(media)
143
+ const schema = media && media.schema ? media.schema : null
144
+ const content = example !== undefined
145
+ ? (typeof example === 'string' ? example : JSON.stringify(example, null, 2))
146
+ : (schema ? JSON.stringify(schema, null, 2) : '')
147
+ return { type, content, schema, examples: [] }
148
+ }
149
+
150
+ function buildResponses(responses) {
151
+ const out = []
152
+ if (!responses || typeof responses !== 'object') return out
153
+ let i = 0
154
+ for (const [code, raw] of Object.entries(responses)) {
155
+ const r = raw && typeof raw === 'object' ? raw : {}
156
+ const contentObj = r.content && typeof r.content === 'object' ? r.content : null
157
+ const first = contentObj ? Object.entries(contentObj)[0] : null
158
+ const contentType = first ? first[0] : 'application/json'
159
+ const media = first ? (first[1] || {}) : {}
160
+ const example = exampleOf(media)
161
+ out.push({
162
+ id: seqId('res_', i),
163
+ name: str(r.description) || ('响应 ' + code),
164
+ code: Number.isNaN(Number(code)) ? 200 : Number(code),
165
+ contentType,
166
+ body: example !== undefined
167
+ ? (typeof example === 'string' ? example : JSON.stringify(example, null, 2))
168
+ : (media.schema ? JSON.stringify(media.schema, null, 2) : ''),
169
+ schema: media.schema || null,
170
+ headers: [],
171
+ enabled: true,
172
+ isDefault: i === 0,
173
+ })
174
+ i += 1
175
+ }
176
+ return out
177
+ }
178
+
179
+ /**
180
+ * OpenAPI 3.x / Swagger 2.0 → { folders, endpoints, schemas }。
181
+ * tags 生成目录(folderId 指向),components.schemas(或 definitions)生成数据模型。
182
+ */
183
+ export function importOpenApi(json) {
184
+ const doc = json && typeof json === 'object' ? json : {}
185
+ const isV3 = doc.openapi !== undefined
186
+ const servers = isV3
187
+ ? asArray(doc.servers)
188
+ : (doc.host
189
+ ? [{ url: (asArray(doc.schemes)[0] ? str(doc.schemes[0]) + '://' : 'https://') + str(doc.host) + str(doc.basePath) }]
190
+ : [])
191
+ const baseUrl = servers.length > 0 && servers[0] && typeof servers[0] === 'object'
192
+ ? str(servers[0].url)
193
+ : ''
194
+
195
+ // tags → 目录(同名 tag 复用一个目录)
196
+ const folders = []
197
+ const folderIdByTag = new Map()
198
+ for (const t of asArray(doc.tags)) {
199
+ const name = t && typeof t === 'object' ? str(t.name) : str(t)
200
+ if (name === '' || folderIdByTag.has(name)) continue
201
+ const id = seqId('fld_', folders.length)
202
+ folders.push({ id, name, parentId: null, order: folders.length })
203
+ folderIdByTag.set(name, id)
204
+ }
205
+
206
+ const endpoints = []
207
+ const paths = doc.paths && typeof doc.paths === 'object' ? doc.paths : {}
208
+ for (const [rawPath, pathItem] of Object.entries(paths)) {
209
+ const item = pathItem && typeof pathItem === 'object' ? pathItem : {}
210
+ for (const method of HTTP_METHODS) {
211
+ const op = item[method]
212
+ if (!op || typeof op !== 'object') continue
213
+ const groups = splitParameters([...asArray(item.parameters), ...asArray(op.parameters)])
214
+ const tags = asArray(op.tags).map(str).filter(Boolean)
215
+ const folderTag = tags.find((t) => folderIdByTag.has(t))
216
+ endpoints.push(makeEndpoint({
217
+ id: seqId('ep_', endpoints.length),
218
+ name: str(op.summary) || str(op.operationId) || (method.toUpperCase() + ' ' + rawPath),
219
+ folderId: folderTag ? folderIdByTag.get(folderTag) : null,
220
+ order: endpoints.length,
221
+ method: method.toUpperCase(),
222
+ url: joinUrl(baseUrl, rawPath),
223
+ params: groups.params,
224
+ pathParams: groups.pathParams,
225
+ headers: groups.headers,
226
+ cookies: groups.cookies,
227
+ body: buildRequestBody(op.requestBody),
228
+ responses: buildResponses(op.responses),
229
+ description: str(op.description) || str(op.summary),
230
+ tags,
231
+ }))
232
+ }
233
+ }
234
+
235
+ const schemaSource = isV3
236
+ ? ((doc.components && doc.components.schemas) || {})
237
+ : (doc.definitions || {})
238
+ const schemas = Object.entries(schemaSource).map(([name, jsonSchema], i) => ({
239
+ id: seqId('sch_', i),
240
+ name,
241
+ folderId: null,
242
+ jsonSchema: jsonSchema && typeof jsonSchema === 'object' ? jsonSchema : {},
243
+ description: str(jsonSchema && jsonSchema.description),
244
+ }))
245
+
246
+ return { folders, endpoints, schemas }
247
+ }
248
+
249
+ /* ── 导入:Postman collection v2.1 ─────────────────────────────────────── */
250
+
251
+ function postmanUrlParts(url) {
252
+ if (typeof url === 'string') return { raw: url, query: [] }
253
+ const u = url && typeof url === 'object' ? url : {}
254
+ const host = Array.isArray(u.host) ? u.host.join('.') : str(u.host)
255
+ const pathPart = Array.isArray(u.path)
256
+ ? '/' + u.path.map((p) => (p && typeof p === 'object' ? str(p.value) : str(p))).join('/')
257
+ : ''
258
+ const raw = str(u.raw) || ((u.protocol ? str(u.protocol) + '://' : '') + host + pathPart)
259
+ return { raw, query: asArray(u.query) }
260
+ }
261
+
262
+ function postmanBody(body) {
263
+ const b = body && typeof body === 'object' ? body : null
264
+ if (!b) return { type: 'none', content: '', schema: null, examples: [] }
265
+ const mode = str(b.mode)
266
+ if (mode === 'raw') {
267
+ const lang = b.options && b.options.raw && b.options.raw.language ? str(b.options.raw.language) : ''
268
+ let type = 'raw'
269
+ if (lang === 'json' || (lang === '' && looksJson(b.raw))) type = 'json'
270
+ else if (lang === 'xml') type = 'xml'
271
+ return { type, content: str(b.raw), schema: null, examples: [] }
272
+ }
273
+ if (mode === 'urlencoded') {
274
+ return {
275
+ type: 'urlencoded',
276
+ content: JSON.stringify(asArray(b.urlencoded).map((r) => ({ key: str(r && r.key), value: str(r && r.value) }))),
277
+ schema: null,
278
+ examples: [],
279
+ }
280
+ }
281
+ if (mode === 'formdata') {
282
+ return {
283
+ type: 'form',
284
+ content: JSON.stringify(asArray(b.formdata).map((r) => ({ key: str(r && r.key), value: str(r && r.value) }))),
285
+ schema: null,
286
+ examples: [],
287
+ }
288
+ }
289
+ if (mode === 'file') return { type: 'binary', content: '', schema: null, examples: [] }
290
+ if (mode === 'graphql') {
291
+ return {
292
+ type: 'graphql',
293
+ content: JSON.stringify({ query: str(b.graphql && b.graphql.query), variables: str(b.graphql && b.graphql.variables) }),
294
+ schema: null,
295
+ examples: [],
296
+ }
297
+ }
298
+ return { type: 'none', content: '', schema: null, examples: [] }
299
+ }
300
+
301
+ function postmanAuth(auth) {
302
+ const a = auth && typeof auth === 'object' ? auth : null
303
+ if (!a || !a.type) return { ...EMPTY_ENDPOINT.auth }
304
+ const pick = (key) => {
305
+ const row = asArray(a[a.type]).find((r) => r && r.key === key)
306
+ return row ? str(row.value) : ''
307
+ }
308
+ const type = str(a.type)
309
+ if (type === 'bearer') return { ...EMPTY_ENDPOINT.auth, type: 'bearer', token: pick('token') }
310
+ if (type === 'basic') return { ...EMPTY_ENDPOINT.auth, type: 'basic', username: pick('username'), password: pick('password') }
311
+ if (type === 'apikey') {
312
+ return { ...EMPTY_ENDPOINT.auth, type: 'apikey', key: pick('key'), value: pick('value'), addTo: pick('in') === 'query' ? 'query' : 'header' }
313
+ }
314
+ if (type === 'oauth2') return { ...EMPTY_ENDPOINT.auth, type: 'oauth2', token: pick('accessToken') }
315
+ return { ...EMPTY_ENDPOINT.auth }
316
+ }
317
+
318
+ /**
319
+ * Postman v2.1 → { folders, endpoints, schemas: [] }。
320
+ * 标准层级:collection 名 → 根目录(parentId null),item 树递归挂在它下面;
321
+ * item 含 request 的当接口,含 item 的当目录。order 是同级内序号(不是全局序号),
322
+ * folders 数组保持先序(父目录必在子目录之前),便于按序落盘。
323
+ */
324
+ export function importPostman(json) {
325
+ const collection = json && typeof json === 'object'
326
+ ? (json.collection && typeof json.collection === 'object' ? json.collection : json)
327
+ : {}
328
+ const folders = []
329
+ const endpoints = []
330
+ // 空集合(无 item 且无 info.name)不造根目录,保持「无内容 → 空结构」的边界语义
331
+ const rootName = str(collection.info && collection.info.name)
332
+ if (rootName === '' && asArray(collection.item).length === 0) {
333
+ return { folders: [], endpoints: [], schemas: [] }
334
+ }
335
+ // 根目录:collection.info.name(缺失时给中性名),让导入结果始终有唯一的项目级分组
336
+ const rootId = seqId('fld_', 0)
337
+ folders.push({ id: rootId, name: rootName || '导入的 Collection', parentId: null, order: 0 })
338
+
339
+ /** 同级序号:按父目录分别计数,子目录与接口各自独立递增。 */
340
+ const walk = (items, parentId) => {
341
+ let folderOrder = 0
342
+ let endpointOrder = 0
343
+ for (const raw of asArray(items)) {
344
+ const item = raw && typeof raw === 'object' ? raw : {}
345
+ const name = str(item.name)
346
+ if (item.request && typeof item.request === 'object') {
347
+ const req = item.request
348
+ const parts = postmanUrlParts(req.url)
349
+ const headers = asArray(req.header).map((h) => makeParam(h && h.key, h && h.value, {
350
+ enabled: !(h && h.disabled),
351
+ description: h && h.description,
352
+ }))
353
+ const params = parts.query.map((q) => makeParam(q && q.key, q && q.value, {
354
+ enabled: !(q && q.disabled),
355
+ description: q && q.description,
356
+ }))
357
+ const responses = asArray(item.response).map((r, i) => ({
358
+ id: seqId('res_', i),
359
+ name: str(r && r.name) || ('响应 ' + str(r && r.code)),
360
+ code: Number(str(r && r.code)) || 200,
361
+ contentType: (() => {
362
+ const h = asArray(r && r.header).find((x) => str(x && x.key).toLowerCase() === 'content-type')
363
+ return h ? str(h.value) : 'application/json'
364
+ })(),
365
+ body: str(r && r.body),
366
+ schema: null,
367
+ headers: asArray(r && r.header).map((h) => makeParam(h && h.key, h && h.value)),
368
+ enabled: true,
369
+ isDefault: i === 0,
370
+ }))
371
+ endpoints.push(makeEndpoint({
372
+ id: seqId('ep_', endpoints.length),
373
+ name: name || ((str(req.method) || 'GET').toUpperCase() + ' ' + parts.raw),
374
+ folderId: parentId,
375
+ order: endpointOrder++,
376
+ method: (str(req.method) || 'GET').toUpperCase(),
377
+ url: parts.raw,
378
+ params,
379
+ headers,
380
+ body: postmanBody(req.body),
381
+ auth: postmanAuth(req.auth),
382
+ description: str(req.description),
383
+ responses,
384
+ }))
385
+ continue
386
+ }
387
+ if (Array.isArray(item.item)) {
388
+ const id = seqId('fld_', folders.length)
389
+ folders.push({ id, name, parentId, order: folderOrder++ })
390
+ walk(item.item, id)
391
+ }
392
+ }
393
+ }
394
+
395
+ walk(collection.item, rootId)
396
+ return { folders, endpoints, schemas: [] }
397
+ }
398
+
399
+ /* ── 导入:HAR ─────────────────────────────────────────────────────────── */
400
+
401
+ /** HAR log.entries → { folders: [], endpoints, schemas: [] }(每条 entry 一个接口,method+path 去重)。 */
402
+ export function importHar(json) {
403
+ const doc = json && typeof json === 'object' ? json : {}
404
+ const entries = asArray(doc.log && doc.log.entries)
405
+ const endpoints = []
406
+ const seen = new Set()
407
+ for (const raw of entries) {
408
+ const entry = raw && typeof raw === 'object' ? raw : {}
409
+ const req = entry.request && typeof entry.request === 'object' ? entry.request : {}
410
+ const res = entry.response && typeof entry.response === 'object' ? entry.response : {}
411
+ const url = str(req.url)
412
+ if (url === '') continue
413
+ let pathname = url
414
+ try {
415
+ pathname = new URL(url).pathname
416
+ } catch {
417
+ // 非绝对 URL 时保留原串
418
+ }
419
+ const method = (str(req.method) || 'GET').toUpperCase()
420
+ const key = method + ' ' + pathname
421
+ if (seen.has(key)) continue
422
+ seen.add(key)
423
+ const content = res.content && typeof res.content === 'object' ? res.content : {}
424
+ const postData = req.postData && typeof req.postData === 'object' ? req.postData : null
425
+ endpoints.push(makeEndpoint({
426
+ id: seqId('ep_', endpoints.length),
427
+ name: method + ' ' + pathname,
428
+ order: endpoints.length,
429
+ method,
430
+ url,
431
+ params: asArray(req.queryString).map((q) => makeParam(q && q.name, q && q.value)),
432
+ headers: asArray(req.headers)
433
+ .filter((h) => h && !str(h.name).startsWith(':'))
434
+ .map((h) => makeParam(h && h.name, h && h.value)),
435
+ body: postData
436
+ ? { type: looksJson(postData.text) ? 'json' : 'raw', content: str(postData.text), schema: null, examples: [] }
437
+ : { type: 'none', content: '', schema: null, examples: [] },
438
+ description: str(res.statusText),
439
+ responses: [{
440
+ id: seqId('res_', 0),
441
+ name: 'HAR 记录响应',
442
+ code: Number(res.status) || 200,
443
+ contentType: str(content.mimeType) || 'application/json',
444
+ body: str(content.text),
445
+ schema: null,
446
+ headers: asArray(res.headers).map((h) => makeParam(h && h.name, h && h.value)),
447
+ enabled: true,
448
+ isDefault: true,
449
+ }],
450
+ }))
451
+ }
452
+ return { folders: [], endpoints, schemas: [] }
453
+ }
454
+
455
+ /* ── 导入:cURL ────────────────────────────────────────────────────────── */
456
+
457
+ /** 按 shell 规则切分参数(支持单/双引号与反斜杠续行)。 */
458
+ function splitCurlArgs(text) {
459
+ const s = str(text).replace(/\\\r?\n/g, ' ')
460
+ const args = []
461
+ let cur = ''
462
+ let quote = ''
463
+ let started = false
464
+ for (let i = 0; i < s.length; i += 1) {
465
+ const ch = s[i]
466
+ if (quote !== '') {
467
+ if (ch === quote) quote = ''
468
+ else if (ch === '\\' && quote === '"' && i + 1 < s.length) {
469
+ cur += s[i + 1]
470
+ i += 1
471
+ } else cur += ch
472
+ continue
473
+ }
474
+ if (ch === "'" || ch === '"') {
475
+ quote = ch
476
+ started = true
477
+ continue
478
+ }
479
+ if (/\s/.test(ch)) {
480
+ if (started) {
481
+ args.push(cur)
482
+ cur = ''
483
+ started = false
484
+ }
485
+ continue
486
+ }
487
+ cur += ch
488
+ started = true
489
+ }
490
+ if (started) args.push(cur)
491
+ return args
492
+ }
493
+
494
+ /**
495
+ * cURL 命令 → endpoint 骨架。支持 -X/--request、-H/--header、-d/--data*、-u/--user、
496
+ * -F/--form、--url、-G(data 转 query)、以及任意位置的首个 URL。
497
+ */
498
+ export function importCurl(text) {
499
+ const args = splitCurlArgs(text)
500
+ let method = ''
501
+ let url = ''
502
+ const headers = []
503
+ const dataParts = []
504
+ const formParts = []
505
+ let user = ''
506
+ let toQuery = false
507
+
508
+ const takeValue = (i) => (i + 1 < args.length ? args[i + 1] : '')
509
+ for (let i = 0; i < args.length; i += 1) {
510
+ const a = args[i]
511
+ if (a === 'curl') continue
512
+ if (a === '-X' || a === '--request') {
513
+ method = takeValue(i).toUpperCase()
514
+ i += 1
515
+ continue
516
+ }
517
+ if (a === '-H' || a === '--header') {
518
+ const raw = takeValue(i)
519
+ i += 1
520
+ const idx = raw.indexOf(':')
521
+ if (idx > 0) headers.push(makeParam(raw.slice(0, idx).trim(), raw.slice(idx + 1).trim()))
522
+ continue
523
+ }
524
+ if (a === '-d' || a === '--data' || a === '--data-raw' || a === '--data-binary' || a === '--data-ascii') {
525
+ dataParts.push(takeValue(i))
526
+ i += 1
527
+ continue
528
+ }
529
+ if (a === '-F' || a === '--form') {
530
+ const raw = takeValue(i)
531
+ i += 1
532
+ const idx = raw.indexOf('=')
533
+ if (idx > 0) formParts.push({ key: raw.slice(0, idx), value: raw.slice(idx + 1) })
534
+ continue
535
+ }
536
+ if (a === '-u' || a === '--user') {
537
+ user = takeValue(i)
538
+ i += 1
539
+ continue
540
+ }
541
+ if (a === '--url') {
542
+ url = takeValue(i)
543
+ i += 1
544
+ continue
545
+ }
546
+ if (a === '-G' || a === '--get') {
547
+ toQuery = true
548
+ continue
549
+ }
550
+ if (a.startsWith('-')) continue
551
+ if (url === '') url = a
552
+ }
553
+
554
+ const data = dataParts.join('&')
555
+ let params = []
556
+ let baseUrl = url
557
+ try {
558
+ const u = new URL(url)
559
+ params = [...u.searchParams.entries()].map(([k, v]) => makeParam(k, v))
560
+ baseUrl = u.origin + u.pathname
561
+ } catch {
562
+ const qi = url.indexOf('?')
563
+ if (qi >= 0) {
564
+ baseUrl = url.slice(0, qi)
565
+ params = url.slice(qi + 1).split('&').filter(Boolean).map((pair) => {
566
+ const [k, v] = pair.split('=')
567
+ return makeParam(decodeURIComponent(k || ''), decodeURIComponent(v || ''))
568
+ })
569
+ }
570
+ }
571
+ if (toQuery && data !== '') {
572
+ for (const pair of data.split('&').filter(Boolean)) {
573
+ const [k, v] = pair.split('=')
574
+ params.push(makeParam(decodeURIComponent(k || ''), decodeURIComponent(v || '')))
575
+ }
576
+ }
577
+
578
+ let body = { type: 'none', content: '', schema: null, examples: [] }
579
+ if (formParts.length > 0) {
580
+ body = { type: 'form', content: JSON.stringify(formParts), schema: null, examples: [] }
581
+ } else if (data !== '' && !toQuery) {
582
+ const ct = headers.find((h) => h.key.toLowerCase() === 'content-type')
583
+ const ctValue = ct ? ct.value.toLowerCase() : ''
584
+ let type = 'raw'
585
+ if (looksJson(data) || ctValue.includes('json')) type = 'json'
586
+ else if (ctValue.includes('x-www-form-urlencoded')) type = 'urlencoded'
587
+ else if (ctValue.includes('xml')) type = 'xml'
588
+ body = { type, content: data, schema: null, examples: [] }
589
+ }
590
+
591
+ let auth = { ...EMPTY_ENDPOINT.auth }
592
+ if (user !== '') {
593
+ const idx = user.indexOf(':')
594
+ auth = {
595
+ ...auth,
596
+ type: 'basic',
597
+ username: idx >= 0 ? user.slice(0, idx) : user,
598
+ password: idx >= 0 ? user.slice(idx + 1) : '',
599
+ }
600
+ }
601
+
602
+ if (method === '') {
603
+ if (toQuery) method = 'GET'
604
+ else if (body.type !== 'none') method = 'POST'
605
+ else method = 'GET'
606
+ }
607
+
608
+ let name = baseUrl
609
+ try {
610
+ name = new URL(baseUrl).pathname
611
+ } catch {
612
+ // 保留原串
613
+ }
614
+
615
+ return makeEndpoint({
616
+ id: seqId('ep_', 0),
617
+ name: name || (method + ' ' + baseUrl),
618
+ method,
619
+ url: baseUrl,
620
+ params,
621
+ headers,
622
+ body,
623
+ auth,
624
+ })
625
+ }
626
+
627
+ /* ── 导出 ──────────────────────────────────────────────────────────────── */
628
+
629
+ function defaultEnvironment(project) {
630
+ const envs = asArray(project && project.environments)
631
+ return envs.find((e) => e && e.isDefault) || envs[0] || null
632
+ }
633
+
634
+ /** endpoint.url → OpenAPI path(绝对 URL 取 pathname,相对串原样)。 */
635
+ function toOpenApiPath(url, baseUrl) {
636
+ const raw = str(url)
637
+ const base = str(baseUrl).replace(/\/+$/, '')
638
+ if (base !== '' && raw.startsWith(base)) return raw.slice(base.length) || '/'
639
+ try {
640
+ const u = new URL(raw)
641
+ return u.pathname || '/'
642
+ } catch {
643
+ return raw.startsWith('/') ? raw : '/' + raw
644
+ }
645
+ }
646
+
647
+ function paramToOpenApi(row, where) {
648
+ const p = row && typeof row === 'object' ? row : {}
649
+ if (str(p.key) === '') return null
650
+ const schema = { type: str(p.type) || 'string' }
651
+ const out = {
652
+ name: str(p.key),
653
+ in: where,
654
+ required: where === 'path' ? true : !!p.required,
655
+ schema,
656
+ }
657
+ if (str(p.description) !== '') out.description = str(p.description)
658
+ if (str(p.value) !== '') {
659
+ if (schema.type === 'number' || schema.type === 'integer') out.example = Number(p.value)
660
+ else if (schema.type === 'boolean') out.example = p.value === 'true'
661
+ else out.example = str(p.value)
662
+ }
663
+ return out
664
+ }
665
+
666
+ function bodyToOpenApi(body) {
667
+ const b = body && typeof body === 'object' ? body : {}
668
+ const type = str(b.type) || 'none'
669
+ if (type === 'none') return null
670
+ const content = str(b.content)
671
+ const media = {}
672
+ if (b.schema && typeof b.schema === 'object') media.schema = b.schema
673
+ if (type === 'json') {
674
+ if (looksJson(content)) media.example = JSON.parse(content)
675
+ else if (content !== '') media.example = content
676
+ return { content: { 'application/json': media } }
677
+ }
678
+ if (type === 'urlencoded' || type === 'form') {
679
+ let rows = []
680
+ try {
681
+ rows = JSON.parse(content)
682
+ } catch {
683
+ rows = []
684
+ }
685
+ const properties = {}
686
+ for (const r of asArray(rows)) properties[str(r && r.key)] = { type: 'string' }
687
+ media.schema = media.schema || { type: 'object', properties }
688
+ const ct = type === 'form' ? 'multipart/form-data' : 'application/x-www-form-urlencoded'
689
+ return { content: { [ct]: media } }
690
+ }
691
+ if (type === 'xml') return { content: { 'application/xml': { ...media, example: content } } }
692
+ if (type === 'graphql') return { content: { 'application/graphql': { ...media, example: content } } }
693
+ if (type === 'binary') return { content: { 'application/octet-stream': media } }
694
+ return { content: { 'text/plain': { ...media, example: content } } }
695
+ }
696
+
697
+ function responsesToOpenApi(responses) {
698
+ const out = {}
699
+ const rows = asArray(responses)
700
+ if (rows.length === 0) {
701
+ out['200'] = { description: '成功' }
702
+ return out
703
+ }
704
+ for (const raw of rows) {
705
+ const r = raw && typeof raw === 'object' ? raw : {}
706
+ const code = String(r.code === undefined || r.code === null ? 200 : r.code)
707
+ const entry = { description: str(r.name) || ('响应 ' + code) }
708
+ const body = str(r.body)
709
+ const ct = str(r.contentType) || 'application/json'
710
+ if (body !== '') {
711
+ const media = {}
712
+ if (looksJson(body)) media.example = JSON.parse(body)
713
+ else media.example = body
714
+ if (r.schema && typeof r.schema === 'object') media.schema = r.schema
715
+ entry.content = { [ct]: media }
716
+ } else if (r.schema && typeof r.schema === 'object') {
717
+ entry.content = { [ct]: { schema: r.schema } }
718
+ }
719
+ out[code] = entry
720
+ }
721
+ return out
722
+ }
723
+
724
+ /** project → OpenAPI 3.0.3 文档对象。 */
725
+ export function exportOpenApi(project) {
726
+ const p = project && typeof project === 'object' ? project : {}
727
+ const env = defaultEnvironment(p)
728
+ const baseUrl = env ? str(env.baseUrl) : ''
729
+ const paths = {}
730
+ const tagOrder = []
731
+ for (const raw of asArray(p.endpoints)) {
732
+ const ep = raw && typeof raw === 'object' ? raw : {}
733
+ const folder = asArray(p.folders).find((f) => f && f.id === ep.folderId)
734
+ const tag = folder ? str(folder.name) : ''
735
+ if (tag !== '' && !tagOrder.includes(tag)) tagOrder.push(tag)
736
+ const pathKey = toOpenApiPath(ep.url, baseUrl)
737
+ if (!paths[pathKey]) paths[pathKey] = {}
738
+ const operation = {
739
+ summary: str(ep.name) || (str(ep.method) + ' ' + pathKey),
740
+ operationId: str(ep.id),
741
+ responses: responsesToOpenApi(ep.responses),
742
+ }
743
+ if (str(ep.description) !== '') operation.description = str(ep.description)
744
+ if (tag !== '') operation.tags = [tag]
745
+ const parameters = [
746
+ ...asArray(ep.pathParams).map((r) => paramToOpenApi(r, 'path')),
747
+ ...asArray(ep.params).map((r) => paramToOpenApi(r, 'query')),
748
+ ...asArray(ep.headers).map((r) => paramToOpenApi(r, 'header')),
749
+ ...asArray(ep.cookies).map((r) => paramToOpenApi(r, 'cookie')),
750
+ ].filter(Boolean)
751
+ if (parameters.length > 0) operation.parameters = parameters
752
+ const requestBody = bodyToOpenApi(ep.body)
753
+ if (requestBody) operation.requestBody = requestBody
754
+ paths[pathKey][(str(ep.method) || 'GET').toLowerCase()] = operation
755
+ }
756
+
757
+ const schemas = {}
758
+ for (const raw of asArray(p.schemas)) {
759
+ const s = raw && typeof raw === 'object' ? raw : {}
760
+ const name = str(s.name)
761
+ if (name === '') continue
762
+ const base = s.jsonSchema && typeof s.jsonSchema === 'object' ? s.jsonSchema : { type: 'object' }
763
+ schemas[name] = str(s.description) !== '' && base.description === undefined
764
+ ? { ...base, description: str(s.description) }
765
+ : base
766
+ }
767
+
768
+ const doc = {
769
+ openapi: '3.0.3',
770
+ info: {
771
+ title: str(p.name) || 'dsh-postapi 项目',
772
+ version: '1.0.0',
773
+ description: str(p.description),
774
+ },
775
+ paths,
776
+ }
777
+ if (baseUrl !== '') doc.servers = [{ url: baseUrl }]
778
+ if (tagOrder.length > 0) doc.tags = tagOrder.map((name) => ({ name }))
779
+ if (Object.keys(schemas).length > 0) doc.components = { schemas }
780
+ return doc
781
+ }
782
+
783
+ /** project → Postman collection v2.1 对象。 */
784
+ export function exportPostman(project) {
785
+ const p = project && typeof project === 'object' ? project : {}
786
+ const env = defaultEnvironment(p)
787
+ const baseUrl = env ? str(env.baseUrl) : ''
788
+ const folders = asArray(p.folders)
789
+ const endpoints = asArray(p.endpoints)
790
+
791
+ const toItem = (ep) => {
792
+ const e = ep && typeof ep === 'object' ? ep : {}
793
+ const rawUrl = str(e.url)
794
+ const fullUrl = /^https?:\/\//i.test(rawUrl) || baseUrl === '' ? rawUrl : joinUrl(baseUrl, rawUrl)
795
+ const query = asArray(e.params)
796
+ .filter((r) => r && r.enabled !== false && str(r.key) !== '')
797
+ .map((r) => ({ key: str(r.key), value: str(r.value) }))
798
+ const headers = asArray(e.headers)
799
+ .filter((r) => r && r.enabled !== false && str(r.key) !== '')
800
+ .map((r) => ({ key: str(r.key), value: str(r.value) }))
801
+ // Postman raw 惯例带完整 query,导入侧直接取 raw 作 url(往返一致)
802
+ const queryString = query
803
+ .map((q) => encodeURIComponent(q.key) + '=' + encodeURIComponent(q.value))
804
+ .join('&')
805
+ const urlObj = { raw: queryString === '' ? fullUrl : fullUrl + (fullUrl.includes('?') ? '&' : '?') + queryString, query }
806
+ const b = e.body && typeof e.body === 'object' ? e.body : {}
807
+ const bodyType = str(b.type) || 'none'
808
+ const content = str(b.content)
809
+ let body
810
+ if (bodyType === 'json') body = { mode: 'raw', raw: content, options: { raw: { language: 'json' } } }
811
+ else if (bodyType === 'raw' || bodyType === 'xml') body = { mode: 'raw', raw: content }
812
+ else if (bodyType === 'urlencoded' || bodyType === 'form') {
813
+ let rows = []
814
+ try {
815
+ rows = JSON.parse(content)
816
+ } catch {
817
+ rows = []
818
+ }
819
+ const list = asArray(rows).map((r) => ({ key: str(r && r.key), value: str(r && r.value) }))
820
+ body = bodyType === 'form' ? { mode: 'formdata', formdata: list } : { mode: 'urlencoded', urlencoded: list }
821
+ } else if (bodyType === 'graphql') body = { mode: 'graphql', graphql: { query: content } }
822
+ else if (bodyType === 'none') body = undefined
823
+ else body = { mode: 'raw', raw: content }
824
+
825
+ const a = e.auth && typeof e.auth === 'object' ? e.auth : {}
826
+ const authType = str(a.type) || 'none'
827
+ let auth
828
+ if (authType === 'bearer') auth = { type: 'bearer', bearer: [{ key: 'token', value: str(a.token), type: 'string' }] }
829
+ else if (authType === 'basic') {
830
+ auth = {
831
+ type: 'basic',
832
+ basic: [
833
+ { key: 'username', value: str(a.username), type: 'string' },
834
+ { key: 'password', value: str(a.password), type: 'string' },
835
+ ],
836
+ }
837
+ } else if (authType === 'apikey') {
838
+ auth = {
839
+ type: 'apikey',
840
+ apikey: [
841
+ { key: 'key', value: str(a.key), type: 'string' },
842
+ { key: 'value', value: str(a.value), type: 'string' },
843
+ { key: 'in', value: str(a.addTo) || 'header', type: 'string' },
844
+ ],
845
+ }
846
+ }
847
+
848
+ const item = {
849
+ name: str(e.name) || (str(e.method) + ' ' + fullUrl),
850
+ request: {
851
+ method: (str(e.method) || 'GET').toUpperCase(),
852
+ header: headers,
853
+ url: urlObj,
854
+ },
855
+ response: asArray(e.responses).map((r) => ({
856
+ name: str(r && r.name),
857
+ originalRequest: { method: (str(e.method) || 'GET').toUpperCase(), url: urlObj, header: headers },
858
+ status: str(r && r.code),
859
+ code: Number(r && r.code) || 200,
860
+ header: asArray(r && r.headers).map((h) => ({ key: str(h && h.key), value: str(h && h.value) })),
861
+ body: str(r && r.body),
862
+ })),
863
+ }
864
+ if (body) item.request.body = body
865
+ if (auth) item.request.auth = auth
866
+ if (str(e.description) !== '') item.request.description = str(e.description)
867
+ return item
868
+ }
869
+
870
+ const childrenOf = (parentId) => endpoints.filter((ep) => {
871
+ const fid = ep && ep.folderId != null ? ep.folderId : null
872
+ return fid === parentId
873
+ })
874
+ const folderItem = (folder) => {
875
+ const id = folder && folder.id != null ? folder.id : null
876
+ const subFolders = folders.filter((f) => (f && f.parentId != null ? f.parentId : null) === id)
877
+ return {
878
+ name: str(folder && folder.name),
879
+ item: [
880
+ ...subFolders.map(folderItem),
881
+ ...childrenOf(id).map(toItem),
882
+ ],
883
+ }
884
+ }
885
+ const topFolders = folders.filter((f) => !f || f.parentId == null)
886
+ const item = [
887
+ ...topFolders.map(folderItem),
888
+ ...childrenOf(null).map(toItem),
889
+ ]
890
+
891
+ return {
892
+ info: {
893
+ name: str(p.name) || 'dsh-postapi 项目',
894
+ description: str(p.description),
895
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
896
+ },
897
+ item,
898
+ }
899
+ }
900
+
901
+ /** project → HAR 1.2 对象(用第一个响应的 body 作为 content.text)。 */
902
+ export function exportHar(project) {
903
+ const p = project && typeof project === 'object' ? project : {}
904
+ const env = defaultEnvironment(p)
905
+ const baseUrl = env ? str(env.baseUrl) : ''
906
+ const now = new Date(0).toISOString()
907
+ const entries = asArray(p.endpoints).map((raw) => {
908
+ const ep = raw && typeof raw === 'object' ? raw : {}
909
+ const rawUrl = str(ep.url)
910
+ const fullUrl = /^https?:\/\//i.test(rawUrl) || baseUrl === '' ? rawUrl : joinUrl(baseUrl, rawUrl)
911
+ const query = asArray(ep.params)
912
+ .filter((r) => r && r.enabled !== false && str(r.key) !== '')
913
+ .map((r) => ({ name: str(r.key), value: str(r.value) }))
914
+ const headers = asArray(ep.headers)
915
+ .filter((r) => r && r.enabled !== false && str(r.key) !== '')
916
+ .map((r) => ({ name: str(r.key), value: str(r.value) }))
917
+ const bodyText = str(ep.body && ep.body.content)
918
+ const firstResponse = asArray(ep.responses)[0] || null
919
+ // HAR 惯例:request.url 带完整 query,同时保留 queryString 明细
920
+ const harQuery = query
921
+ .map((q) => encodeURIComponent(q.name) + '=' + encodeURIComponent(q.value))
922
+ .join('&')
923
+ const request = {
924
+ method: (str(ep.method) || 'GET').toUpperCase(),
925
+ url: harQuery === '' ? fullUrl : fullUrl + (fullUrl.includes('?') ? '&' : '?') + harQuery,
926
+ httpVersion: 'HTTP/1.1',
927
+ headers,
928
+ queryString: query,
929
+ cookies: [],
930
+ headersSize: -1,
931
+ bodySize: bodyText.length,
932
+ }
933
+ if (bodyText !== '') {
934
+ request.postData = {
935
+ mimeType: str(ep.body && ep.body.type) === 'json' ? 'application/json' : 'text/plain',
936
+ text: bodyText,
937
+ }
938
+ }
939
+ return {
940
+ startedDateTime: now,
941
+ time: 0,
942
+ request,
943
+ response: {
944
+ status: firstResponse ? Number(firstResponse.code) || 200 : 200,
945
+ statusText: firstResponse ? str(firstResponse.name) : '',
946
+ httpVersion: 'HTTP/1.1',
947
+ headers: firstResponse
948
+ ? asArray(firstResponse.headers).map((h) => ({ name: str(h && h.key), value: str(h && h.value) }))
949
+ : [],
950
+ cookies: [],
951
+ content: {
952
+ size: firstResponse ? str(firstResponse.body).length : 0,
953
+ mimeType: firstResponse ? (str(firstResponse.contentType) || 'application/json') : 'application/json',
954
+ text: firstResponse ? str(firstResponse.body) : '',
955
+ },
956
+ redirectURL: '',
957
+ headersSize: -1,
958
+ bodySize: -1,
959
+ },
960
+ cache: {},
961
+ timings: { send: 0, wait: 0, receive: 0 },
962
+ }
963
+ })
964
+ return {
965
+ log: {
966
+ version: '1.2',
967
+ creator: { name: 'dsh-postapi', version: '1.0.0' },
968
+ entries,
969
+ },
970
+ }
971
+ }
972
+
973
+ /** project → Markdown 接口文档字符串(目录树 + 参数表 + 响应示例)。 */
974
+ export function exportMarkdown(project) {
975
+ const p = project && typeof project === 'object' ? project : {}
976
+ const FENCE = '```'
977
+ const BQ = '`'
978
+ const lines = []
979
+ lines.push('# ' + (str(p.name) || 'dsh-postapi 项目'))
980
+ if (str(p.description) !== '') lines.push('', str(p.description))
981
+ lines.push('')
982
+
983
+ const folders = asArray(p.folders)
984
+ const endpoints = asArray(p.endpoints)
985
+ const byFolder = (fid) => endpoints.filter((ep) => (ep && ep.folderId != null ? ep.folderId : null) === fid)
986
+
987
+ const table = (title, rows) => {
988
+ const list = asArray(rows).filter((r) => r && str(r.key) !== '')
989
+ if (list.length === 0) return
990
+ lines.push('**' + title + '**', '')
991
+ lines.push('| 参数 | 值 | 必填 | 说明 |')
992
+ lines.push('| --- | --- | --- | --- |')
993
+ for (const r of list) {
994
+ lines.push('| ' + str(r.key) + ' | ' + str(r.value) + ' | ' + (r.required ? '是' : '否') + ' | ' + str(r.description) + ' |')
995
+ }
996
+ lines.push('')
997
+ }
998
+
999
+ const renderEndpoint = (ep) => {
1000
+ lines.push('### ' + (str(ep.name) || str(ep.id)))
1001
+ lines.push('')
1002
+ lines.push(BQ + (str(ep.method) || 'GET') + ' ' + str(ep.url) + BQ)
1003
+ lines.push('')
1004
+ if (str(ep.description) !== '') lines.push(str(ep.description), '')
1005
+ table('Path 参数', ep.pathParams)
1006
+ table('Query 参数', ep.params)
1007
+ table('Headers', ep.headers)
1008
+ table('Cookies', ep.cookies)
1009
+ const body = ep.body && typeof ep.body === 'object' ? ep.body : {}
1010
+ if (str(body.content) !== '') {
1011
+ lines.push('**请求体(' + (str(body.type) || 'none') + ')**', '')
1012
+ lines.push(FENCE + (str(body.type) === 'json' ? 'json' : ''))
1013
+ lines.push(str(body.content))
1014
+ lines.push(FENCE, '')
1015
+ }
1016
+ const responses = asArray(ep.responses)
1017
+ if (responses.length > 0) {
1018
+ lines.push('**响应**', '')
1019
+ for (const r of responses) {
1020
+ lines.push('- ' + BQ + str(r && r.code) + BQ + ' ' + str(r && r.name))
1021
+ if (str(r && r.body) !== '') {
1022
+ lines.push('', FENCE + 'json', str(r.body), FENCE)
1023
+ }
1024
+ }
1025
+ lines.push('')
1026
+ }
1027
+ }
1028
+
1029
+ const renderFolder = (folder, depth) => {
1030
+ lines.push('#'.repeat(Math.min(depth + 2, 6)) + ' ' + (str(folder && folder.name) || '未命名目录'))
1031
+ lines.push('')
1032
+ const parentId = folder ? folder.id : null
1033
+ for (const sub of folders.filter((f) => (f && f.parentId != null ? f.parentId : null) === parentId)) {
1034
+ renderFolder(sub, depth + 1)
1035
+ }
1036
+ for (const ep of byFolder(parentId)) renderEndpoint(ep)
1037
+ }
1038
+
1039
+ const topFolders = folders.filter((f) => !f || f.parentId == null)
1040
+ for (const f of topFolders) renderFolder(f, 0)
1041
+ for (const ep of byFolder(null)) renderEndpoint(ep)
1042
+ if (topFolders.length === 0 && byFolder(null).length === 0) lines.push('_(暂无接口)_')
1043
+ return lines.join('\n')
1044
+ }