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.
- package/LICENSE +201 -0
- package/README.md +139 -2
- package/cordis.patch.yml +3 -0
- package/dist/client.js +5651 -0
- package/docs/DETAIL.md +27 -0
- package/docs/apifox-design-spec.md +101 -0
- package/docs/apifox-research/analysis.md +254 -0
- package/docs/apifox-ui-delivery.md +150 -0
- package/docs/apifox-visual-parity-spec.md +353 -0
- package/docs/feature-matrix.md +112 -0
- package/docs/flow-reference/sequence-reference.html +163 -0
- package/docs/interface-contract-v2.md +175 -0
- package/docs/interface-contract.md +105 -0
- package/docs/nav-layout-v2-spec.md +107 -0
- package/docs/preview.svg +9 -0
- package/docs/probe-client.legacy.js +31 -0
- package/docs/rootcause-sidebar-vanish.md +95 -0
- package/docs/rootcause.md +86 -0
- package/docs/sidebar-notes.md +153 -0
- package/docs/ui-audit.md +197 -0
- package/docs/ui-notes.md +98 -0
- package/docs/v2-delivery.md +99 -0
- package/icon.svg +4 -0
- package/index.js +5 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +73 -4
- package/src/client/index.js +132 -0
- package/src/client/jsx-shim.js +9 -0
- package/src/client/pages/__tests__/heights.test.js +135 -0
- package/src/client/pages/components/AssertTable.jsx +122 -0
- package/src/client/pages/components/BodyEditor.jsx +91 -0
- package/src/client/pages/components/EmptyState.jsx +52 -0
- package/src/client/pages/components/FolderTree.jsx +109 -0
- package/src/client/pages/components/JsonEditor.jsx +45 -0
- package/src/client/pages/components/ParamTable.jsx +226 -0
- package/src/client/pages/components/ResponsePanel.jsx +278 -0
- package/src/client/pages/components/ScriptPanel.jsx +99 -0
- package/src/client/pages/components/StatusPill.jsx +35 -0
- package/src/client/pages/components/__tests__/apifox-ui.test.js +291 -0
- package/src/client/pages/components/__tests__/pages-a.test.js +392 -0
- package/src/client/pages/components/__tests__/tree.test.js +379 -0
- package/src/client/pages/components/headerPresets.js +63 -0
- package/src/client/pages/debug.jsx +576 -0
- package/src/client/pages/design-tokens.css +2604 -0
- package/src/client/pages/doc.jsx +552 -0
- package/src/client/pages/env.jsx +378 -0
- package/src/client/pages/flow.jsx +349 -0
- package/src/client/pages/history.jsx +238 -0
- package/src/client/pages/import.jsx +396 -0
- package/src/client/pages/mock.jsx +316 -0
- package/src/client/pages/overview.jsx +348 -0
- package/src/client/pages/schema.jsx +317 -0
- package/src/client/pages/search.jsx +216 -0
- package/src/client/pages/sequence.jsx +344 -0
- package/src/client/pages/settings.jsx +205 -0
- package/src/client/pages/test.jsx +470 -0
- package/src/client/pages/theme.js +27 -0
- package/src/client/pages-entry.js +20 -0
- package/src/client/shell/ApiTitle.js +19 -0
- package/src/client/shell/Body.js +492 -0
- package/src/client/shell/definition.js +57 -0
- package/src/client/shell/locales.js +185 -0
- package/src/client/shell/menu.js +174 -0
- package/src/client/shell/registry.js +530 -0
- package/src/host/bridge.js +407 -0
- package/src/host/codegen.js +356 -0
- package/src/host/import-export.js +1044 -0
- package/src/host/index.js +102 -0
- package/src/host/mock-server.js +303 -0
- package/src/host/request.js +336 -0
- package/src/host/script-sandbox.js +272 -0
- package/src/host/storage.js +803 -0
- package/src/host/test-runner.js +126 -0
- package/src/host/variables.js +108 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T3 请求服务:契约 §2 postapi.request face,v2 §4 扩展。
|
|
3
|
+
* Node 全局 fetch + AbortController;错误结构化进 error 字段,不抛出。
|
|
4
|
+
* v2 新增:variables({{}} 替换)、preScript / postScript(沙箱)、assertions(内置断言);
|
|
5
|
+
* 返回体新增 request / tests / variables / logs,既有字段与行为不变。
|
|
6
|
+
*/
|
|
7
|
+
import { createVariableResolver } from './variables.js'
|
|
8
|
+
import { runScript } from './script-sandbox.js'
|
|
9
|
+
|
|
10
|
+
const OVER_LIMIT_BYTES = 2 * 1024 * 1024 // >2MB 触发截断
|
|
11
|
+
const KEEP_BYTES = 200 * 1024 // 截断后保留 200KB
|
|
12
|
+
|
|
13
|
+
const BODY_TYPE_CONTENT_TYPE = {
|
|
14
|
+
json: 'application/json',
|
|
15
|
+
form: 'application/x-www-form-urlencoded',
|
|
16
|
+
urlencoded: 'application/x-www-form-urlencoded',
|
|
17
|
+
raw: 'text/plain',
|
|
18
|
+
xml: 'application/xml',
|
|
19
|
+
graphql: 'application/json',
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 既有可用 body 类型(需要序列化并补默认 Content-Type 的)。 */
|
|
23
|
+
const BODY_TYPES = new Set(Object.keys(BODY_TYPE_CONTENT_TYPE))
|
|
24
|
+
|
|
25
|
+
/** header 两种形态归一:对象 {k:v} 与数组 [{key,value,enabled}]。 */
|
|
26
|
+
function headersToObject(input) {
|
|
27
|
+
if (!input) return {}
|
|
28
|
+
if (Array.isArray(input)) {
|
|
29
|
+
const out = {}
|
|
30
|
+
for (const item of input) {
|
|
31
|
+
if (!item || item.enabled === false) continue
|
|
32
|
+
const key = item.key == null ? '' : String(item.key)
|
|
33
|
+
if (key === '') continue
|
|
34
|
+
out[key] = item.value == null ? '' : String(item.value)
|
|
35
|
+
}
|
|
36
|
+
return out
|
|
37
|
+
}
|
|
38
|
+
if (typeof input === 'object') {
|
|
39
|
+
const out = {}
|
|
40
|
+
for (const [k, v] of Object.entries(input)) {
|
|
41
|
+
if (v == null) continue
|
|
42
|
+
out[k] = String(v)
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
return {}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** params 两种形态归一:数组 [{key,value,enabled}] 与对象 {k:v}。 */
|
|
50
|
+
function paramsToList(input) {
|
|
51
|
+
if (!input) return []
|
|
52
|
+
if (Array.isArray(input)) {
|
|
53
|
+
return input
|
|
54
|
+
.filter((p) => p && p.enabled !== false && p.key != null && p.key !== '')
|
|
55
|
+
.map((p) => ({ key: String(p.key), value: p.value == null ? '' : String(p.value) }))
|
|
56
|
+
}
|
|
57
|
+
if (typeof input === 'object') {
|
|
58
|
+
return Object.entries(input).map(([k, v]) => ({ key: String(k), value: v == null ? '' : String(v) }))
|
|
59
|
+
}
|
|
60
|
+
return []
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 'a.b[0].c' 取值;解析失败返回 undefined。 */
|
|
64
|
+
export function pickValue(res, source, path) {
|
|
65
|
+
const src = String(source || 'body')
|
|
66
|
+
const key = path == null ? '' : String(path)
|
|
67
|
+
if (src === 'status') return res.status
|
|
68
|
+
if (src === 'time') return res.timeMs
|
|
69
|
+
if (src === 'header') {
|
|
70
|
+
const headers = res.headers || {}
|
|
71
|
+
const lower = key.toLowerCase()
|
|
72
|
+
for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === lower) return v
|
|
73
|
+
return undefined
|
|
74
|
+
}
|
|
75
|
+
const text = res.body == null ? '' : String(res.body)
|
|
76
|
+
if (key === '') {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(text)
|
|
79
|
+
} catch {
|
|
80
|
+
return text
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
let parsed
|
|
84
|
+
try {
|
|
85
|
+
parsed = JSON.parse(text)
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
const segs = key.replace(/\[(\d+)\]/g, '.$1').split('.').filter((s) => s !== '')
|
|
90
|
+
let cur = parsed
|
|
91
|
+
for (const seg of segs) {
|
|
92
|
+
if (cur == null || typeof cur !== 'object') return undefined
|
|
93
|
+
cur = cur[seg]
|
|
94
|
+
}
|
|
95
|
+
return cur
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 内置断言(契约 §4:source=status|body|header|time,op 共 9 种)。 */
|
|
99
|
+
function evalAssertion(a, res) {
|
|
100
|
+
const item = a && typeof a === 'object' ? a : {}
|
|
101
|
+
const source = String(item.source || 'status')
|
|
102
|
+
const op = String(item.op || 'eq')
|
|
103
|
+
const expected = item.value
|
|
104
|
+
const name = item.message || `${source}${item.path ? ':' + item.path : ''} ${op} ${expected == null ? '' : expected}`.trim()
|
|
105
|
+
const actual = pickValue(res, source, item.path)
|
|
106
|
+
const actualText = actual == null ? '' : typeof actual === 'object' ? JSON.stringify(actual) : String(actual)
|
|
107
|
+
try {
|
|
108
|
+
let cond
|
|
109
|
+
switch (op) {
|
|
110
|
+
case 'eq':
|
|
111
|
+
cond = actualText === String(expected == null ? '' : expected)
|
|
112
|
+
break
|
|
113
|
+
case 'neq':
|
|
114
|
+
cond = actualText !== String(expected == null ? '' : expected)
|
|
115
|
+
break
|
|
116
|
+
case 'gt':
|
|
117
|
+
cond = Number(actualText) > Number(expected)
|
|
118
|
+
break
|
|
119
|
+
case 'lt':
|
|
120
|
+
cond = Number(actualText) < Number(expected)
|
|
121
|
+
break
|
|
122
|
+
case 'contains':
|
|
123
|
+
cond = actualText.includes(String(expected == null ? '' : expected))
|
|
124
|
+
break
|
|
125
|
+
case 'notContains':
|
|
126
|
+
cond = !actualText.includes(String(expected == null ? '' : expected))
|
|
127
|
+
break
|
|
128
|
+
case 'exists':
|
|
129
|
+
cond = actual !== undefined && actual !== null
|
|
130
|
+
break
|
|
131
|
+
case 'notExists':
|
|
132
|
+
cond = actual === undefined || actual === null
|
|
133
|
+
break
|
|
134
|
+
case 'regex':
|
|
135
|
+
cond = new RegExp(String(expected == null ? '' : expected)).test(actualText)
|
|
136
|
+
break
|
|
137
|
+
default:
|
|
138
|
+
return { name, passed: false, error: `unknown op: ${op}` }
|
|
139
|
+
}
|
|
140
|
+
if (cond) return { name, passed: true }
|
|
141
|
+
return { name, passed: false, error: `expected ${actualText === '' ? '(empty)' : actualText} ${op} ${expected == null ? '' : expected}`.trim() }
|
|
142
|
+
} catch (err) {
|
|
143
|
+
return { name, passed: false, error: err && err.message ? err.message : String(err) }
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function createRequestService() {
|
|
148
|
+
return {
|
|
149
|
+
/**
|
|
150
|
+
* send({ method,url,params,headers,body,auth,timeoutMs=30000,
|
|
151
|
+
* variables, preScript, postScript, assertions })
|
|
152
|
+
* → { status,statusText,headers,body,bodySize,timeMs,error?,truncated?,
|
|
153
|
+
* request, tests, variables, logs }
|
|
154
|
+
*/
|
|
155
|
+
async send(options = {}) {
|
|
156
|
+
const {
|
|
157
|
+
method = 'GET',
|
|
158
|
+
url,
|
|
159
|
+
params,
|
|
160
|
+
headers,
|
|
161
|
+
body,
|
|
162
|
+
auth,
|
|
163
|
+
timeoutMs = 30000,
|
|
164
|
+
variables,
|
|
165
|
+
preScript,
|
|
166
|
+
postScript,
|
|
167
|
+
assertions,
|
|
168
|
+
} = options || {}
|
|
169
|
+
const started = Date.now()
|
|
170
|
+
const result = {
|
|
171
|
+
status: 0,
|
|
172
|
+
statusText: '',
|
|
173
|
+
headers: {},
|
|
174
|
+
body: '',
|
|
175
|
+
bodySize: 0,
|
|
176
|
+
timeMs: 0,
|
|
177
|
+
request: { method: String(method || 'GET').toUpperCase(), url: url == null ? '' : String(url), headers: {}, body: '' },
|
|
178
|
+
tests: [],
|
|
179
|
+
variables: {},
|
|
180
|
+
logs: [],
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
if (!url) throw new Error('send: url is required')
|
|
184
|
+
|
|
185
|
+
// ---- 1. 变量替换:{{key}} / {{$dynamic}},未定义保留原文(契约 §4) ----
|
|
186
|
+
const resolver = variables
|
|
187
|
+
? createVariableResolver({
|
|
188
|
+
globals: variables.globals,
|
|
189
|
+
environment: variables.environment,
|
|
190
|
+
local: variables.local,
|
|
191
|
+
})
|
|
192
|
+
: null
|
|
193
|
+
const R = (v) => (resolver ? resolver.resolve(v) : v)
|
|
194
|
+
|
|
195
|
+
let methodValue = String(method || 'GET').toUpperCase()
|
|
196
|
+
let urlValue = R(String(url))
|
|
197
|
+
let paramList = paramsToList(params).map((p) => ({ key: R(p.key), value: R(p.value) }))
|
|
198
|
+
let headerMap = headersToObject(headers)
|
|
199
|
+
for (const k of Object.keys(headerMap)) headerMap[k] = R(headerMap[k])
|
|
200
|
+
let bodyValue = body && typeof body === 'object' ? { ...body } : body
|
|
201
|
+
if (bodyValue && typeof bodyValue === 'object' && bodyValue.content != null) {
|
|
202
|
+
bodyValue = { ...bodyValue, content: R(String(bodyValue.content)) }
|
|
203
|
+
}
|
|
204
|
+
let authValue = auth && typeof auth === 'object' ? { ...auth } : auth
|
|
205
|
+
if (authValue) {
|
|
206
|
+
for (const k of ['token', 'username', 'password', 'key', 'value']) {
|
|
207
|
+
if (authValue[k] != null) authValue[k] = R(String(authValue[k]))
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ---- 2. 前置脚本:可改 request 的 method/url/params/headers/body ----
|
|
212
|
+
const ctxRequest = {
|
|
213
|
+
method: methodValue,
|
|
214
|
+
url: urlValue,
|
|
215
|
+
params: paramList,
|
|
216
|
+
headers: { ...headerMap },
|
|
217
|
+
body: bodyValue,
|
|
218
|
+
}
|
|
219
|
+
if (preScript) {
|
|
220
|
+
const out = runScript(preScript, {
|
|
221
|
+
context: { request: ctxRequest, response: null, env: {}, globals: {}, variables: {} },
|
|
222
|
+
timeoutMs,
|
|
223
|
+
})
|
|
224
|
+
result.logs.push(...out.logs.map((l) => 'pre ' + l))
|
|
225
|
+
Object.assign(result.variables, out.variables)
|
|
226
|
+
if (!out.ok) {
|
|
227
|
+
result.timeMs = Date.now() - started
|
|
228
|
+
result.error = { kind: out.error.kind === 'timeout' ? 'timeout' : 'script', message: `preScript: ${out.error.message}`, phase: 'preScript' }
|
|
229
|
+
return result
|
|
230
|
+
}
|
|
231
|
+
methodValue = String(ctxRequest.method || methodValue).toUpperCase()
|
|
232
|
+
urlValue = String(ctxRequest.url || urlValue)
|
|
233
|
+
paramList = paramsToList(ctxRequest.params)
|
|
234
|
+
headerMap = headersToObject(ctxRequest.headers)
|
|
235
|
+
bodyValue = ctxRequest.body
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const target = new URL(urlValue)
|
|
239
|
+
for (const p of paramList) target.searchParams.set(p.key, p.value)
|
|
240
|
+
|
|
241
|
+
const h = new Headers(headerMap)
|
|
242
|
+
// auth 注入(契约 §2 §4:bearer/basic/apikey)
|
|
243
|
+
if (authValue && authValue.type === 'bearer' && authValue.token) {
|
|
244
|
+
h.set('Authorization', `Bearer ${authValue.token}`)
|
|
245
|
+
} else if (authValue && authValue.type === 'basic') {
|
|
246
|
+
h.set('Authorization', `Basic ${Buffer.from(`${authValue.username || ''}:${authValue.password || ''}`).toString('base64')}`)
|
|
247
|
+
} else if (authValue && authValue.type === 'apikey' && authValue.key) {
|
|
248
|
+
const addTo = String(authValue.addTo || 'header')
|
|
249
|
+
if (addTo === 'query') target.searchParams.set(String(authValue.key), String(authValue.value == null ? '' : authValue.value))
|
|
250
|
+
else h.set(String(authValue.key), String(authValue.value == null ? '' : authValue.value))
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// body 按 type 序列化并补默认 Content-Type(显式 header 优先)
|
|
254
|
+
let payload
|
|
255
|
+
const bodyType = bodyValue && bodyValue.type
|
|
256
|
+
if (BODY_TYPES.has(bodyType)) {
|
|
257
|
+
payload = bodyValue.content == null ? '' : String(bodyValue.content)
|
|
258
|
+
if (!h.has('Content-Type')) h.set('Content-Type', BODY_TYPE_CONTENT_TYPE[bodyType])
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// 实际发出的请求快照(含变量替换后与脚本改动后的值)
|
|
262
|
+
result.request = {
|
|
263
|
+
method: methodValue,
|
|
264
|
+
url: target.toString(),
|
|
265
|
+
headers: Object.fromEntries(h),
|
|
266
|
+
body: payload == null ? '' : String(payload),
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const ac = new AbortController()
|
|
270
|
+
// 计时覆盖到 body 读取完成:下载阶段卡住同样按超时中止
|
|
271
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs)
|
|
272
|
+
let res
|
|
273
|
+
let text
|
|
274
|
+
try {
|
|
275
|
+
res = await fetch(target, {
|
|
276
|
+
method: methodValue,
|
|
277
|
+
headers: h,
|
|
278
|
+
body: payload,
|
|
279
|
+
signal: ac.signal,
|
|
280
|
+
})
|
|
281
|
+
text = await res.text()
|
|
282
|
+
} finally {
|
|
283
|
+
clearTimeout(timer)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const bytes = Buffer.byteLength(text)
|
|
287
|
+
result.status = res.status
|
|
288
|
+
result.statusText = res.statusText
|
|
289
|
+
result.headers = Object.fromEntries(res.headers)
|
|
290
|
+
result.bodySize = bytes
|
|
291
|
+
if (bytes > OVER_LIMIT_BYTES) {
|
|
292
|
+
result.body = text.slice(0, KEEP_BYTES)
|
|
293
|
+
result.truncated = true
|
|
294
|
+
} else {
|
|
295
|
+
result.body = text
|
|
296
|
+
}
|
|
297
|
+
result.timeMs = Date.now() - started
|
|
298
|
+
|
|
299
|
+
// ---- 3. 后置脚本:读 pm.response,可 set 变量 ----
|
|
300
|
+
if (postScript) {
|
|
301
|
+
const out = runScript(postScript, {
|
|
302
|
+
context: {
|
|
303
|
+
request: result.request,
|
|
304
|
+
response: { status: result.status, headers: result.headers, body: result.body, timeMs: result.timeMs },
|
|
305
|
+
env: {},
|
|
306
|
+
globals: {},
|
|
307
|
+
variables: {},
|
|
308
|
+
eventName: 'test',
|
|
309
|
+
},
|
|
310
|
+
timeoutMs,
|
|
311
|
+
})
|
|
312
|
+
result.logs.push(...out.logs.map((l) => 'post ' + l))
|
|
313
|
+
Object.assign(result.variables, out.variables)
|
|
314
|
+
for (const t of out.tests) result.tests.push(t)
|
|
315
|
+
if (!out.ok) {
|
|
316
|
+
result.tests.push({ name: 'postScript 执行', passed: false, error: out.error.message })
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---- 4. 内置断言 ----
|
|
321
|
+
for (const a of Array.isArray(assertions) ? assertions : []) {
|
|
322
|
+
result.tests.push(evalAssertion(a, result))
|
|
323
|
+
}
|
|
324
|
+
return result
|
|
325
|
+
} catch (err) {
|
|
326
|
+
result.timeMs = Date.now() - started
|
|
327
|
+
const aborted = err && (err.name === 'AbortError' || (err.cause && err.cause.name === 'AbortError'))
|
|
328
|
+
result.error = {
|
|
329
|
+
kind: aborted ? 'timeout' : 'network',
|
|
330
|
+
message: err && err.message ? err.message : String(err),
|
|
331
|
+
}
|
|
332
|
+
return result
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
}
|
|
336
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 脚本沙箱:契约 §4 runScript。node:vm 隔离 + pm.* 兼容面。
|
|
3
|
+
* 安全边界:vm 不是进程级安全边界,但「不注入 require/process/fs/global」+
|
|
4
|
+
* codeGeneration.strings=false(禁 eval/new Function)已阻断契约要求的逃逸路径。
|
|
5
|
+
* 超时用 Script.runInContext 的 timeout 中断同步死循环;沙箱内无 setTimeout/setInterval。
|
|
6
|
+
*/
|
|
7
|
+
import vm from 'node:vm'
|
|
8
|
+
|
|
9
|
+
function stringifyArg(v) {
|
|
10
|
+
if (typeof v === 'string') return v
|
|
11
|
+
try {
|
|
12
|
+
const s = JSON.stringify(v)
|
|
13
|
+
return s === undefined ? String(v) : s
|
|
14
|
+
} catch {
|
|
15
|
+
return String(v)
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function deepEqual(a, b) {
|
|
20
|
+
if (a === b) return true
|
|
21
|
+
if (typeof a !== typeof b) return false
|
|
22
|
+
if (a == null || b == null) return false
|
|
23
|
+
if (typeof a !== 'object') return false
|
|
24
|
+
try {
|
|
25
|
+
return JSON.stringify(a) === JSON.stringify(b)
|
|
26
|
+
} catch {
|
|
27
|
+
return false
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function fmtValue(v) {
|
|
32
|
+
if (typeof v === 'string') return JSON.stringify(v)
|
|
33
|
+
try {
|
|
34
|
+
const s = JSON.stringify(v)
|
|
35
|
+
return s === undefined ? String(v) : s
|
|
36
|
+
} catch {
|
|
37
|
+
return String(v)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 链式断言:pm.expect(v).to.eql(x) / .not.include(y) / .be.above(1) / .be.true ... */
|
|
42
|
+
function makeExpect(actual, negate) {
|
|
43
|
+
const check = (cond, msg) => {
|
|
44
|
+
if (negate ? cond : !cond) throw new Error((negate ? 'not: ' : '') + msg)
|
|
45
|
+
}
|
|
46
|
+
const api = {
|
|
47
|
+
eql(v) {
|
|
48
|
+
check(deepEqual(actual, v), `expected ${fmtValue(actual)} to eql ${fmtValue(v)}`)
|
|
49
|
+
return api
|
|
50
|
+
},
|
|
51
|
+
equal(v) {
|
|
52
|
+
check(actual === v, `expected ${fmtValue(actual)} to equal ${fmtValue(v)}`)
|
|
53
|
+
return api
|
|
54
|
+
},
|
|
55
|
+
above(n) {
|
|
56
|
+
check(Number(actual) > Number(n), `expected ${fmtValue(actual)} to be above ${fmtValue(n)}`)
|
|
57
|
+
return api
|
|
58
|
+
},
|
|
59
|
+
below(n) {
|
|
60
|
+
check(Number(actual) < Number(n), `expected ${fmtValue(actual)} to be below ${fmtValue(n)}`)
|
|
61
|
+
return api
|
|
62
|
+
},
|
|
63
|
+
least(n) {
|
|
64
|
+
check(Number(actual) >= Number(n), `expected ${fmtValue(actual)} to be at least ${fmtValue(n)}`)
|
|
65
|
+
return api
|
|
66
|
+
},
|
|
67
|
+
most(n) {
|
|
68
|
+
check(Number(actual) <= Number(n), `expected ${fmtValue(actual)} to be at most ${fmtValue(n)}`)
|
|
69
|
+
return api
|
|
70
|
+
},
|
|
71
|
+
include(v) {
|
|
72
|
+
const hay = actual == null ? '' : String(actual)
|
|
73
|
+
check(hay.includes(String(v)), `expected ${fmtValue(actual)} to include ${fmtValue(v)}`)
|
|
74
|
+
return api
|
|
75
|
+
},
|
|
76
|
+
match(re) {
|
|
77
|
+
check(new RegExp(re).test(actual == null ? '' : String(actual)), `expected ${fmtValue(actual)} to match ${String(re)}`)
|
|
78
|
+
return api
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
api.to = api
|
|
82
|
+
api.be = api
|
|
83
|
+
api.have = api
|
|
84
|
+
api.that = api
|
|
85
|
+
api.is = api
|
|
86
|
+
api.and = api
|
|
87
|
+
api.a = api
|
|
88
|
+
api.an = api
|
|
89
|
+
Object.defineProperty(api, 'not', { get: () => makeExpect(actual, !negate) })
|
|
90
|
+
Object.defineProperty(api, 'true', {
|
|
91
|
+
get: () => {
|
|
92
|
+
check(actual === true, `expected ${fmtValue(actual)} to be true`)
|
|
93
|
+
return api
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
Object.defineProperty(api, 'false', {
|
|
97
|
+
get: () => {
|
|
98
|
+
check(actual === false, `expected ${fmtValue(actual)} to be false`)
|
|
99
|
+
return api
|
|
100
|
+
},
|
|
101
|
+
})
|
|
102
|
+
Object.defineProperty(api, 'ok', {
|
|
103
|
+
get: () => {
|
|
104
|
+
check(!!actual, `expected ${fmtValue(actual)} to be truthy`)
|
|
105
|
+
return api
|
|
106
|
+
},
|
|
107
|
+
})
|
|
108
|
+
Object.defineProperty(api, 'undefined', {
|
|
109
|
+
get: () => {
|
|
110
|
+
check(actual === undefined, `expected ${fmtValue(actual)} to be undefined`)
|
|
111
|
+
return api
|
|
112
|
+
},
|
|
113
|
+
})
|
|
114
|
+
Object.defineProperty(api, 'exist', {
|
|
115
|
+
get: () => {
|
|
116
|
+
check(actual !== undefined && actual !== null, `expected ${fmtValue(actual)} to exist`)
|
|
117
|
+
return api
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
return api
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function plain(value) {
|
|
124
|
+
if (value === undefined) return {}
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(JSON.stringify(value))
|
|
127
|
+
} catch {
|
|
128
|
+
return {}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* runScript(code, { context, timeoutMs = 3000 })
|
|
134
|
+
* context: { request, response, env, globals, variables, eventName }
|
|
135
|
+
* → { ok, error?, logs: [], variables: {}, tests: [], exports: {} }
|
|
136
|
+
* 注意:context.request / env / globals / variables 以引用方式进入沙箱,脚本对它们的修改对调用方可见。
|
|
137
|
+
*/
|
|
138
|
+
export function runScript(code, { context = {}, timeoutMs = 3000 } = {}) {
|
|
139
|
+
const logs = []
|
|
140
|
+
const tests = []
|
|
141
|
+
const collected = {}
|
|
142
|
+
const source = String(code == null ? '' : code)
|
|
143
|
+
const request = context.request && typeof context.request === 'object' ? context.request : {}
|
|
144
|
+
const response = context.response && typeof context.response === 'object' ? context.response : null
|
|
145
|
+
const envObj = context.env && typeof context.env === 'object' ? context.env : {}
|
|
146
|
+
const globalsObj = context.globals && typeof context.globals === 'object' ? context.globals : {}
|
|
147
|
+
const varsObj = context.variables && typeof context.variables === 'object' ? context.variables : {}
|
|
148
|
+
|
|
149
|
+
const makeScope = (target) => ({
|
|
150
|
+
get: (k) => target[String(k)],
|
|
151
|
+
set: (k, v) => {
|
|
152
|
+
target[String(k)] = v
|
|
153
|
+
collected[String(k)] = v
|
|
154
|
+
},
|
|
155
|
+
unset: (k) => {
|
|
156
|
+
delete target[String(k)]
|
|
157
|
+
delete collected[String(k)]
|
|
158
|
+
},
|
|
159
|
+
toObject: () => ({ ...target }),
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
const variablesScope = {
|
|
163
|
+
get: (k) => {
|
|
164
|
+
const key = String(k)
|
|
165
|
+
if (key in varsObj) return varsObj[key]
|
|
166
|
+
if (key in envObj) return envObj[key]
|
|
167
|
+
return globalsObj[key]
|
|
168
|
+
},
|
|
169
|
+
set: (k, v) => {
|
|
170
|
+
varsObj[String(k)] = v
|
|
171
|
+
collected[String(k)] = v
|
|
172
|
+
},
|
|
173
|
+
unset: (k) => {
|
|
174
|
+
delete varsObj[String(k)]
|
|
175
|
+
delete collected[String(k)]
|
|
176
|
+
},
|
|
177
|
+
toObject: () => ({ ...globalsObj, ...envObj, ...varsObj }),
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
let parsedBody
|
|
181
|
+
let bodyParsed = false
|
|
182
|
+
const pmResponse = response
|
|
183
|
+
? {
|
|
184
|
+
get code() {
|
|
185
|
+
return response.status
|
|
186
|
+
},
|
|
187
|
+
get status() {
|
|
188
|
+
return response.status
|
|
189
|
+
},
|
|
190
|
+
get headers() {
|
|
191
|
+
return response.headers || {}
|
|
192
|
+
},
|
|
193
|
+
get responseTime() {
|
|
194
|
+
return response.timeMs
|
|
195
|
+
},
|
|
196
|
+
text: () => (response.body == null ? '' : String(response.body)),
|
|
197
|
+
json: () => {
|
|
198
|
+
if (!bodyParsed) {
|
|
199
|
+
parsedBody = JSON.parse(response.body == null ? '' : String(response.body))
|
|
200
|
+
bodyParsed = true
|
|
201
|
+
}
|
|
202
|
+
return parsedBody
|
|
203
|
+
},
|
|
204
|
+
}
|
|
205
|
+
: {
|
|
206
|
+
get code() {
|
|
207
|
+
return 0
|
|
208
|
+
},
|
|
209
|
+
get headers() {
|
|
210
|
+
return {}
|
|
211
|
+
},
|
|
212
|
+
text: () => '',
|
|
213
|
+
json: () => {
|
|
214
|
+
throw new Error('pm.response is not available: no response yet')
|
|
215
|
+
},
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const pm = {
|
|
219
|
+
test(name, fn) {
|
|
220
|
+
const entry = { name: String(name), passed: false }
|
|
221
|
+
try {
|
|
222
|
+
if (typeof fn === 'function') fn()
|
|
223
|
+
entry.passed = true
|
|
224
|
+
} catch (err) {
|
|
225
|
+
entry.error = err && err.message ? err.message : String(err)
|
|
226
|
+
}
|
|
227
|
+
tests.push(entry)
|
|
228
|
+
return entry
|
|
229
|
+
},
|
|
230
|
+
expect: (v) => makeExpect(v, false),
|
|
231
|
+
environment: makeScope(envObj),
|
|
232
|
+
globals: makeScope(globalsObj),
|
|
233
|
+
variables: variablesScope,
|
|
234
|
+
response: pmResponse,
|
|
235
|
+
request,
|
|
236
|
+
info: { eventName: String(context.eventName || '') },
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const pushLog = (level) => (...args) => logs.push(`${level}: ${args.map(stringifyArg).join(' ')}`)
|
|
240
|
+
const sandbox = {
|
|
241
|
+
pm,
|
|
242
|
+
console: { log: pushLog('log'), info: pushLog('info'), warn: pushLog('warn'), error: pushLog('error'), debug: pushLog('debug') },
|
|
243
|
+
module: { exports: {} },
|
|
244
|
+
exports: null,
|
|
245
|
+
// 明确禁用异步定时器(契约:setTimeout 禁用);不给 require/process/fs/global
|
|
246
|
+
setTimeout: () => {
|
|
247
|
+
throw new Error('setTimeout is not available in script sandbox')
|
|
248
|
+
},
|
|
249
|
+
setInterval: () => {
|
|
250
|
+
throw new Error('setInterval is not available in script sandbox')
|
|
251
|
+
},
|
|
252
|
+
}
|
|
253
|
+
sandbox.exports = sandbox.module.exports
|
|
254
|
+
|
|
255
|
+
const ctx = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } })
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
const script = new vm.Script(source, { filename: 'postapi-script.js' })
|
|
259
|
+
script.runInContext(ctx, { timeout: Math.max(1, Number(timeoutMs) || 3000) })
|
|
260
|
+
return { ok: true, logs, variables: collected, tests, exports: plain(sandbox.module.exports) }
|
|
261
|
+
} catch (err) {
|
|
262
|
+
const isTimeout = err && err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT'
|
|
263
|
+
return {
|
|
264
|
+
ok: false,
|
|
265
|
+
error: { kind: isTimeout ? 'timeout' : 'script', message: err && err.message ? err.message : String(err) },
|
|
266
|
+
logs,
|
|
267
|
+
variables: collected,
|
|
268
|
+
tests,
|
|
269
|
+
exports: plain(sandbox.module.exports),
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|