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,102 @@
1
+ /**
2
+ * Host 侧入口:组装 storage / request 与扩展服务(variables / sandbox / mock / runner /
3
+ * importExport / codegen),统一经 webServer prefix 桥暴露给 client。
4
+ *
5
+ * web client 无法注入插件自定义 face(官方机制核实:样板 inject 全为宿主内置 face),
6
+ * 契约 §3 的 inject face 方案作废,改走 dsh-db-tool 同款 webServer prefix 桥(0.2.x 生产验证)。
7
+ */
8
+ import { createStorageService } from './storage.js'
9
+ import { createRequestService } from './request.js'
10
+ import { createMockServer } from './mock-server.js'
11
+ import { createTestRunner } from './test-runner.js'
12
+ import { runScript } from './script-sandbox.js'
13
+ import { createVariableResolver, DYNAMIC_VARS } from './variables.js'
14
+ import * as importExport from './import-export.js'
15
+ import * as codegen from './codegen.js'
16
+ import { handlePostapiRequest } from './bridge.js'
17
+ import { appendFileSync } from 'node:fs'
18
+
19
+ /** cordis 受控 ctx:宿主按此清单注入服务,未声明的属性访问会直接抛错(without inject)。 */
20
+ export const inject = ['webServer', 'connection']
21
+
22
+ /**
23
+ * 自诊断日志路径:仅当 POSTAPI_DEBUG_LOG 指定具体文件时才落盘。
24
+ * 默认不写任何文件——发布版不能往使用者机器上固定路径写日志。
25
+ */
26
+ const POSTAPI_DEBUG_LOG = (process.env.POSTAPI_DEBUG_LOG || '').trim()
27
+
28
+ /** 自诊断日志:写失败不得影响插件加载(磁盘只读 / 目录缺失时静默跳过)。 */
29
+ function bootLog(line) {
30
+ if (POSTAPI_DEBUG_LOG === '') return
31
+ try {
32
+ appendFileSync(POSTAPI_DEBUG_LOG, new Date().toISOString() + ' ' + line + '\n')
33
+ } catch {
34
+ // 诊断日志不是功能路径,写不了就算了
35
+ }
36
+ }
37
+
38
+ export function apply(ctx, config) {
39
+ // 自诊断:host 半边是否被 cordis 加载(定位插件未生效时用;稳定后可删)。
40
+ bootLog('host apply called')
41
+ const basePath = (config && (config.storage?.basePath ?? config.basePath)) || undefined
42
+ const storage = createStorageService(basePath)
43
+ const request = createRequestService()
44
+
45
+ // Mock 服务按需持有单例:项目数据从 storage 现取,端口取项目 settings.mockPort。
46
+ const mock = createMockServer({
47
+ getProject: (projectId) => storage.getProject(projectId),
48
+ port: (config && config.mockPort) || 4010,
49
+ })
50
+ const runner = createTestRunner({ storage, request })
51
+
52
+ // 桥第三参:服务方法缺失时对应路由返回 501 NOT_WIRED,绝不崩 handler。
53
+ const services = {
54
+ variables: {
55
+ createVariableResolver,
56
+ DYNAMIC_VARS,
57
+ },
58
+ sandbox: { runScript },
59
+ mock,
60
+ runner,
61
+ importExport,
62
+ codegen,
63
+ }
64
+
65
+ // cordis ctx 为受控对象,禁止直接挂属性(cannot set property without provide);
66
+ // client 经 webServer prefix 桥取数,全部服务以闭包形式供 handler 使用。
67
+
68
+ // 形态对齐 dsh-db-tool lib/index.ts:136-181:register 缺失时给空 disposer,并带 effect 名。
69
+ ctx.effect?.(
70
+ () =>
71
+ ctx.webServer?.register({
72
+ kind: 'prefix',
73
+ path: '/dsh-postapi/api',
74
+ handler: async (req, res) => {
75
+ // 宿主 Connection 栅栏优先(同 db-tool lib/index.ts 141-158 形态):
76
+ // 插件前缀路由不经宿主鉴权,必须显式应用 requestRejection(Host/Origin + 浏览器 token);
77
+ // 401/403 时由本处兜底写出 JSON 响应(宿主只返回状态码)。
78
+ const rejection = ctx.connection?.requestRejection?.(req)
79
+ if (rejection !== undefined) {
80
+ res.statusCode = rejection
81
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
82
+ res.end(JSON.stringify({
83
+ ok: false,
84
+ error: rejection === 401 ? 'unauthorized: browser authentication required' : 'forbidden: untrusted request',
85
+ code: rejection === 401 ? 'UNAUTHORIZED' : 'FORBIDDEN',
86
+ }))
87
+ return
88
+ }
89
+ await handlePostapiRequest(req, res, { storage, request, services })
90
+ },
91
+ }) ?? (() => {}),
92
+ 'postapi-api',
93
+ )
94
+
95
+ // 插件卸载时收掉可能仍在监听的 Mock 端口(effect disposer 随插件生命周期释放)。
96
+ ctx.effect?.(
97
+ () => () => {
98
+ mock.stop().catch(() => {})
99
+ },
100
+ 'postapi-mock-teardown',
101
+ )
102
+ }
@@ -0,0 +1,303 @@
1
+ /**
2
+ * 本地 Mock 服务:契约 §4 createMockServer。
3
+ * 两种命中路径:GET /mock/<projectId>/<endpointId> 与 GET /mock/<projectId><endpointPath>。
4
+ * body 由 project.mocks 的字段规则生成(fixed/regex/increment/random/template);
5
+ * 未命中规则回落 endpoint.responses 的默认响应,再回落 200 {}。
6
+ */
7
+ import http from 'node:http'
8
+ import { randomUUID } from 'node:crypto'
9
+ import { DYNAMIC_VARS } from './variables.js'
10
+
11
+ const TEMPLATE_RE = /\{\{\s*([^{}]+?)\s*\}\}/g
12
+
13
+ function randInt(min, max) {
14
+ return Math.floor(Math.random() * (max - min + 1)) + min
15
+ }
16
+
17
+ function randStr(len) {
18
+ let out = ''
19
+ const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
20
+ for (let i = 0; i < len; i += 1) out += alphabet[randInt(0, alphabet.length - 1)]
21
+ return out
22
+ }
23
+
24
+ /** 模板规则:{{$timestamp}} 等动态变量即时替换,其它 {{key}} 原样保留。 */
25
+ function resolveTemplate(text) {
26
+ return String(text).replace(TEMPLATE_RE, (raw, name) => {
27
+ const key = String(name).trim()
28
+ return typeof DYNAMIC_VARS[key] === 'function' ? String(DYNAMIC_VARS[key]()) : raw
29
+ })
30
+ }
31
+
32
+ function randomBy(spec) {
33
+ const s = String(spec == null ? '' : spec).trim()
34
+ if (s === '') return randStr(8)
35
+ if (s === 'number' || s === 'int') return String(randInt(0, 1000))
36
+ if (s === 'float') return Math.random().toFixed(4)
37
+ if (s === 'boolean' || s === 'bool') return Math.random() < 0.5 ? 'true' : 'false'
38
+ if (s === 'uuid') return randomUUID()
39
+ if (s === 'email') return `user_${randStr(6)}@example.com`
40
+ if (s === 'phone') return `1${randInt(3, 9)}${String(randInt(0, 999999999)).padStart(9, '0')}`
41
+ if (s === 'string') return randStr(8)
42
+ const m = /^int:(-?\d+):(-?\d+)$/.exec(s)
43
+ if (m) return String(randInt(Number(m[1]), Number(m[2])))
44
+ return randStr(8)
45
+ }
46
+
47
+ function pickChar(token) {
48
+ if (token.startsWith('[') && token.endsWith(']')) {
49
+ const body = token.slice(1, -1)
50
+ const range = /^(\w)-(\w)$/.exec(body)
51
+ if (range) return String.fromCharCode(randInt(range[1].charCodeAt(0), range[2].charCodeAt(0)))
52
+ const chars = body.replace(/\\/g, '')
53
+ return chars === '' ? 'a' : chars[randInt(0, chars.length - 1)]
54
+ }
55
+ if (token === '\\d') return String(randInt(0, 9))
56
+ if (token === '\\w') return randStr(1)
57
+ if (token === '\\s') return ' '
58
+ if (token === '.') return 'a'
59
+ if (token.length === 2 && token[0] === '\\') return token[1]
60
+ return token
61
+ }
62
+
63
+ /** 正则规则:把 [A-Z]{3}[0-9]{4} 这类字面正则展开成一个可匹配串。 */
64
+ function regexSample(pattern) {
65
+ const p = String(pattern == null ? '' : pattern)
66
+ let out = ''
67
+ let i = 0
68
+ while (i < p.length) {
69
+ let token = ''
70
+ if (p[i] === '[') {
71
+ const end = p.indexOf(']', i)
72
+ if (end < 0) {
73
+ token = 'a'
74
+ i += 1
75
+ } else {
76
+ token = p.slice(i, end + 1)
77
+ i = end + 1
78
+ }
79
+ } else if (p[i] === '\\') {
80
+ token = p.slice(i, i + 2)
81
+ i += 2
82
+ } else {
83
+ token = p[i]
84
+ i += 1
85
+ }
86
+ let min = 1
87
+ let max = 1
88
+ const q = /^(?:\{(\d+)(?:,(\d*))?\}|([*+?]))/.exec(p.slice(i))
89
+ if (q) {
90
+ i += q[0].length
91
+ if (q[1] != null) {
92
+ min = Number(q[1])
93
+ max = q[2] == null || q[2] === '' ? min : Number(q[2])
94
+ } else if (q[3] === '*') {
95
+ min = 0
96
+ max = 3
97
+ } else if (q[3] === '+') {
98
+ min = 1
99
+ max = 3
100
+ }
101
+ }
102
+ const n = randInt(min, Math.max(min, Math.min(max, 12)))
103
+ out += pickChar(token).repeat(n)
104
+ }
105
+ return out
106
+ }
107
+
108
+ /** 规则值 → JS 值:能解析成 JSON 的按 JSON 走,否则保留字符串。 */
109
+ function coerce(text) {
110
+ const s = String(text)
111
+ const t = s.trim()
112
+ if (t === '') return s
113
+ if (!/^[[{"]|^-?\d+(\.\d+)?$|^(true|false|null)$/.test(t)) return s
114
+ try {
115
+ return JSON.parse(t)
116
+ } catch {
117
+ return s
118
+ }
119
+ }
120
+
121
+ function ruleValue(rule, endpointId, counters) {
122
+ const value = rule.value == null ? '' : String(rule.value)
123
+ switch (String(rule.rule || 'fixed')) {
124
+ case 'increment': {
125
+ const key = `${endpointId}::${rule.field || ''}::${rule.id || ''}`
126
+ const start = Number(value)
127
+ const base = value !== '' && Number.isFinite(start) ? start : 1
128
+ const current = counters.has(key) ? counters.get(key) : base
129
+ counters.set(key, current + 1)
130
+ return String(current)
131
+ }
132
+ case 'random':
133
+ return randomBy(value)
134
+ case 'regex':
135
+ return regexSample(value)
136
+ case 'template':
137
+ return resolveTemplate(value)
138
+ case 'fixed':
139
+ default:
140
+ return value
141
+ }
142
+ }
143
+
144
+ /** 'a.b[0].c' 路径写入。 */
145
+ function writePath(root, field, value) {
146
+ const segs = String(field).replace(/\[(\d+)\]/g, '.$1').split('.').filter((s) => s !== '')
147
+ let cur = root
148
+ for (let i = 0; i < segs.length; i += 1) {
149
+ const seg = segs[i]
150
+ const last = i === segs.length - 1
151
+ const nextIsIndex = !last && /^\d+$/.test(segs[i + 1])
152
+ if (last) {
153
+ cur[seg] = value
154
+ break
155
+ }
156
+ if (cur[seg] == null) cur[seg] = nextIsIndex ? [] : {}
157
+ cur = cur[seg]
158
+ }
159
+ }
160
+
161
+ /** endpoint.url → pathname(剔除 {{var}} 后取 path;'/api/users' 与 'https://x/api/users' 都归一)。 */
162
+ function urlPathOf(url) {
163
+ if (!url) return ''
164
+ const cleaned = String(url).replace(/\{\{[^{}]*\}\}/g, '')
165
+ try {
166
+ return new URL(cleaned, 'http://mock.local').pathname
167
+ } catch {
168
+ return ''
169
+ }
170
+ }
171
+
172
+ function defaultResponse(endpoint) {
173
+ const responses = Array.isArray(endpoint.responses) ? endpoint.responses.filter((r) => r && r.enabled !== false) : []
174
+ const pick = responses.find((r) => r.isDefault) || responses[0] || null
175
+ if (!pick) return { status: 200, body: {} }
176
+ let body = pick.body
177
+ if (typeof body === 'string' && body.trim() !== '') {
178
+ try {
179
+ body = JSON.parse(body)
180
+ } catch {
181
+ // 非 JSON 响应体原样返回
182
+ }
183
+ }
184
+ const status = Number(pick.code)
185
+ return { status: Number.isFinite(status) && status > 0 ? status : 200, body: body == null || body === '' ? {} : body }
186
+ }
187
+
188
+ function sendJson(res, status, payload) {
189
+ const text = typeof payload === 'string' ? JSON.stringify(payload) : JSON.stringify(payload == null ? {} : payload)
190
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) })
191
+ res.end(text)
192
+ }
193
+
194
+ /**
195
+ * createMockServer({ getProject, port = 4010 })
196
+ * → { start(), stop(), status() -> { running, port } }
197
+ */
198
+ export function createMockServer({ getProject, port = 4010 } = {}) {
199
+ let server = null
200
+ let actualPort = 0
201
+ const counters = new Map()
202
+
203
+ function status() {
204
+ return { running: server != null, port: actualPort }
205
+ }
206
+
207
+ function buildBody(project, endpoint) {
208
+ const rules = (Array.isArray(project.mocks) ? project.mocks : []).filter(
209
+ (r) => r && r.enabled !== false && String(r.endpointId || '') === String(endpoint.id || ''),
210
+ )
211
+ if (rules.length === 0) return null
212
+ const root = {}
213
+ let whole = null
214
+ for (const rule of rules) {
215
+ const v = ruleValue(rule, endpoint.id, counters)
216
+ const field = rule.field == null ? '' : String(rule.field).trim()
217
+ if (field === '') {
218
+ whole = v
219
+ continue
220
+ }
221
+ writePath(root, field, coerce(v))
222
+ }
223
+ if (whole != null && Object.keys(root).length === 0) return coerce(whole)
224
+ return root
225
+ }
226
+
227
+ function matchTarget(project, tail) {
228
+ const endpoints = Array.isArray(project.endpoints) ? project.endpoints : []
229
+ if (tail === '') return null
230
+ const byId = endpoints.find((e) => e && tail === '/' + e.id)
231
+ if (byId) return byId
232
+ for (const e of endpoints) {
233
+ if (!e) continue
234
+ const p = urlPathOf(e.url)
235
+ if (p && (tail === p || tail === p + '/')) return e
236
+ }
237
+ return null
238
+ }
239
+
240
+ async function handle(req, res) {
241
+ try {
242
+ const u = new URL(req.url || '/', 'http://mock.local')
243
+ if (!u.pathname.startsWith('/mock/')) return sendJson(res, 404, { ok: false, error: 'mock: route must start with /mock/' })
244
+ const rest = u.pathname.slice('/mock/'.length)
245
+ const slash = rest.indexOf('/')
246
+ const projectId = slash < 0 ? rest : rest.slice(0, slash)
247
+ const tail = slash < 0 ? '' : rest.slice(slash)
248
+ if (projectId === '') return sendJson(res, 404, { ok: false, error: 'mock: projectId is required' })
249
+
250
+ let project
251
+ try {
252
+ project = await getProject(projectId)
253
+ } catch (err) {
254
+ return sendJson(res, 404, { ok: false, error: `mock: project not found: ${projectId}` })
255
+ }
256
+ if (!project) return sendJson(res, 404, { ok: false, error: `mock: project not found: ${projectId}` })
257
+
258
+ const endpoint = matchTarget(project, tail)
259
+ if (!endpoint) return sendJson(res, 404, { ok: false, error: `mock: no endpoint matched path ${u.pathname}` })
260
+
261
+ const generated = buildBody(project, endpoint)
262
+ const fallback = generated == null ? defaultResponse(endpoint) : null
263
+ const delay = Number(endpoint.mock && endpoint.mock.delayMs) || 0
264
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay))
265
+ return sendJson(res, fallback ? fallback.status : 200, generated == null ? fallback.body : generated)
266
+ } catch (err) {
267
+ return sendJson(res, 500, { ok: false, error: err && err.message ? err.message : String(err) })
268
+ }
269
+ }
270
+
271
+ function start() {
272
+ if (server) return Promise.resolve(status())
273
+ return new Promise((resolve, reject) => {
274
+ const s = http.createServer(handle)
275
+ const onError = (err) => {
276
+ s.removeListener('listening', onListening)
277
+ reject(err)
278
+ }
279
+ const onListening = () => {
280
+ s.removeListener('error', onError)
281
+ s.on('error', () => {})
282
+ server = s
283
+ actualPort = s.address().port
284
+ resolve(status())
285
+ }
286
+ s.once('error', onError)
287
+ s.once('listening', onListening)
288
+ s.listen(Number(port) || 0, '127.0.0.1')
289
+ })
290
+ }
291
+
292
+ function stop() {
293
+ if (!server) return Promise.resolve(status())
294
+ const s = server
295
+ server = null
296
+ actualPort = 0
297
+ return new Promise((resolve) => {
298
+ s.close(() => resolve(status()))
299
+ })
300
+ }
301
+
302
+ return { start, stop, status }
303
+ }