dsh-postapi 0.0.0-stage → 0.0.2

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,530 @@
1
+ /**
2
+ * 页面注册表 + 同源 HTTP 桥 api(db-tool 同款)。
3
+ *
4
+ * - window.__postapiPages:页面注册表。页面(T5 ui-pages)运行时调用
5
+ * window.__postapiPages.register(name, component) 自注册;本骨架禁止静态
6
+ * import ../pages/,只消费注册表。
7
+ * - window.__postapiApi:同源 HTTP 桥。宿主 face 总线只提供内置 face,postapi.*
8
+ * 无法注册为自定义 face,故 client 侧经 fetch('/dsh-postapi/api/…') 同源相对
9
+ * 路径调用宿主桥路由(契约 §2/§3/§4 签名逐项映射,契约 §5 路由全表一一对应);
10
+ * 响应封套 { ok, data | error },fetch 失败 / 非 2xx / ok!==true 时该次调用回落
11
+ * 内存桩兜底(签名不变,桩为最小可用实现,不抛错)。
12
+ */
13
+ import { POSTAPI_NS } from './locales.js'
14
+
15
+ /** 页面注册表(name -> component)。 */
16
+ const pages = new Map()
17
+
18
+ export const pageRegistry = {
19
+ register(name, component) { pages.set(name, component) },
20
+ get(name) { return pages.get(name) },
21
+ has(name) { return pages.has(name) },
22
+ names() { return [...pages.keys()] },
23
+ }
24
+
25
+ /** 把注册表挂到 window(幂等),并重放队列期注册(页面模块可能早于本函数求值)。 */
26
+ export function ensureGlobals() {
27
+ if (typeof window === 'undefined') return
28
+ window.__postapiPages = pageRegistry
29
+ const queued = window.__postapiQueue
30
+ if (Array.isArray(queued)) {
31
+ for (const entry of queued.splice(0)) pageRegistry.register(entry[0], entry[1])
32
+ }
33
+ }
34
+
35
+ /* ---------------- 同源 HTTP 桥 ---------------- */
36
+
37
+ /** 桥基路径:宿主在同源下托管的插件路由前缀。 */
38
+ export const BRIDGE_BASE = '/dsh-postapi/api'
39
+
40
+ /**
41
+ * 一次桥调用:fetch 同源相对路径并解包封套。
42
+ * @param path - 桥内路径(如 '/storage/listProjects')。
43
+ * @param init - fetch init(缺省 GET)。
44
+ * @returns 封套 data 字段。
45
+ * @throws 任一环节失败(网络 / HTTP 非 2xx / ok!==true)。
46
+ */
47
+ async function bridgeCall(path, init) {
48
+ const res = await fetch(BRIDGE_BASE + path, init)
49
+ if (!res.ok) throw new Error('postapi bridge: HTTP ' + res.status + ' ' + path)
50
+ const payload = await res.json()
51
+ if (!payload || payload.ok !== true) {
52
+ const reason = payload && payload.error && payload.error.message ? payload.error.message : '响应缺少 ok:true'
53
+ throw new Error('postapi bridge: ' + reason + ' (' + path + ')')
54
+ }
55
+ return payload.data
56
+ }
57
+
58
+ function bridgePost(path, body) {
59
+ return bridgeCall(path, {
60
+ method: 'POST',
61
+ headers: { 'Content-Type': 'application/json' },
62
+ body: JSON.stringify(body ?? {}),
63
+ })
64
+ }
65
+
66
+ /** GET + query 形态(history/search/listProjects 用,契约 §5 这两条为 GET)。 */
67
+ function bridgeGet(path, query) {
68
+ const qs = new URLSearchParams()
69
+ for (const [k, v] of Object.entries(query ?? {})) {
70
+ if (v !== undefined && v !== null && v !== '') qs.set(k, String(v))
71
+ }
72
+ const tail = qs.toString()
73
+ return bridgeCall(path + (tail ? '?' + tail : ''))
74
+ }
75
+
76
+ /**
77
+ * storage 桥:契约 §3 全量签名映射到 /storage/<method>。
78
+ * 与 host 路由一一对应(storage/X ↔ POST|GET /storage/X),名称不得改写。
79
+ */
80
+ export function createBridgeStorage() {
81
+ const post = (method, body) => bridgePost('/storage/' + method, body)
82
+ return {
83
+ // 既有 9 方法(签名保持不变)
84
+ listProjects: () => bridgeCall('/storage/listProjects'),
85
+ createProject: (name) => post('createProject', { name }),
86
+ renameProject: (id, name) => post('renameProject', { id, name }),
87
+ deleteProject: (id) => post('deleteProject', { id }),
88
+ getProject: (id) => post('getProject', { id }),
89
+ saveEndpoint: (projectId, endpoint) => post('saveEndpoint', { projectId, endpoint }),
90
+ deleteEndpoint: (projectId, endpointId) => post('deleteEndpoint', { projectId, endpointId }),
91
+ saveFolder: (projectId, folder) => post('saveFolder', { projectId, folder }),
92
+ deleteFolder: (projectId, folderId) => post('deleteFolder', { projectId, folderId }),
93
+ // 契约 §3 新增
94
+ moveNode: (projectId, node) => post('moveNode', { projectId, ...(node ?? {}) }),
95
+ importBundle: (projectId, bundle) => post('importBundle', { projectId, bundle }),
96
+ saveSchema: (projectId, schema) => post('saveSchema', { projectId, schema }),
97
+ deleteSchema: (projectId, schemaId) => post('deleteSchema', { projectId, schemaId }),
98
+ saveEnvironment: (projectId, environment) => post('saveEnvironment', { projectId, environment }),
99
+ deleteEnvironment: (projectId, envId) => post('deleteEnvironment', { projectId, envId }),
100
+ saveGlobals: (projectId, globals) => post('saveGlobals', { projectId, globals }),
101
+ saveProjectSettings: (projectId, settings) => post('saveProjectSettings', { projectId, settings }),
102
+ saveFlow: (projectId, flow) => post('saveFlow', { projectId, flow }),
103
+ saveResponse: (projectId, endpointId, response) => post('saveResponse', { projectId, endpointId, response }),
104
+ deleteResponse: (projectId, endpointId, responseId) => post('deleteResponse', { projectId, endpointId, responseId }),
105
+ getHistory: (projectId) => bridgeGet('/storage/getHistory', { projectId }),
106
+ appendHistory: (projectId, entry) => post('appendHistory', { projectId, entry }),
107
+ clearHistory: (projectId) => post('clearHistory', { projectId }),
108
+ search: (projectId, keyword) => bridgeGet('/storage/search', { projectId, keyword }),
109
+ }
110
+ }
111
+
112
+ /** request 桥:契约 §4 send / preview 整体走 POST。 */
113
+ export function createBridgeRequest() {
114
+ return {
115
+ send: (opts) => bridgePost('/request/send', opts ?? {}),
116
+ preview: (opts) => bridgePost('/request/preview', opts ?? {}),
117
+ }
118
+ }
119
+
120
+ /** script / mock / schema / import / export / codegen / test / db 桥(契约 §4,名称与 host 路由同名)。 */
121
+ export function createBridgeServices() {
122
+ const post = bridgePost
123
+ return {
124
+ script: { run: (code, options) => post('/script/run', { code, ...(options ?? {}) }) },
125
+ mock: {
126
+ start: (port) => post('/mock/start', { port }),
127
+ stop: () => post('/mock/stop', {}),
128
+ status: () => post('/mock/status', {}),
129
+ },
130
+ schema: {
131
+ example: (opts) => post('/schema/example', opts ?? {}),
132
+ validate: (opts) => post('/schema/validate', opts ?? {}),
133
+ },
134
+ import: {
135
+ openapi: (json) => post('/import/openapi', { json }),
136
+ postman: (json) => post('/import/postman', { json }),
137
+ har: (json) => post('/import/har', { json }),
138
+ curl: (text) => post('/import/curl', { text }),
139
+ },
140
+ export: {
141
+ openapi: (project) => post('/export/openapi', { project }),
142
+ postman: (project) => post('/export/postman', { project }),
143
+ har: (project) => post('/export/har', { project }),
144
+ markdown: (project) => post('/export/markdown', { project }),
145
+ },
146
+ codegen: { run: (opts) => post('/codegen/run', opts ?? {}) },
147
+ test: {
148
+ runCase: (projectId, caseId) => post('/test/runCase', { projectId, caseId }),
149
+ runScenario: (projectId, scenarioId) => post('/test/runScenario', { projectId, scenarioId }),
150
+ },
151
+ db: {
152
+ test: (opts) => post('/db/test', opts ?? {}),
153
+ query: (opts) => post('/db/query', opts ?? {}),
154
+ close: (opts) => post('/db/close', opts ?? {}),
155
+ },
156
+ }
157
+ }
158
+
159
+ /* ---------------- 内存版 storage 桩(契约 §3 签名,兜底用) ---------------- */
160
+
161
+ function nowIso() { return new Date().toISOString() }
162
+ function makeId(prefix) { return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 4) }
163
+
164
+ function emptyProject(id, name) {
165
+ return {
166
+ id, name, description: '', createdAt: nowIso(), updatedAt: nowIso(), schemaVersion: 2,
167
+ folders: [], endpoints: [], schemas: [],
168
+ environments: [], globals: { variables: [] },
169
+ mocks: [], testCases: [], testScenarios: [],
170
+ flow: { name: '', steps: [] },
171
+ settings: { mockPort: 4010, proxyUrl: '', requestTimeoutMs: 30000, historyLimit: 200 },
172
+ }
173
+ }
174
+
175
+ /** upsert 到数组:有 id 覆盖(保留 createdAt),无 id 新建。 */
176
+ function upsert(list, item, prefix) {
177
+ const ts = nowIso()
178
+ if (item && item.id) {
179
+ const at = list.findIndex((x) => x.id === item.id)
180
+ const merged = { ...(at >= 0 ? list[at] : { createdAt: ts }), ...item, updatedAt: ts }
181
+ if (at >= 0) list[at] = merged
182
+ else list.push(merged)
183
+ return merged
184
+ }
185
+ const created = { ...item, id: makeId(prefix), createdAt: ts, updatedAt: ts }
186
+ list.push(created)
187
+ return created
188
+ }
189
+
190
+ /** 契约 §3 postapi.storage 的内存实现,签名逐项对齐(兜底不落盘)。 */
191
+ export function createStubStorage() {
192
+ const projects = new Map()
193
+ const history = new Map()
194
+ const project = (id) => projects.get(id)
195
+ const clone = (v) => (v === undefined ? undefined : structuredClone(v))
196
+ return {
197
+ listProjects() {
198
+ return [...projects.values()]
199
+ .map((p) => ({ id: p.id, name: p.name, updatedAt: p.updatedAt }))
200
+ .sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))
201
+ },
202
+ createProject(name) {
203
+ const created = emptyProject(makeId('proj_'), String(name ?? '新项目'))
204
+ projects.set(created.id, created)
205
+ return clone(created)
206
+ },
207
+ renameProject(id, name) {
208
+ const p = project(id)
209
+ if (p) { p.name = String(name ?? p.name); p.updatedAt = nowIso() }
210
+ return clone(p)
211
+ },
212
+ deleteProject(id) { projects.delete(id); history.delete(id) },
213
+ getProject(id) { return clone(project(id)) },
214
+ saveEndpoint(projectId, endpoint) {
215
+ const p = project(projectId)
216
+ if (!p) return undefined
217
+ p.updatedAt = nowIso()
218
+ return clone(upsert(p.endpoints, endpoint ?? {}, 'ep_'))
219
+ },
220
+ deleteEndpoint(projectId, endpointId) {
221
+ const p = project(projectId)
222
+ if (!p) return undefined
223
+ p.endpoints = p.endpoints.filter((e) => e.id !== endpointId)
224
+ p.updatedAt = nowIso()
225
+ return { id: endpointId }
226
+ },
227
+ saveFolder(projectId, folder) {
228
+ const p = project(projectId)
229
+ if (!p) return undefined
230
+ p.updatedAt = nowIso()
231
+ return clone(upsert(p.folders, folder ?? {}, 'fld_'))
232
+ },
233
+ deleteFolder(projectId, folderId) {
234
+ const p = project(projectId)
235
+ if (!p) return undefined
236
+ p.folders = p.folders.filter((f) => f.id !== folderId)
237
+ for (const e of p.endpoints) if (e.folderId === folderId) e.folderId = null
238
+ for (const f of p.folders) if (f.parentId === folderId) f.parentId = null
239
+ p.updatedAt = nowIso()
240
+ return { id: folderId }
241
+ },
242
+ moveNode(projectId, node) {
243
+ const p = project(projectId)
244
+ if (!p) return undefined
245
+ const { kind, id, parentId = null, order } = node ?? {}
246
+ const list = kind === 'folder' ? p.folders : p.endpoints
247
+ const hit = list.find((x) => x.id === id)
248
+ if (!hit) return undefined
249
+ if (kind === 'folder') hit.parentId = parentId
250
+ else hit.folderId = parentId
251
+ if (order !== undefined) hit.order = order
252
+ p.updatedAt = nowIso()
253
+ return clone(hit)
254
+ },
255
+ /** 桥不可达时的兜底:与 host importBundle 同形返回(计数 + 空映射),数据不落盘。 */
256
+ importBundle(projectId, bundle) {
257
+ const p = project(projectId)
258
+ const b = bundle && typeof bundle === 'object' ? bundle : {}
259
+ const count = (v) => (Array.isArray(v) ? v.length : 0)
260
+ const result = { folders: count(b.folders), endpoints: count(b.endpoints), schemas: count(b.schemas), idMap: {} }
261
+ if (p) p.updatedAt = nowIso()
262
+ return result
263
+ },
264
+ saveSchema(projectId, schema) {
265
+ const p = project(projectId)
266
+ if (!p) return undefined
267
+ p.updatedAt = nowIso()
268
+ return clone(upsert(p.schemas, schema ?? {}, 'sch_'))
269
+ },
270
+ deleteSchema(projectId, schemaId) {
271
+ const p = project(projectId)
272
+ if (!p) return undefined
273
+ p.schemas = p.schemas.filter((s) => s.id !== schemaId)
274
+ p.updatedAt = nowIso()
275
+ return { id: schemaId }
276
+ },
277
+ saveEnvironment(projectId, environment) {
278
+ const p = project(projectId)
279
+ if (!p) return undefined
280
+ p.updatedAt = nowIso()
281
+ return clone(upsert(p.environments, environment ?? {}, 'env_'))
282
+ },
283
+ deleteEnvironment(projectId, envId) {
284
+ const p = project(projectId)
285
+ if (!p) return undefined
286
+ p.environments = p.environments.filter((e) => e.id !== envId)
287
+ p.updatedAt = nowIso()
288
+ return { id: envId }
289
+ },
290
+ saveGlobals(projectId, globals) {
291
+ const p = project(projectId)
292
+ if (!p) return undefined
293
+ p.globals = { variables: [], ...(globals ?? {}) }
294
+ p.updatedAt = nowIso()
295
+ return clone(p.globals)
296
+ },
297
+ saveProjectSettings(projectId, settings) {
298
+ const p = project(projectId)
299
+ if (!p) return undefined
300
+ p.settings = { ...p.settings, ...(settings ?? {}) }
301
+ p.updatedAt = nowIso()
302
+ return clone(p.settings)
303
+ },
304
+ saveFlow(projectId, flow) {
305
+ const p = project(projectId)
306
+ if (!p) return undefined
307
+ p.flow = { name: '', steps: [], ...(flow ?? {}) }
308
+ p.updatedAt = nowIso()
309
+ return clone(p.flow)
310
+ },
311
+ saveResponse(projectId, endpointId, response) {
312
+ const p = project(projectId)
313
+ if (!p) return undefined
314
+ const ep = p.endpoints.find((e) => e.id === endpointId)
315
+ if (!ep) return undefined
316
+ ep.responses = Array.isArray(ep.responses) ? ep.responses : []
317
+ p.updatedAt = nowIso()
318
+ return clone(upsert(ep.responses, response ?? {}, 'res_'))
319
+ },
320
+ deleteResponse(projectId, endpointId, responseId) {
321
+ const p = project(projectId)
322
+ if (!p) return undefined
323
+ const ep = p.endpoints.find((e) => e.id === endpointId)
324
+ if (ep && Array.isArray(ep.responses)) ep.responses = ep.responses.filter((r) => r.id !== responseId)
325
+ p.updatedAt = nowIso()
326
+ return { id: responseId }
327
+ },
328
+ getHistory(projectId) {
329
+ return { entries: clone(history.get(projectId) || []) }
330
+ },
331
+ appendHistory(projectId, entry) {
332
+ const p = project(projectId)
333
+ const limit = (p && p.settings && p.settings.historyLimit) || 200
334
+ const list = history.get(projectId) || []
335
+ const created = { id: makeId('his_'), at: nowIso(), ...(entry ?? {}) }
336
+ list.unshift(created)
337
+ history.set(projectId, list.slice(0, limit))
338
+ return clone(created)
339
+ },
340
+ clearHistory(projectId) {
341
+ const n = (history.get(projectId) || []).length
342
+ history.set(projectId, [])
343
+ return { cleared: n }
344
+ },
345
+ search(projectId, keyword) {
346
+ const p = project(projectId)
347
+ const kw = String(keyword ?? '').toLowerCase()
348
+ if (!p || kw === '') return { endpoints: [], schemas: [], folders: [] }
349
+ const hit = (obj, fields) => fields.some((f) => String(obj[f] ?? '').toLowerCase().includes(kw))
350
+ return {
351
+ endpoints: clone(p.endpoints.filter((e) => hit(e, ['name', 'url', 'description']))),
352
+ schemas: clone(p.schemas.filter((s) => hit(s, ['name', 'description']))),
353
+ folders: clone(p.folders.filter((f) => hit(f, ['name']))),
354
+ }
355
+ },
356
+ }
357
+ }
358
+
359
+ /* ---------------- request 桩(契约 §4 签名,fetch 实现,兜底用) ---------------- */
360
+
361
+ /** 契约 §4 postapi.request:fetch + AbortController + auth 注入 + query 拼接。 */
362
+ export function createStubRequest() {
363
+ return async function send(opts = {}) {
364
+ const { method = 'GET', url = '', params, headers, body, auth, timeoutMs = 30000 } = opts
365
+ const started = Date.now()
366
+ const controller = new AbortController()
367
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
368
+ try {
369
+ const finalUrl = new URL(url, typeof location !== 'undefined' ? location.href : 'http://localhost/')
370
+ for (const { key, value, enabled = true } of params ?? []) {
371
+ if (enabled && key) finalUrl.searchParams.set(String(key), String(value ?? ''))
372
+ }
373
+ const h = new Headers()
374
+ for (const { key, value, enabled = true } of headers ?? []) {
375
+ if (enabled && key) h.set(String(key), String(value ?? ''))
376
+ }
377
+ let bodyText
378
+ if (body && body.type !== 'none' && method !== 'GET' && method !== 'HEAD') {
379
+ if (body.type === 'json') {
380
+ bodyText = body.content ?? ''
381
+ if (!h.has('Content-Type')) h.set('Content-Type', 'application/json')
382
+ } else if (body.type === 'form') {
383
+ bodyText = body.content ?? ''
384
+ if (!h.has('Content-Type')) h.set('Content-Type', 'application/x-www-form-urlencoded')
385
+ } else {
386
+ bodyText = body.content ?? ''
387
+ }
388
+ }
389
+ if (auth?.type === 'bearer' && auth.token) h.set('Authorization', 'Bearer ' + auth.token)
390
+ if (auth?.type === 'basic' && auth.username !== undefined) {
391
+ h.set('Authorization', 'Basic ' + btoa(auth.username + ':' + (auth.password ?? '')))
392
+ }
393
+ const res = await fetch(finalUrl.toString(), { method, headers: h, body: bodyText, signal: controller.signal })
394
+ const text = await res.text()
395
+ return {
396
+ status: res.status,
397
+ statusText: res.statusText,
398
+ headers: Object.fromEntries(res.headers.entries()),
399
+ body: text,
400
+ bodySize: text.length,
401
+ timeMs: Date.now() - started,
402
+ }
403
+ } catch (error) {
404
+ return {
405
+ status: 0, statusText: '', headers: {}, body: '', bodySize: 0,
406
+ timeMs: Date.now() - started,
407
+ error: { message: error instanceof Error ? error.message : String(error), aborted: controller.signal.aborted },
408
+ }
409
+ } finally { clearTimeout(timer) }
410
+ }
411
+ }
412
+
413
+ /* ---------------- 服务桩(契约 §4 最小可用,兜底不抛错) ---------------- */
414
+
415
+ /** 脚本沙箱桩:明确回报「不可用」,不执行任何代码(浏览器侧无 vm 隔离)。 */
416
+ export function createStubServices() {
417
+ return {
418
+ script: {
419
+ run: async () => ({ ok: false, error: '脚本沙箱不可用(桥降级:需 host 侧 vm 沙箱)', logs: [], variables: {}, tests: [], exports: {} }),
420
+ },
421
+ mock: {
422
+ start: async () => ({ running: false, port: 0, error: 'Mock 服务不可用(桥降级)' }),
423
+ stop: async () => ({ running: false, port: 0 }),
424
+ status: async () => ({ running: false, port: 0 }),
425
+ },
426
+ schema: {
427
+ example: async () => ({ example: {} }),
428
+ validate: async () => ({ ok: true, message: '降级:桥不可达,未执行服务端校验' }),
429
+ },
430
+ import: {
431
+ openapi: async () => ({ folders: [], endpoints: [], schemas: [] }),
432
+ postman: async () => ({ folders: [], endpoints: [], schemas: [] }),
433
+ har: async () => ({ folders: [], endpoints: [], schemas: [] }),
434
+ curl: async () => ({ folders: [], endpoints: [], schemas: [], endpoint: null }),
435
+ },
436
+ export: {
437
+ openapi: async () => '',
438
+ postman: async () => '',
439
+ har: async () => '',
440
+ markdown: async () => '',
441
+ },
442
+ codegen: { run: async () => '' },
443
+ test: {
444
+ runCase: async (projectId, caseId) => ({ caseId, passed: false, results: [], durationMs: 0, error: '测试运行器不可用(桥降级)' }),
445
+ runScenario: async (projectId, scenarioId) => ({ scenarioId, passed: false, steps: [], durationMs: 0, error: '测试运行器不可用(桥降级)' }),
446
+ },
447
+ db: {
448
+ test: async () => ({ available: false, message: '数据库操作规划中(P2)' }),
449
+ query: async () => ({ available: false, message: '数据库操作规划中(P2)' }),
450
+ close: async () => ({ available: false, message: '数据库操作规划中(P2)' }),
451
+ },
452
+ }
453
+ }
454
+
455
+ /* ---------------- 安装:桥 + 逐方法兜底 ---------------- */
456
+
457
+ /** storage 桥/桩共有的全部方法名(installApi 逐方法包装的事实来源)。 */
458
+ export const STORAGE_METHODS = [
459
+ 'listProjects', 'createProject', 'renameProject', 'deleteProject', 'getProject',
460
+ 'saveEndpoint', 'deleteEndpoint', 'saveFolder', 'deleteFolder',
461
+ 'moveNode', 'importBundle', 'saveSchema', 'deleteSchema', 'saveEnvironment', 'deleteEnvironment',
462
+ 'saveGlobals', 'saveProjectSettings', 'saveFlow', 'saveResponse', 'deleteResponse',
463
+ 'getHistory', 'appendHistory', 'clearHistory', 'search',
464
+ ]
465
+
466
+ /** request 桥/桩共有的全部方法名。 */
467
+ export const REQUEST_METHODS = ['send', 'preview']
468
+
469
+ /** 服务命名空间与方法名(契约 §4 全表,键为 api.<ns>.<method>)。 */
470
+ export const SERVICE_METHODS = {
471
+ script: ['run'],
472
+ mock: ['start', 'stop', 'status'],
473
+ schema: ['example', 'validate'],
474
+ import: ['openapi', 'postman', 'har', 'curl'],
475
+ export: ['openapi', 'postman', 'har', 'markdown'],
476
+ codegen: ['run'],
477
+ test: ['runCase', 'runScenario'],
478
+ db: ['test', 'query', 'close'],
479
+ }
480
+
481
+ /**
482
+ * 把桥形态的 api 挂到 window.__postapiApi(幂等)。
483
+ * 每个方法独立兜底:桥调用失败时 console.warn 一次并回落内存桩,
484
+ * 契约 §3/§4 签名保持不变(兜底数据不落盘)。
485
+ * @returns 挂载后的 api 对象。
486
+ */
487
+ export function installApi() {
488
+ if (typeof window === 'undefined') return undefined
489
+ let warned = false
490
+ const warnOnce = () => {
491
+ if (warned) return
492
+ warned = true
493
+ try { console.warn('[dsh-postapi] ' + BRIDGE_BASE + ' 桥不可达,本次起降级内存桩(数据不落盘)') }
494
+ catch { /* 非控制台环境忽略 */ }
495
+ }
496
+ const wrap = (bridgeFn, stubFn) => (...args) =>
497
+ Promise.resolve()
498
+ .then(() => bridgeFn(...args))
499
+ .catch(() => {
500
+ warnOnce()
501
+ return stubFn(...args)
502
+ })
503
+
504
+ const bridgeStorage = createBridgeStorage()
505
+ const stubStorage = createStubStorage()
506
+ const storage = {}
507
+ for (const method of STORAGE_METHODS) storage[method] = wrap(bridgeStorage[method], stubStorage[method])
508
+
509
+ const bridgeRequest = createBridgeRequest()
510
+ const stubSend = createStubRequest()
511
+ // 桩 request 是单函数形态(契约 §4 send 主体);preview 的桩为纯本地渲染占位。
512
+ const requestStub = {
513
+ send: stubSend,
514
+ preview: async (opts = {}) => ({ url: { resolved: String(opts.url ?? ''), missing: [] }, params: opts.params ?? [], headers: opts.headers ?? [], body: opts.body ?? null }),
515
+ }
516
+ const request = {}
517
+ for (const method of REQUEST_METHODS) request[method] = wrap(bridgeRequest[method], requestStub[method])
518
+
519
+ const bridgeServices = createBridgeServices()
520
+ const stubServices = createStubServices()
521
+ const api = { storage, request }
522
+ for (const [ns, methods] of Object.entries(SERVICE_METHODS)) {
523
+ api[ns] = {}
524
+ for (const method of methods) api[ns][method] = wrap(bridgeServices[ns][method], stubServices[ns][method])
525
+ }
526
+ window.__postapiApi = api
527
+ return api
528
+ }
529
+
530
+ export { POSTAPI_NS }