@stalfh233/omc-cli 0.6.99 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1986 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * frontend-behavior-probe.mjs — 前台行为验证(Playwright)
4
+ *
5
+ * 目标:打开真实 CloudPivot 页面,按场景 JSON 触发并验证
6
+ * 在线 JS 生命周期事件 / 表单按钮 / 视图按钮 / 计算规则 / 字段显隐 / 只读必填
7
+ * 输出:probe-report.json(逐 step、逐断言、控制台、网络、探针数据、dataLinks)+ 可选截图
8
+ * (默认不截图;--screenshots 开启逐步骤截图)。
9
+ * 场景创建/提交数据后,报告末尾打印可直接点开的单据链接 `DATA-LINK <url>`。
10
+ *
11
+ * 与 frontend-acceptance.mjs 的分工:
12
+ * - frontend-acceptance.mjs 验证「写进去的配置在管理端看得见」;
13
+ * - 本脚本验证「配好的东西在运行时真的会动」:事件注册并触发、按钮真的发请求、
14
+ * 计算规则真的算出值、显隐/只读/必填跟着条件变。
15
+ *
16
+ * 用法:
17
+ * node conformance/frontend-behavior-probe.mjs --scenario frontend-scenarios/calc-visibility.json
18
+ * node conformance/frontend-behavior-probe.mjs --self-test
19
+ * node conformance/frontend-behavior-probe.mjs --validate conformance/frontend-scenarios/onlinejs.json
20
+ *
21
+ * 环境变量:
22
+ * BASE_URL 默认 http://10.168.150.248:8088(也可 --base-url)
23
+ * OMC_ENV 凭据条目名,默认 t248(也可 --env)
24
+ * CREDS 凭据文件,默认 /root/.omc-conformance/credentials
25
+ * PW_ROOT 提供 playwright 的 node_modules 目录(默认 npx cache)
26
+ * PW_EXECUTABLE_PATH 浏览器可执行文件,默认 /usr/bin/chromium
27
+ *
28
+ * 退出码:0 全通过 · 1 有断言/步骤失败 · 2 场景配置非法 · 3 harness/浏览器/登录错误。
29
+ */
30
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync } from "node:fs";
31
+ import { createRequire } from "node:module";
32
+ import { resolve, dirname, join, isAbsolute } from "node:path";
33
+ import { tmpdir, homedir } from "node:os";
34
+ import { fileURLToPath } from "node:url";
35
+
36
+ const HERE = dirname(fileURLToPath(import.meta.url));
37
+ const DEFAULT_BASE_URL = "http://10.168.150.248:8088";
38
+ const DEFAULT_OUT = "./frontend-probe-out";
39
+ const DEFAULT_TIMEOUT = 15000;
40
+ const KNOWN_ACTIONS = new Set([
41
+ "goto", "wait", "waitForText", "fill", "select", "check", "uncheck",
42
+ "click", "press", "eval", "screenshot", "dumpProbe", "assert",
43
+ ]);
44
+ const KNOWN_ASSERTS = new Set([
45
+ "valueEquals", "valueMatches", "visible", "hidden", "readonly", "required",
46
+ "textContains", "eventFired", "eventNotFired", "request", "noConsoleErrors",
47
+ "probeLogContains", "eventRegistered",
48
+ ]);
49
+
50
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
51
+ const pad = (n) => String(n).padStart(2, "0");
52
+ const escapeRegex = (text) => String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53
+ const normalizeSpace = (text) => String(text ?? "").replace(/[\s\u00a0\u3000]+/g, " ").trim();
54
+ const sanitize = (text) => String(text ?? "step").replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 60);
55
+
56
+ function truncate(value, max = 400) {
57
+ let text;
58
+ if (typeof value === "string") text = value;
59
+ else {
60
+ try { text = JSON.stringify(value); } catch { text = String(value); }
61
+ }
62
+ if (text == null) text = String(value);
63
+ return text.length > max ? `${text.slice(0, max)}…` : text;
64
+ }
65
+
66
+ // 比较用归一化:去首尾空白 + 去千分位逗号(半角/全角)
67
+ function normalizeComparable(value) {
68
+ let text = String(value ?? "").replace(/[\u00a0\u3000]/g, " ").trim();
69
+ text = text.replace(/(?<=\d),(?=\d{3}(\D|$))/g, "").replace(/(?<=\d),(?=\d{3}(\D|$))/g, "");
70
+ return text.trim();
71
+ }
72
+
73
+ function numericEqual(left, right) {
74
+ if (left === "" || right === "") return false;
75
+ const a = Number(left);
76
+ const b = Number(right);
77
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return false;
78
+ return Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(b));
79
+ }
80
+
81
+ function parseArgs(argv) {
82
+ const options = {
83
+ scenario: null, validate: null, selfTest: false, baseUrl: null, envName: null,
84
+ out: null, failFast: false, headed: false, timeout: null, trace: false,
85
+ // 默认不截图:报告里 screenshots 为 [],失败也不自动截图(除非显式 --screenshots)。
86
+ screenshots: false, help: false,
87
+ };
88
+ const valueOf = (arg, name, index) => {
89
+ if (arg === name) return [argv[index + 1], index + 1];
90
+ return [arg.slice(name.length + 1), index];
91
+ };
92
+ for (let i = 0; i < argv.length; i += 1) {
93
+ const arg = argv[i];
94
+ if (arg === "--help" || arg === "-h") options.help = true;
95
+ else if (arg === "--self-test") options.selfTest = true;
96
+ else if (arg === "--fail-fast") options.failFast = true;
97
+ else if (arg === "--headed") options.headed = true;
98
+ else if (arg === "--trace") options.trace = true;
99
+ else if (arg === "--screenshots") options.screenshots = true;
100
+ // 兼容旧写法:不再出现在 help 里,行为等价于默认(关闭)。
101
+ else if (arg === "--no-screenshots") options.screenshots = false;
102
+ else if (arg === "--scenario" || arg.startsWith("--scenario=")) {
103
+ const [value, next] = valueOf(arg, "--scenario", i); options.scenario = value; i = next;
104
+ } else if (arg === "--validate" || arg.startsWith("--validate=")) {
105
+ const [value, next] = valueOf(arg, "--validate", i); options.validate = value; i = next;
106
+ } else if (arg === "--base-url" || arg.startsWith("--base-url=")) {
107
+ const [value, next] = valueOf(arg, "--base-url", i); options.baseUrl = value; i = next;
108
+ } else if (arg === "--env" || arg.startsWith("--env=")) {
109
+ const [value, next] = valueOf(arg, "--env", i); options.envName = value; i = next;
110
+ } else if (arg === "--out" || arg.startsWith("--out=")) {
111
+ const [value, next] = valueOf(arg, "--out", i); options.out = value; i = next;
112
+ } else if (arg === "--timeout" || arg.startsWith("--timeout=")) {
113
+ const [value, next] = valueOf(arg, "--timeout", i); options.timeout = Number(value); i = next;
114
+ } else {
115
+ console.error(`[probe] 忽略未知参数:${arg}`);
116
+ }
117
+ }
118
+ return options;
119
+ }
120
+
121
+ function printHelp() {
122
+ console.log(`frontend-behavior-probe — CloudPivot 前台行为验证
123
+
124
+ 用法:
125
+ node conformance/frontend-behavior-probe.mjs --scenario <scenario.json> [选项]
126
+ node conformance/frontend-behavior-probe.mjs --self-test
127
+ node conformance/frontend-behavior-probe.mjs --validate <scenario.json>
128
+
129
+ 选项:
130
+ --scenario <path> 场景 JSON 路径
131
+ --base-url <url> CloudPivot 根地址(默认 $BASE_URL 或 ${DEFAULT_BASE_URL})
132
+ --env <name> 凭据条目(默认 $OMC_ENV 或 t248)
133
+ --out <dir> 输出目录(默认 ${DEFAULT_OUT})
134
+ --timeout <ms> 单步默认超时(默认 ${DEFAULT_TIMEOUT})
135
+ --fail-fast 首个失败即停
136
+ --headed 有头浏览器
137
+ --trace 记录 trace.zip
138
+ --screenshots 逐步骤截图(默认关闭;失败也不自动截图)
139
+ --self-test 不连 CloudPivot,用内联 HTML 验证 harness 自身
140
+ --validate <path> 只校验场景配置
141
+
142
+ 动作: goto wait waitForText fill select check uncheck click press eval screenshot dumpProbe assert
143
+ 断言: valueEquals valueMatches visible hidden readonly required textContains
144
+ eventFired eventNotFired eventRegistered request noConsoleErrors probeLogContains
145
+ `);
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // 页面内探针(addInitScript 注入)
150
+ // ---------------------------------------------------------------------------
151
+ /**
152
+ * 安装 window.__omcProbe。
153
+ * 约束:必须完全自包含(会被 toString() 后注入页面),不得引用模块作用域。
154
+ * 所有包装幂等(只包一次)、失败静默,且保留原有行为。
155
+ */
156
+ function omcProbeInstall() {
157
+ if (window.__omcProbe) return;
158
+ const MAX_TEXT = 2000;
159
+ const cut = (value, max) => {
160
+ const limit = typeof max === "number" ? max : MAX_TEXT;
161
+ try {
162
+ let text;
163
+ if (typeof value === "string") text = value;
164
+ else if (value instanceof Error) text = `${value.name}: ${value.message}\n${value.stack || ""}`;
165
+ else if (value && typeof value === "object") {
166
+ try { text = JSON.stringify(value); } catch { text = String(value); }
167
+ } else text = String(value);
168
+ if (text == null) text = String(value);
169
+ return text.length > limit ? text.slice(0, limit) + "…" : text;
170
+ } catch {
171
+ return "[unserializable]";
172
+ }
173
+ };
174
+ const probe = {
175
+ installedAt: Date.now(),
176
+ hooks: [],
177
+ formSeen: false,
178
+ formWrapped: false,
179
+ logs: [],
180
+ errors: [],
181
+ registrations: [],
182
+ events: [],
183
+ requests: [],
184
+ };
185
+ window.__omcProbe = probe;
186
+
187
+ // ---- console:保留原输出,同时入库 ----
188
+ const levels = ["log", "info", "warn", "error", "debug"];
189
+ for (const level of levels) {
190
+ const original = console[level];
191
+ if (typeof original !== "function") continue;
192
+ const wrapped = function () {
193
+ try {
194
+ const args = Array.prototype.slice.call(arguments);
195
+ probe.logs.push({
196
+ level: level,
197
+ at: Date.now(),
198
+ text: cut(args.map((item) => (typeof item === "string" ? item : cut(item, 400))).join(" ")),
199
+ });
200
+ if (probe.logs.length > 2000) probe.logs.splice(0, 500);
201
+ } catch (_) { /* 探针自身不得影响页面 */ }
202
+ return original.apply(this, arguments);
203
+ };
204
+ try { console[level] = wrapped; } catch (_) { /* ignore */ }
205
+ }
206
+
207
+ // ---- fetch ----
208
+ const originalFetch = window.fetch;
209
+ if (typeof originalFetch === "function") {
210
+ window.fetch = function (input, init) {
211
+ const startedAt = Date.now();
212
+ let method = "GET";
213
+ let url = "";
214
+ try {
215
+ method = String((init && init.method) || (input && input.method) || "GET").toUpperCase();
216
+ url = typeof input === "string" ? input : (input && input.url) || String(input);
217
+ } catch (_) { /* ignore */ }
218
+ const record = { source: "fetch", method: method, url: cut(url, 800), startedAt: startedAt, status: null, ms: null };
219
+ probe.requests.push(record);
220
+ if (probe.requests.length > 500) probe.requests.splice(0, 100);
221
+ return originalFetch.apply(this, arguments).then(
222
+ (response) => {
223
+ try { record.status = response.status; record.ms = Date.now() - startedAt; } catch (_) { /* ignore */ }
224
+ return response;
225
+ },
226
+ (error) => {
227
+ try { record.error = cut(error && error.message ? error.message : error, 300); record.ms = Date.now() - startedAt; } catch (_) { /* ignore */ }
228
+ throw error;
229
+ },
230
+ );
231
+ };
232
+ }
233
+
234
+ // ---- XMLHttpRequest ----
235
+ try {
236
+ const XHR = window.XMLHttpRequest;
237
+ if (XHR && XHR.prototype && !XHR.prototype.__omcProbeWrapped) {
238
+ const originalOpen = XHR.prototype.open;
239
+ const originalSend = XHR.prototype.send;
240
+ XHR.prototype.open = function (method, url) {
241
+ try {
242
+ this.__omcProbeMeta = { method: String(method || "GET").toUpperCase(), url: cut(url, 800), startedAt: Date.now() };
243
+ } catch (_) { /* ignore */ }
244
+ return originalOpen.apply(this, arguments);
245
+ };
246
+ XHR.prototype.send = function () {
247
+ try {
248
+ const meta = this.__omcProbeMeta || { method: "GET", url: "", startedAt: Date.now() };
249
+ const record = { source: "xhr", method: meta.method, url: meta.url, startedAt: meta.startedAt, status: null, ms: null };
250
+ probe.requests.push(record);
251
+ if (probe.requests.length > 500) probe.requests.splice(0, 100);
252
+ this.addEventListener("loadend", () => {
253
+ try { record.status = this.status; record.ms = Date.now() - meta.startedAt; } catch (_) { /* ignore */ }
254
+ });
255
+ } catch (_) { /* ignore */ }
256
+ return originalSend.apply(this, arguments);
257
+ };
258
+ XHR.prototype.__omcProbeWrapped = true;
259
+ }
260
+ } catch (_) { /* ignore */ }
261
+
262
+ // ---- form.on 事件探针 ----
263
+ const simplify = (value) => {
264
+ if (value == null || typeof value !== "object") return value;
265
+ if (Array.isArray(value)) return { __array_length: value.length };
266
+ const out = {};
267
+ let count = 0;
268
+ try {
269
+ for (const key of Object.keys(value)) {
270
+ if (count >= 8) break;
271
+ const item = value[key];
272
+ if (typeof item === "function") continue;
273
+ if (item && typeof item === "object") out[key] = Array.isArray(item) ? `[${item.length}]` : "{…}";
274
+ else out[key] = cut(item, 200);
275
+ count += 1;
276
+ }
277
+ } catch (_) { /* ignore */ }
278
+ return out;
279
+ };
280
+
281
+ const wrapForm = (form) => {
282
+ if (!form || typeof form !== "object" || form.__omcProbeWrapped) return false;
283
+ const originalOn = form.on;
284
+ if (typeof originalOn !== "function") return false;
285
+ const wrappedOn = function (event, callback) {
286
+ const name = String(event);
287
+ try {
288
+ probe.registrations.push({
289
+ event: name,
290
+ at: Date.now(),
291
+ hasCallback: typeof callback === "function",
292
+ callbackName: typeof callback === "function" ? cut(callback.name || "(anonymous)", 80) : null,
293
+ });
294
+ if (probe.registrations.length > 500) probe.registrations.splice(0, 100);
295
+ } catch (_) { /* ignore */ }
296
+ if (typeof callback !== "function") {
297
+ try { return originalOn.apply(this, arguments); } catch (error) { throw error; }
298
+ }
299
+ const wrappedCallback = function () {
300
+ try {
301
+ const args = Array.prototype.slice.call(arguments);
302
+ probe.events.push({
303
+ event: name,
304
+ at: Date.now(),
305
+ argsPreview: cut(args.map((item) => simplify(item)), 600),
306
+ });
307
+ if (probe.events.length > 500) probe.events.splice(0, 100);
308
+ } catch (_) { /* ignore */ }
309
+ try {
310
+ return callback.apply(this, arguments);
311
+ } catch (error) {
312
+ try {
313
+ probe.errors.push({
314
+ event: name,
315
+ at: Date.now(),
316
+ message: cut(error && error.message ? error.message : error),
317
+ stack: cut(error && error.stack ? error.stack : "", 1500),
318
+ });
319
+ if (probe.errors.length > 100) probe.errors.splice(0, 20);
320
+ } catch (_) { /* ignore */ }
321
+ throw error;
322
+ }
323
+ };
324
+ try {
325
+ return originalOn.call(this, event, wrappedCallback);
326
+ } catch (error) {
327
+ throw error;
328
+ }
329
+ };
330
+ let assigned = false;
331
+ try {
332
+ form.on = wrappedOn;
333
+ assigned = form.on === wrappedOn;
334
+ } catch (_) { /* ignore */ }
335
+ if (!assigned) {
336
+ try {
337
+ Object.defineProperty(form, "on", { configurable: true, writable: true, value: wrappedOn });
338
+ assigned = form.on === wrappedOn;
339
+ } catch (_) { /* ignore */ }
340
+ }
341
+ if (!assigned) return false;
342
+ try { form.__omcProbeWrapped = true; } catch (_) { /* ignore */ }
343
+ probe.formWrapped = true;
344
+ return true;
345
+ };
346
+
347
+ // 优先挂 window.form 的 setter:平台一赋值就包装,避免漏掉页面初始化阶段的注册。
348
+ try {
349
+ const descriptor = Object.getOwnPropertyDescriptor(window, "form");
350
+ if (!descriptor || descriptor.configurable) {
351
+ let current = descriptor && descriptor.get ? undefined : window.form;
352
+ Object.defineProperty(window, "form", {
353
+ configurable: true,
354
+ enumerable: true,
355
+ get() { return current; },
356
+ set(value) {
357
+ current = value;
358
+ try {
359
+ probe.formSeen = true;
360
+ wrapForm(value);
361
+ } catch (_) { /* ignore */ }
362
+ },
363
+ });
364
+ probe.hooks.push("defineProperty");
365
+ if (current) {
366
+ probe.formSeen = true;
367
+ wrapForm(current);
368
+ }
369
+ }
370
+ } catch (_) { /* ignore */ }
371
+
372
+ // 轮询兜底:早期 10ms(抓住「创建 form → 立刻 form.on(...)」的窗口),
373
+ // 之后 100ms,30s 后降到 500ms 只为跟住 SPA 重建的 form。
374
+ const startedAt = Date.now();
375
+ const tick = () => {
376
+ try {
377
+ const form = window.form;
378
+ if (form) {
379
+ probe.formSeen = true;
380
+ wrapForm(form);
381
+ }
382
+ } catch (_) { /* ignore */ }
383
+ const elapsed = Date.now() - startedAt;
384
+ const delay = elapsed < 5000 ? 10 : elapsed < 30000 ? 100 : 500;
385
+ setTimeout(tick, delay);
386
+ };
387
+ tick();
388
+
389
+ window.__omcProbeDump = function () {
390
+ return {
391
+ installedAt: probe.installedAt,
392
+ hooks: probe.hooks.slice(),
393
+ formSeen: probe.formSeen,
394
+ formWrapped: probe.formWrapped,
395
+ logs: probe.logs.slice(-500),
396
+ errors: probe.errors.slice(-100),
397
+ registrations: probe.registrations.slice(-200),
398
+ events: probe.events.slice(-300),
399
+ requests: probe.requests.slice(-300),
400
+ };
401
+ };
402
+ }
403
+
404
+ const PROBE_SOURCE = `(${omcProbeInstall.toString()})();`;
405
+
406
+ // ---------------------------------------------------------------------------
407
+ // 页面内定位(label/code → 控件容器)
408
+ // ---------------------------------------------------------------------------
409
+ /**
410
+ * 在页面里解析一个「字段」,并把 target/container/label 打上唯一 token 属性,
411
+ * 让 Node 侧用 [data-omc-target="<token>"] 取用(Playwright locator 自动等待)。
412
+ * 定位优先级:selector > code > label > text。
413
+ */
414
+ function resolveTargetInPage(args) {
415
+ const norm = (value) => String(value == null ? "" : value).replace(/[\s\u00a0\u3000]+/g, " ").trim();
416
+ const stripLabel = (value) => norm(value).replace(/^[**\s]+/, "").replace(/[::**\s]+$/, "");
417
+ const isVisible = (el) => {
418
+ try {
419
+ const rect = el.getBoundingClientRect();
420
+ const style = getComputedStyle(el);
421
+ return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" &&
422
+ style.display !== "none" && Number(style.opacity) > 0;
423
+ } catch (_) { return false; }
424
+ };
425
+ const CONTROL = "input:not([type='hidden']), textarea, select, [contenteditable='true']";
426
+
427
+ // 清掉上一轮的标记,避免多个 token 打架
428
+ for (const el of document.querySelectorAll("[data-omc-target], [data-omc-container], [data-omc-label]")) {
429
+ el.removeAttribute("data-omc-target");
430
+ el.removeAttribute("data-omc-container");
431
+ el.removeAttribute("data-omc-label");
432
+ }
433
+ for (const el of document.querySelectorAll("[data-omc-label-text]")) el.removeAttribute("data-omc-label-text");
434
+
435
+ const token = String(args && args.token ? args.token : "omc");
436
+ const findContainer = (start) => {
437
+ // 从父级开始:标签自身(label/.ant-form-item-label)不是字段容器
438
+ let node = start.parentElement || start;
439
+ let controlHit = null;
440
+ for (let depth = 0; depth < 10 && node; depth += 1) {
441
+ const tokens = String(node.className || "").split(/\s+/).filter(Boolean);
442
+ if (node.tagName === "FORM") return node;
443
+ if (tokens.some((name) => name === "ant-form-item" || name === "form-item" || name === "formItem" || name === "form-group")) return node;
444
+ if (!controlHit && tokens.some((name) => name === "ant-form-item-control" || name === "control" || name === "field" || name.indexOf("field-") === 0)) {
445
+ controlHit = node;
446
+ }
447
+ if (node.tagName === "TD" || node.tagName === "TR") return controlHit || node;
448
+ node = node.parentElement;
449
+ }
450
+ return controlHit || start.parentElement || start;
451
+ };
452
+ const pickControl = (root) => {
453
+ if (!root) return null;
454
+ const nodes = Array.prototype.slice.call(root.querySelectorAll(CONTROL));
455
+ return nodes.find(isVisible) || nodes.find((node) => node.type !== "hidden") || nodes[0] || null;
456
+ };
457
+ const markAll = (target, container, labelEl) => {
458
+ if (target) target.setAttribute("data-omc-target", token);
459
+ if (container) container.setAttribute("data-omc-container", token);
460
+ if (labelEl) labelEl.setAttribute("data-omc-label", token);
461
+ if (container && labelEl) container.setAttribute("data-omc-label-text", norm(labelEl.textContent));
462
+ return {
463
+ found: true,
464
+ token: token,
465
+ how: args && args.code ? "code" : args && args.label ? "label" : "text",
466
+ targetTag: target ? target.tagName : null,
467
+ containerTag: container ? container.tagName : null,
468
+ text: norm(target ? (target.innerText != null ? target.innerText : target.value) : "").slice(0, 120),
469
+ hasControl: !!(container && container.querySelector(CONTROL)),
470
+ };
471
+ };
472
+
473
+ // ---- code ----
474
+ if (args && args.code) {
475
+ const code = String(args.code);
476
+ const quoted = code.replace(/["\\]/g, "\\$&");
477
+ const candidates = Array.prototype.slice.call(document.querySelectorAll(
478
+ `[data-code="${quoted}"], [data-field-code="${quoted}"], [data-field="${quoted}"], ` +
479
+ `[data-property-code="${quoted}"], [name="${quoted}"], [id="${quoted}"]`,
480
+ ));
481
+ for (const candidate of candidates) {
482
+ const isControl = candidate.matches(CONTROL) || candidate.matches("input, textarea, select");
483
+ const container = isControl ? findContainer(candidate) : candidate;
484
+ let target = isControl ? candidate : pickControl(container);
485
+ if (!target) target = container;
486
+ const labelEl = container && container.querySelector(".ant-form-item-label, label, [data-omc-label], [class*='label']");
487
+ return markAll(target, container, labelEl);
488
+ }
489
+ return { found: false, token: token, how: "code", reason: `未找到 code=${code}(试过 [data-code]/[data-field-code]/[data-field]/[name]/[id])` };
490
+ }
491
+
492
+ // ---- label ----
493
+ if (args && args.label) {
494
+ const wanted = stripLabel(args.label).toLowerCase();
495
+ const ownText = (el) => {
496
+ let text = "";
497
+ for (const node of el.childNodes) {
498
+ if (node.nodeType === 3) text += node.nodeValue;
499
+ else if (node.nodeType === 1 && /^(SPAN|I|B|EM|STRONG|SUP|SMALL|FONT|LABEL|CODE|ABBR)$/.test(node.tagName)) text += node.textContent;
500
+ }
501
+ return norm(text);
502
+ };
503
+ const pool = Array.prototype.slice.call(document.querySelectorAll("label, .ant-form-item-label, [class*='label'], [class*='title'], td, th, span, div, p, dt, dd"));
504
+ const exact = [];
505
+ const loose = [];
506
+ for (const el of pool) {
507
+ // 含输入控件/控件容器的元素是「字段行」而不是标签(label 包着 input 除外)
508
+ if (el.tagName !== "LABEL" && el.querySelector("input, textarea, select, [contenteditable='true'], .ant-form-item-control, [class*='control']")) continue;
509
+ const own = stripLabel(ownText(el)).toLowerCase();
510
+ if (!own) continue;
511
+ if (own === wanted) exact.push(el);
512
+ else if (own.indexOf(wanted) === 0 && own.length <= wanted.length + 8) loose.push(el);
513
+ }
514
+ const tryCandidates = (list, requireControl) => {
515
+ for (const candidate of list) {
516
+ const container = findContainer(candidate);
517
+ if (!container || container === candidate) continue;
518
+ const control = pickControl(container);
519
+ // 第一轮只认有控件的容器(真正可填的字段),第二轮接受只读展示容器
520
+ if (requireControl && !control && !container.matches("td, tr")) continue;
521
+ return markAll(control || container, container, candidate);
522
+ }
523
+ return null;
524
+ };
525
+ const hit = tryCandidates(exact, true) || tryCandidates(exact, false) ||
526
+ tryCandidates(loose, true) || tryCandidates(loose, false);
527
+ if (hit) return hit;
528
+ // 兜底:文本包含 + 能在这块区域里找到控件
529
+ for (const candidate of pool) {
530
+ if (norm(candidate.textContent).indexOf(args.label) === -1) continue;
531
+ if (candidate.querySelectorAll("*").length > 40) continue;
532
+ const container = findContainer(candidate);
533
+ const control = pickControl(container);
534
+ if (control) return markAll(control, container, candidate);
535
+ }
536
+ return { found: false, token: token, how: "label", reason: `未找到显示名「${args.label}」的字段(已按去必填星号/冒号/i18n 归一化匹配)` };
537
+ }
538
+
539
+ // ---- text ----
540
+ if (args && args.text) {
541
+ const wanted = norm(args.text);
542
+ const pool = Array.prototype.slice.call(document.querySelectorAll("button, a, li, span, div, td, th, label, p, h1, h2, h3, h4"));
543
+ const found = pool.find((el) => norm(el.innerText) === wanted) ||
544
+ pool.find((el) => norm(el.innerText).indexOf(wanted) !== -1 && el.querySelectorAll("*").length < 20);
545
+ if (!found) return { found: false, token: token, how: "text", reason: `未找到文本「${args.text}」` };
546
+ return markAll(found, findContainer(found), null);
547
+ }
548
+
549
+ return { found: false, token: token, how: "none", reason: "缺少定位信息(selector/code/label/text)" };
550
+ }
551
+
552
+ /** 读取字段当前值:input.value / textarea.value / .value / .items / 只读文本。 */
553
+ function readValueInPage(el) {
554
+ const norm = (value) => String(value == null ? "" : value).replace(/[\s\u00a0\u3000]+/g, " ").trim();
555
+ if (!el) return "";
556
+ if (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") return String(el.value == null ? "" : el.value);
557
+ if (el.isContentEditable) return norm(el.innerText);
558
+ if (typeof el.value === "string" && el.value !== "") return el.value;
559
+ if (Array.isArray(el.items)) {
560
+ const parts = el.items.map((item) => (typeof item === "string" ? item : (item && (item.name || item.text || item.label)) || ""));
561
+ const joined = parts.filter(Boolean).join(",");
562
+ if (joined) return joined;
563
+ }
564
+ const labelText = el.getAttribute("data-omc-label-text") || "";
565
+ let text = norm(el.innerText != null ? el.innerText : el.textContent);
566
+ if (labelText) {
567
+ const label = norm(labelText);
568
+ if (label) text = norm(text.replace(label, " "));
569
+ }
570
+ return text;
571
+ }
572
+
573
+ /** 读取 readonly/required/disabled 状态(同时看控件、容器 class、标签星号)。 */
574
+ function inspectStateInPage(el) {
575
+ const norm = (value) => String(value == null ? "" : value).replace(/[\s\u00a0\u3000]+/g, " ").trim();
576
+ const container = el.closest("[data-omc-container]") ||
577
+ el.closest(".ant-form-item, [class*='form-item'], [class*='control']") || el.parentElement || el;
578
+ const control = el.matches("input, textarea, select, [contenteditable='true']")
579
+ ? el
580
+ : container.querySelector("input, textarea, select, [contenteditable='true']");
581
+ const classes = `${String(container.className || "")} ${String(el.className || "")}`;
582
+ const labelEl = container.querySelector("[data-omc-label], label, .ant-form-item-label, [class*='label']");
583
+ const labelText = norm(labelEl ? labelEl.textContent : "");
584
+ const labelClasses = String((labelEl && labelEl.className) || "");
585
+ // CloudPivot 的只读/必填标记不总在容器或 label 上:只读渲染会把输入控件换成
586
+ // 纯文本,标记落在子节点 `field__control__readonly` / `readonly-render`;
587
+ // 必填标记也可能在子节点 class。只扫容器自身会把这些字段误判成可编辑/非必填
588
+ //(真机 1.1.25:readonlyFormula:true 的字段 input 不存在,只读 class 在
589
+ // .field__control 上)。
590
+ const descendantReadonly = container.querySelector(
591
+ "[class*='readonly'], [class*='read-only'], [class*='is-readonly'], [class*='disabled']",
592
+ );
593
+ const descendantRequired = container.querySelector("[class*='required'], [class*='is-required']");
594
+ const disabled = !!(control && (control.disabled || control.getAttribute("aria-disabled") === "true")) ||
595
+ /(^|\s)(disabled|is-disabled|ant-input-disabled)(\s|$)/.test(classes);
596
+ const readonly = disabled ||
597
+ !!(control && (control.readOnly || control.hasAttribute("readonly"))) ||
598
+ /(^|\s)(readonly|is-readonly|ant-input-readonly|ant-select-disabled)(\s|$)/.test(classes) ||
599
+ descendantReadonly !== null;
600
+ const required = !!(
601
+ (control && (control.required || control.getAttribute("aria-required") === "true")) ||
602
+ /(^|\s)(ant-form-item-required|is-required|required)(\s|$)/.test(classes) ||
603
+ /(^|\s)(ant-form-item-required|required)(\s|$)/.test(labelClasses) ||
604
+ descendantRequired !== null ||
605
+ /^[**]/.test(labelText)
606
+ );
607
+ return {
608
+ disabled: disabled,
609
+ readonly: readonly,
610
+ required: required,
611
+ labelText: labelText.slice(0, 80),
612
+ controlTag: control ? control.tagName : null,
613
+ classes: classes.slice(0, 200),
614
+ };
615
+ }
616
+
617
+ // ---------------------------------------------------------------------------
618
+ // 场景加载与校验
619
+ // ---------------------------------------------------------------------------
620
+ function resolveInputPath(input) {
621
+ if (!input) return input;
622
+ if (isAbsolute(input)) return input;
623
+ const candidates = [
624
+ resolve(process.cwd(), input),
625
+ resolve(HERE, input),
626
+ resolve(HERE, "frontend-scenarios", input.replace(/^.*frontend-scenarios[\\/]/, "")),
627
+ resolve(HERE, "..", input),
628
+ ];
629
+ return candidates.find((candidate) => existsSync(candidate)) ?? resolve(process.cwd(), input);
630
+ }
631
+
632
+ function loadScenario(filePath) {
633
+ let raw;
634
+ try {
635
+ raw = readFileSync(filePath, "utf8");
636
+ } catch (error) {
637
+ throw new Error(`读不到场景文件 ${filePath}:${error.message}`);
638
+ }
639
+ try {
640
+ return JSON.parse(raw);
641
+ } catch (error) {
642
+ throw new Error(`场景文件不是合法 JSON(${filePath}):${error.message}`);
643
+ }
644
+ }
645
+
646
+ const hasTarget = (step) => Boolean(step.selector || step.code || step.label);
647
+
648
+ function validateScenario(scenario, filePath = "<scenario>") {
649
+ const errors = [];
650
+ if (!scenario || typeof scenario !== "object" || Array.isArray(scenario)) {
651
+ return [`${filePath}: 顶层必须是 JSON 对象`];
652
+ }
653
+ if (typeof scenario.name !== "string" || !scenario.name.trim()) errors.push("缺少 name(字符串)");
654
+ if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) errors.push("steps 必须是非空数组");
655
+ if (scenario.ignoreConsole != null && !Array.isArray(scenario.ignoreConsole)) errors.push("ignoreConsole 必须是字符串数组");
656
+ // 可选:顶层 schemaCode/sheetCode 用于拼 DATA-LINK;sheetCode 缺省等于 schemaCode。
657
+ for (const key of ["schemaCode", "sheetCode"]) {
658
+ if (scenario[key] != null && (typeof scenario[key] !== "string" || !scenario[key].trim())) {
659
+ errors.push(`${key} 必须是非空字符串`);
660
+ }
661
+ }
662
+
663
+ (Array.isArray(scenario.steps) ? scenario.steps : []).forEach((step, index) => {
664
+ const where = `step#${index}`;
665
+ if (!step || typeof step !== "object") { errors.push(`${where}: 必须是对象`); return; }
666
+ if (!KNOWN_ACTIONS.has(step.action)) { errors.push(`${where}: 未知 action「${step.action}」`); return; }
667
+ if (step.optional != null && typeof step.optional !== "boolean") errors.push(`${where}: optional 必须是布尔值`);
668
+
669
+ switch (step.action) {
670
+ case "goto":
671
+ if (typeof step.path !== "string" && typeof step.url !== "string") errors.push(`${where}: goto 需要 path`);
672
+ break;
673
+ case "wait":
674
+ if (step.ms != null && !Number.isFinite(step.ms)) errors.push(`${where}: wait.ms 必须是数字`);
675
+ break;
676
+ case "waitForText":
677
+ if (typeof step.text !== "string" || !step.text) errors.push(`${where}: waitForText 需要 text`);
678
+ break;
679
+ case "fill":
680
+ if (!hasTarget(step)) errors.push(`${where}: fill 需要 selector/code/label 之一`);
681
+ if (step.value == null) errors.push(`${where}: fill 需要 value`);
682
+ break;
683
+ case "select":
684
+ if (!hasTarget(step)) errors.push(`${where}: select 需要 selector/code/label 之一`);
685
+ if (step.value == null) errors.push(`${where}: select 需要 value`);
686
+ break;
687
+ case "check":
688
+ case "uncheck":
689
+ if (!hasTarget(step) && typeof step.text !== "string") errors.push(`${where}: ${step.action} 需要 selector/code/label(或 text)`);
690
+ break;
691
+ case "click":
692
+ if (!hasTarget(step) && typeof step.text !== "string") errors.push(`${where}: click 需要 selector/code/label/text 之一`);
693
+ break;
694
+ case "press":
695
+ if (typeof step.key !== "string" || !step.key) errors.push(`${where}: press 需要 key`);
696
+ break;
697
+ case "eval":
698
+ if (typeof step.script !== "string" || !step.script) errors.push(`${where}: eval 需要 script 字符串`);
699
+ break;
700
+ case "screenshot":
701
+ if (step.name != null && typeof step.name !== "string") errors.push(`${where}: screenshot.name 必须是字符串`);
702
+ break;
703
+ case "assert": {
704
+ if (!KNOWN_ASSERTS.has(step.kind)) { errors.push(`${where}: 未知断言 kind「${step.kind}」`); break; }
705
+ const needsTarget = ["valueEquals", "valueMatches", "readonly", "required"];
706
+ if (needsTarget.includes(step.kind) && !hasTarget(step)) errors.push(`${where}: ${step.kind} 需要 selector/code/label 之一`);
707
+ if (["visible", "hidden"].includes(step.kind) && !hasTarget(step) && typeof step.text !== "string") {
708
+ errors.push(`${where}: ${step.kind} 需要 selector/code/label/text 之一`);
709
+ }
710
+ if (step.kind === "valueEquals" && step.expected == null) errors.push(`${where}: valueEquals 需要 expected`);
711
+ if (step.kind === "valueMatches" && step.expected == null && step.regex == null) errors.push(`${where}: valueMatches 需要 expected(正则源)`);
712
+ if (step.kind === "textContains" && typeof step.expected !== "string") errors.push(`${where}: textContains 需要 expected(子串)`);
713
+ if (["eventFired", "eventNotFired", "eventRegistered"].includes(step.kind) && (typeof step.event !== "string" || !step.event)) {
714
+ errors.push(`${where}: ${step.kind} 需要 event`);
715
+ }
716
+ if (step.kind === "request" && typeof step.path !== "string") errors.push(`${where}: request 需要 path(URL 子串或正则源)`);
717
+ if (step.kind === "probeLogContains" && typeof step.text !== "string" && typeof step.expected !== "string") {
718
+ errors.push(`${where}: probeLogContains 需要 text 或 expected(日志子串)`);
719
+ }
720
+ break;
721
+ }
722
+ default:
723
+ break;
724
+ }
725
+ });
726
+ return errors;
727
+ }
728
+
729
+ // ---------------------------------------------------------------------------
730
+ // Playwright 会话
731
+ // ---------------------------------------------------------------------------
732
+ /** `omc frontend setup` 把 playwright-core 装到这里(与 CLI 共用同一路径)。 */
733
+ export const OMC_FRONTEND_CACHE = join(homedir(), ".omc", "frontend-probe");
734
+
735
+ let playwrightModule = null;
736
+ function loadPlaywright() {
737
+ if (playwrightModule) return playwrightModule;
738
+ const roots = [
739
+ process.env.PW_ROOT,
740
+ join(OMC_FRONTEND_CACHE, "node_modules"),
741
+ "/root/.npm/_npx/e41f203b7505f1fb/node_modules",
742
+ ].filter((root) => typeof root === "string" && root.length > 0);
743
+ const failures = [];
744
+ for (const root of roots) {
745
+ const requireFrom = createRequire(root.endsWith("/") ? root : `${root}/`);
746
+ for (const name of ["playwright", "playwright-core"]) {
747
+ try {
748
+ playwrightModule = requireFrom(name);
749
+ return playwrightModule;
750
+ } catch (error) {
751
+ failures.push(`${root} → ${name}: ${truncate(error?.message ?? String(error), 120)}`);
752
+ }
753
+ }
754
+ }
755
+ throw new Error(
756
+ "未找到 Playwright(playwright / playwright-core)。运行 `omc frontend setup` 一次性安装到 " +
757
+ `${OMC_FRONTEND_CACHE},或设置 PW_ROOT 指向已有 node_modules。已尝试:\n${failures.join("\n")}`,
758
+ );
759
+ }
760
+
761
+ /** 浏览器可执行文件:env 优先,其次常见系统路径;找不到给可执行指引。 */
762
+ function findBrowserExecutable() {
763
+ const explicit = process.env.PW_EXECUTABLE_PATH ?? process.env.CHROME_PATH ?? process.env.PUPPETEER_EXECUTABLE_PATH;
764
+ if (explicit) {
765
+ if (!existsSync(explicit)) throw new Error(`PW_EXECUTABLE_PATH/CHROME_PATH 指向的文件不存在:${explicit}`);
766
+ return explicit;
767
+ }
768
+ const candidates = [
769
+ "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome",
770
+ "/usr/bin/google-chrome-stable", "/opt/google/chrome/chrome", "/snap/bin/chromium",
771
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
772
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
773
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
774
+ ];
775
+ const hit = candidates.find((candidate) => existsSync(candidate));
776
+ if (hit) return hit;
777
+ throw new Error("未找到 Chromium/Chrome:安装系统浏览器,或设置 PW_EXECUTABLE_PATH 指向可执行文件(`omc frontend setup --check` 可诊断)");
778
+ }
779
+
780
+ async function launchBrowser(options) {
781
+ const { chromium } = loadPlaywright();
782
+ return chromium.launch({
783
+ executablePath: findBrowserExecutable(),
784
+ args: ["--no-sandbox"],
785
+ headless: !options.headed,
786
+ });
787
+ }
788
+
789
+ async function openSession({ browser, options, scenario, viewport }) {
790
+ const context = await browser.newContext({ viewport: viewport ?? { width: 1600, height: 1000 } });
791
+ await context.addInitScript({ content: PROBE_SOURCE });
792
+ context.setDefaultTimeout(options.timeout ?? DEFAULT_TIMEOUT);
793
+ if (options.trace) await context.tracing.start({ screenshots: true, snapshots: true, sources: false });
794
+ const page = await context.newPage();
795
+ const session = {
796
+ browser: browser,
797
+ context: context,
798
+ page: page,
799
+ network: [],
800
+ pendingBodies: new Set(),
801
+ console: [],
802
+ pageErrors: [],
803
+ consoleBaseline: 0,
804
+ pageErrorBaseline: 0,
805
+ screenshots: [],
806
+ dataLinks: [],
807
+ windowStartAt: Date.now(),
808
+ options: options,
809
+ scenario: scenario,
810
+ };
811
+ attachObservers(session);
812
+ return session;
813
+ }
814
+
815
+ // ---------------------------------------------------------------------------
816
+ // DATA-LINK:写请求响应里抓业务对象 id,拼成可直接点开的单据链接
817
+ // ---------------------------------------------------------------------------
818
+ const DATA_LINK_PATHS = ["/runtime/form/save", "/runtime/form/submit", "/data/save", "/data/submit", "/data/update"];
819
+
820
+ const asId = (value) =>
821
+ typeof value === "string" && value ? value
822
+ : typeof value === "number" && Number.isFinite(value) ? String(value)
823
+ : null;
824
+
825
+ function pickObjectId(value) {
826
+ if (!value || typeof value !== "object") return null;
827
+ return asId(value.id) ?? asId(value.bizObjectId) ?? asId(value.objectId);
828
+ }
829
+
830
+ /** 从响应 body 的 `data` 取新建/更新对象 id:data.id / bizObjectId / objectId / data.data.id / 数组首项。 */
831
+ function extractDataObjectId(body) {
832
+ let node = body && typeof body === "object" ? body.data : undefined;
833
+ for (let depth = 0; node != null && depth < 4; depth += 1) {
834
+ if (typeof node === "string") {
835
+ try { node = JSON.parse(node); } catch { return null; }
836
+ }
837
+ if (Array.isArray(node)) node = node[0];
838
+ if (!node || typeof node !== "object") return null;
839
+ const id = pickObjectId(node);
840
+ if (id) return id;
841
+ node = node.data;
842
+ }
843
+ return null;
844
+ }
845
+
846
+ function readSchemaCodeFromRequest(request, url) {
847
+ try {
848
+ const parsed = new URL(url);
849
+ for (const key of ["schemaCode", "schema", "modelCode"]) {
850
+ const value = parsed.searchParams.get(key);
851
+ if (value) return value;
852
+ }
853
+ } catch { /* 非绝对 URL 忽略 */ }
854
+ let post = null;
855
+ try { post = request.postData(); } catch { return null; }
856
+ if (!post) return null;
857
+ const fromObject = (value, depth = 0) => {
858
+ if (!value || typeof value !== "object" || depth > 3) return null;
859
+ for (const key of ["schemaCode", "schema", "modelCode"]) {
860
+ if (typeof value[key] === "string" && value[key]) return value[key];
861
+ }
862
+ for (const key of ["data", "formData", "params", "payload"]) {
863
+ const hit = fromObject(value[key], depth + 1);
864
+ if (hit) return hit;
865
+ }
866
+ return null;
867
+ };
868
+ try { return fromObject(JSON.parse(post)); } catch { /* 不是 JSON */ }
869
+ try {
870
+ const params = new URLSearchParams(post);
871
+ for (const key of ["schemaCode", "schema", "modelCode"]) {
872
+ const value = params.get(key);
873
+ if (value) return value;
874
+ }
875
+ } catch { /* ignore */ }
876
+ return null;
877
+ }
878
+
879
+ function recordDataLink(session, entry, body, request) {
880
+ if (!DATA_LINK_PATHS.some((path) => entry.url.includes(path))) return;
881
+ if (entry.status >= 400) return;
882
+ const errcode = body?.errcode ?? body?.errorCode ?? body?.errCode;
883
+ if (errcode != null && Number(errcode) !== 0) return;
884
+ const objectId = extractDataObjectId(body);
885
+ if (!objectId) return;
886
+ const schemaCode = readSchemaCodeFromRequest(request, entry.url) ?? session.scenario?.schemaCode;
887
+ if (!schemaCode) return;
888
+ const sheetCode = session.scenario?.sheetCode ?? schemaCode;
889
+ const duplicate = session.dataLinks.some((link) =>
890
+ link.objectId === objectId && link.schemaCode === schemaCode && link.sheetCode === sheetCode);
891
+ if (duplicate) return;
892
+ const url = `${session.baseUrl}/form/detail?schemaCode=${encodeURIComponent(schemaCode)}`
893
+ + `&sheetCode=${encodeURIComponent(sheetCode)}&objectId=${encodeURIComponent(objectId)}&isWorkFlow=false`;
894
+ session.dataLinks.push({
895
+ schemaCode: schemaCode,
896
+ sheetCode: sheetCode,
897
+ objectId: objectId,
898
+ url: url,
899
+ source: entry.url,
900
+ at: new Date().toISOString(),
901
+ });
902
+ }
903
+
904
+ function attachObservers(session) {
905
+ const page = session.page;
906
+ const requestStarts = new WeakMap();
907
+ page.on("request", (request) => requestStarts.set(request, Date.now()));
908
+
909
+ page.on("response", (response) => {
910
+ let url;
911
+ try { url = response.url(); } catch { return; }
912
+ if (!url.includes("/api/")) return;
913
+ const request = response.request();
914
+ const startedAt = requestStarts.get(request) ?? Date.now();
915
+ const entry = {
916
+ method: request.method(),
917
+ url: truncate(url, 600),
918
+ status: response.status(),
919
+ ms: Date.now() - startedAt,
920
+ at: Date.now(),
921
+ errcode: null,
922
+ errmsg: null,
923
+ bodyPreview: null,
924
+ done: false,
925
+ };
926
+ session.network.push(entry);
927
+ if (session.network.length > 1000) session.network.splice(0, 200);
928
+ const task = (async () => {
929
+ try {
930
+ const length = Number(response.headers()["content-length"] ?? 0);
931
+ if (length && length > 65536) { entry.bodyPreview = `<skipped ${length} bytes>`; return; }
932
+ const text = await response.text();
933
+ if (!text) return;
934
+ entry.bodyPreview = truncate(text, 400);
935
+ try {
936
+ const body = JSON.parse(text);
937
+ const code = body?.errcode ?? body?.errorCode ?? body?.errCode ?? body?.code ?? body?.error?.errcode;
938
+ const message = body?.errmsg ?? body?.message ?? body?.error?.message ?? body?.error?.errmsg;
939
+ if (code != null && Number.isFinite(Number(code))) entry.errcode = Number(code);
940
+ if (message != null) entry.errmsg = truncate(String(message), 200);
941
+ recordDataLink(session, entry, body, request);
942
+ } catch { /* 非 JSON 响应忽略 body */ }
943
+ } catch (error) {
944
+ entry.bodyPreview = `<unreadable ${truncate(error?.message ?? String(error), 120)}>`;
945
+ } finally {
946
+ entry.done = true;
947
+ }
948
+ })();
949
+ session.pendingBodies.add(task);
950
+ task.finally(() => session.pendingBodies.delete(task));
951
+ });
952
+
953
+ page.on("console", (message) => {
954
+ const entry = {
955
+ type: message.type(),
956
+ text: truncate(message.text(), 1000),
957
+ at: Date.now(),
958
+ url: truncate(page.url(), 300),
959
+ };
960
+ session.console.push(entry);
961
+ if (session.console.length > 1500) session.console.splice(0, 300);
962
+ });
963
+
964
+ page.on("pageerror", (error) => {
965
+ session.pageErrors.push({
966
+ message: truncate(error?.message ?? String(error), 800),
967
+ stack: truncate(error?.stack ?? "", 1500),
968
+ at: Date.now(),
969
+ });
970
+ if (session.pageErrors.length > 200) session.pageErrors.splice(0, 50);
971
+ });
972
+ }
973
+
974
+ async function drainNetwork(session) {
975
+ const tasks = Array.from(session.pendingBodies);
976
+ if (tasks.length) await Promise.allSettled(tasks);
977
+ }
978
+
979
+ async function login(session, baseUrl, options) {
980
+ const envName = options.envName ?? process.env.OMC_ENV ?? "t248";
981
+ // `omc frontend probe` 直接从配置根读凭据后以环境变量注入(不落盘);手跑时
982
+ // 仍可用 CREDS 文件。两者都没有才报错。
983
+ let creds = process.env.OMC_PROBE_USERNAME && process.env.OMC_PROBE_PASSWORD
984
+ ? { username: process.env.OMC_PROBE_USERNAME, password: process.env.OMC_PROBE_PASSWORD }
985
+ : undefined;
986
+ if (!creds) {
987
+ const credsPath = process.env.CREDS ?? "/root/.omc-conformance/credentials";
988
+ if (!existsSync(credsPath)) throw new Error(`凭据文件不存在:${credsPath}(可用 CREDS 指定,或场景里设 "login": false;omc frontend probe 会从环境配置读凭据)`);
989
+ let all;
990
+ try {
991
+ all = JSON.parse(readFileSync(credsPath, "utf8"));
992
+ } catch (error) {
993
+ throw new Error(`凭据文件不是合法 JSON:${credsPath}(${error.message})`);
994
+ }
995
+ creds = all[envName];
996
+ if (!creds || !creds.username || !creds.password) {
997
+ throw new Error(`凭据文件缺少环境「${envName}」的 username/password(已有:${Object.keys(all).join(", ")})`);
998
+ }
999
+ }
1000
+ const page = session.page;
1001
+ try {
1002
+ await page.goto(`${baseUrl}/login`, { waitUntil: "domcontentloaded", timeout: options.timeout });
1003
+ await page.getByPlaceholder(/account number/i).fill(creds.username, { timeout: options.timeout });
1004
+ await page.getByPlaceholder(/password/i).fill(creds.password, { timeout: options.timeout });
1005
+ await page.getByPlaceholder(/password/i).press("Enter");
1006
+ await page.waitForURL(/portal-page|admin/, { timeout: Math.max(45000, options.timeout) });
1007
+ } catch (error) {
1008
+ throw new Error(`登录失败(用户 ${creds.username} @ ${baseUrl}):${truncate(error?.message ?? String(error), 300)}`);
1009
+ }
1010
+ // 登录页自身的控制台噪声不计入场景断言
1011
+ session.consoleBaseline = session.console.length;
1012
+ session.pageErrorBaseline = session.pageErrors.length;
1013
+ }
1014
+
1015
+ // ---------------------------------------------------------------------------
1016
+ // 定位与动作
1017
+ // ---------------------------------------------------------------------------
1018
+ function targetDescription(step) {
1019
+ if (step.selector) return `selector=${step.selector}`;
1020
+ if (step.code) return `code=${step.code}`;
1021
+ if (step.label) return `label=「${step.label}」`;
1022
+ if (step.text) return `text=「${step.text}」`;
1023
+ return "(无定位)";
1024
+ }
1025
+
1026
+ async function locate(session, step, token) {
1027
+ const page = session.page;
1028
+ if (step.selector) {
1029
+ const locator = page.locator(step.selector).first();
1030
+ return { locator: locator, container: locator, missing: false, how: "selector", info: { how: "selector", selector: step.selector } };
1031
+ }
1032
+ let descriptor = null;
1033
+ try {
1034
+ descriptor = await page.evaluate(resolveTargetInPage, {
1035
+ label: step.label ?? null,
1036
+ code: step.code ?? null,
1037
+ text: step.text ?? null,
1038
+ token: token,
1039
+ });
1040
+ } catch (error) {
1041
+ descriptor = { found: false, reason: `定位时页面异常:${truncate(error?.message ?? String(error), 200)}` };
1042
+ }
1043
+ const locator = page.locator(`[data-omc-target="${token}"]`).first();
1044
+ const container = page.locator(`[data-omc-container="${token}"]`).first();
1045
+ if (!descriptor || !descriptor.found) {
1046
+ return { locator: locator, container: container, missing: true, how: descriptor?.how ?? "unknown", info: descriptor ?? {} };
1047
+ }
1048
+ return { locator: locator, container: container, missing: false, how: descriptor.how, info: descriptor };
1049
+ }
1050
+
1051
+ async function waitForTextInPage(page, text, timeoutMs, isRegex = false) {
1052
+ const deadline = Date.now() + timeoutMs;
1053
+ const wanted = normalizeSpace(text);
1054
+ let last = "";
1055
+ while (true) {
1056
+ last = await page.locator("body").innerText().catch(() => "");
1057
+ const haystack = normalizeSpace(last);
1058
+ const hit = isRegex ? new RegExp(text).test(last) : haystack.includes(wanted);
1059
+ if (hit) return { found: true, waitedMs: timeoutMs - Math.max(0, deadline - Date.now()) };
1060
+ if (Date.now() >= deadline) return { found: false, waitedMs: timeoutMs, tail: truncate(haystack.slice(-300), 300) };
1061
+ await sleep(250);
1062
+ }
1063
+ }
1064
+
1065
+ function resolveUrl(pathOrUrl, baseUrl) {
1066
+ if (/^https?:\/\//i.test(pathOrUrl)) return pathOrUrl;
1067
+ if (pathOrUrl.startsWith("/")) return `${baseUrl}${pathOrUrl}`;
1068
+ return `${baseUrl}/${pathOrUrl}`;
1069
+ }
1070
+
1071
+ async function firstUsable(candidates) {
1072
+ for (const candidate of candidates) {
1073
+ try {
1074
+ if (!(await candidate.count())) continue;
1075
+ const first = candidate.first();
1076
+ if (await first.isVisible().catch(() => false)) return first;
1077
+ } catch { /* 下一个候选 */ }
1078
+ }
1079
+ return null;
1080
+ }
1081
+
1082
+ async function clickByText(page, step, timeout) {
1083
+ const text = String(step.text);
1084
+ const nameRe = new RegExp(escapeRegex(text), "i");
1085
+ const role = step.role ? String(step.role) : "button";
1086
+ const quoted = text.replace(/"/g, '\\"');
1087
+ const candidates = [
1088
+ page.getByRole(role, { name: nameRe }),
1089
+ page.getByRole("button", { name: nameRe }),
1090
+ page.getByRole("link", { name: nameRe }),
1091
+ page.getByRole("menuitem", { name: nameRe }),
1092
+ page.locator(`button:has-text("${quoted}")`),
1093
+ page.locator(`a:has-text("${quoted}")`),
1094
+ page.getByText(text, { exact: true }),
1095
+ page.getByText(text, { exact: false }),
1096
+ ];
1097
+ const locator = await firstUsable(candidates);
1098
+ if (!locator) throw new Error(`未找到可点击的文本「${text}」`);
1099
+ await locator.click({ force: true, timeout: timeout });
1100
+ return { clickedBy: "text", text: text };
1101
+ }
1102
+
1103
+ async function runAction(session, step, index, outDir, options, token) {
1104
+ const page = session.page;
1105
+ const timeout = step.timeoutMs ?? options.timeout ?? DEFAULT_TIMEOUT;
1106
+ switch (step.action) {
1107
+ case "goto": {
1108
+ const url = resolveUrl(step.path ?? step.url, session.baseUrl);
1109
+ await page.goto(url, { waitUntil: step.waitUntil ?? "domcontentloaded", timeout: timeout });
1110
+ if (step.waitMs) await sleep(step.waitMs);
1111
+ if (step.waitForText) {
1112
+ const waited = await waitForTextInPage(page, step.waitForText, timeout, step.regex === true);
1113
+ if (!waited.found) throw new Error(`goto ${url} 后等待文本「${step.waitForText}」超时(${timeout}ms)`);
1114
+ }
1115
+ return { url: page.url() };
1116
+ }
1117
+ case "wait":
1118
+ await sleep(step.ms ?? 1000);
1119
+ return { waitedMs: step.ms ?? 1000 };
1120
+ case "waitForText": {
1121
+ const waited = await waitForTextInPage(page, step.text, timeout, step.regex === true);
1122
+ if (!waited.found) throw new Error(`等待文本「${step.text}」超时(${timeout}ms)`);
1123
+ return { found: true, waitedMs: waited.waitedMs };
1124
+ }
1125
+ case "fill": {
1126
+ const located = await locate(session, step, token);
1127
+ if (located.missing) throw new Error(`未找到字段 ${targetDescription(step)}:${located.info?.reason ?? "no match"}`);
1128
+ const tag = await located.locator.evaluate((el) => el.tagName).catch(() => null);
1129
+ if (tag === "INPUT" || tag === "TEXTAREA") {
1130
+ await located.locator.fill(String(step.value), { timeout: timeout });
1131
+ } else if (tag === "SELECT") {
1132
+ await located.locator.selectOption({ label: String(step.value) }, { timeout: timeout });
1133
+ } else {
1134
+ await located.locator.click({ force: true, timeout: timeout });
1135
+ await page.keyboard.type(String(step.value));
1136
+ }
1137
+ return { how: located.how, tag: tag, value: String(step.value) };
1138
+ }
1139
+ case "select": {
1140
+ const located = await locate(session, step, token);
1141
+ if (located.missing) throw new Error(`未找到下拉字段 ${targetDescription(step)}:${located.info?.reason ?? "no match"}`);
1142
+ const tag = await located.locator.evaluate((el) => el.tagName).catch(() => null);
1143
+ const value = String(step.value);
1144
+ if (tag === "SELECT") {
1145
+ try {
1146
+ await located.locator.selectOption({ value: value }, { timeout: timeout });
1147
+ } catch {
1148
+ await located.locator.selectOption({ label: value }, { timeout: timeout });
1149
+ }
1150
+ } else {
1151
+ await located.locator.click({ force: true, timeout: timeout });
1152
+ const option = await firstUsable([
1153
+ page.locator(".ant-select-item-option, [role='option']").filter({ hasText: new RegExp(escapeRegex(value), "i") }),
1154
+ page.getByText(value, { exact: true }),
1155
+ ]);
1156
+ if (!option) throw new Error(`下拉「${value}」没有可选项`);
1157
+ await option.click({ force: true, timeout: timeout });
1158
+ }
1159
+ return { how: located.how, tag: tag, value: value };
1160
+ }
1161
+ case "check":
1162
+ case "uncheck": {
1163
+ const checked = step.action === "check";
1164
+ const located = await locate(session, step, token);
1165
+ if (located.missing) throw new Error(`未找到勾选字段 ${targetDescription(step)}:${located.info?.reason ?? "no match"}`);
1166
+ let viaContainer = false;
1167
+ try {
1168
+ await located.locator.setChecked(checked, { force: true, timeout: timeout });
1169
+ } catch (error) {
1170
+ if (!located.container) throw new Error(`勾选失败 ${targetDescription(step)}:${truncate(error?.message ?? String(error), 200)}`);
1171
+ await located.container.click({ force: true, timeout: timeout });
1172
+ viaContainer = true;
1173
+ }
1174
+ const state = await located.locator.evaluate((el) => ({
1175
+ checked: typeof el.checked === "boolean" ? el.checked : null,
1176
+ containerChecked: !!el.closest(".ant-checkbox-checked, .ant-radio-checked, [aria-checked='true']"),
1177
+ })).catch(() => null);
1178
+ return { how: located.how, checked: checked, viaContainer: viaContainer, state: state };
1179
+ }
1180
+ case "click": {
1181
+ if (hasTarget(step)) {
1182
+ const located = await locate(session, step, token);
1183
+ if (located.missing) throw new Error(`未找到可点击元素 ${targetDescription(step)}:${located.info?.reason ?? "no match"}`);
1184
+ await located.locator.click({ force: true, timeout: timeout });
1185
+ return { how: located.how, clickedBy: "locator" };
1186
+ }
1187
+ return clickByText(page, step, timeout);
1188
+ }
1189
+ case "press": {
1190
+ if (hasTarget(step)) {
1191
+ const located = await locate(session, step, token);
1192
+ if (located.missing) throw new Error(`未找到按键目标 ${targetDescription(step)}`);
1193
+ await located.locator.press(String(step.key), { timeout: timeout });
1194
+ } else {
1195
+ await page.keyboard.press(String(step.key));
1196
+ }
1197
+ return { key: String(step.key) };
1198
+ }
1199
+ case "eval": {
1200
+ let result;
1201
+ try {
1202
+ result = await page.evaluate(step.script);
1203
+ } catch (error) {
1204
+ throw new Error(`eval 执行失败:${truncate(error?.message ?? String(error), 400)}`);
1205
+ }
1206
+ return { result: truncate(result, 1200) };
1207
+ }
1208
+ case "screenshot": {
1209
+ const name = sanitize(step.name ?? `shot-${pad(index)}`);
1210
+ const file = `${name}.png`;
1211
+ await page.screenshot({ path: join(outDir, file) });
1212
+ session.screenshots.push(file);
1213
+ return { file: file };
1214
+ }
1215
+ case "dumpProbe": {
1216
+ const dump = await readProbe(session);
1217
+ const file = `probe-step-${pad(index)}.json`;
1218
+ writeFileSync(join(outDir, file), JSON.stringify(dump, null, 2));
1219
+ return {
1220
+ file: file,
1221
+ summary: {
1222
+ logs: dump?.logs?.length ?? 0,
1223
+ events: dump?.events?.length ?? 0,
1224
+ registrations: dump?.registrations?.length ?? 0,
1225
+ requests: dump?.requests?.length ?? 0,
1226
+ },
1227
+ };
1228
+ }
1229
+ default:
1230
+ throw new Error(`未实现的 action「${step.action}」`);
1231
+ }
1232
+ }
1233
+
1234
+ async function readProbe(session) {
1235
+ try {
1236
+ return await session.page.evaluate(() => (typeof window.__omcProbeDump === "function" ? window.__omcProbeDump() : null));
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ }
1241
+
1242
+ // ---------------------------------------------------------------------------
1243
+ // 断言
1244
+ // ---------------------------------------------------------------------------
1245
+ function summarizeNetwork(entry) {
1246
+ return {
1247
+ method: entry.method,
1248
+ url: truncate(entry.url, 240),
1249
+ status: entry.status,
1250
+ ms: entry.ms,
1251
+ errcode: entry.errcode,
1252
+ errmsg: entry.errmsg ?? null,
1253
+ };
1254
+ }
1255
+
1256
+ function buildIgnorePatterns(list) {
1257
+ return (Array.isArray(list) ? list : []).map((item) => {
1258
+ if (item && typeof item === "object" && typeof item.pattern === "string") return new RegExp(item.pattern, item.flags ?? "");
1259
+ return new RegExp(escapeRegex(String(item)), "i");
1260
+ });
1261
+ }
1262
+
1263
+ function matchRequest(entry, step) {
1264
+ let pathOk;
1265
+ if (step.regex === true || step.pathIsRegex === true) {
1266
+ try { pathOk = new RegExp(step.path).test(entry.url); } catch { pathOk = false; }
1267
+ } else if (step.regex && typeof step.regex === "string" && step.regex === "path") {
1268
+ try { pathOk = new RegExp(step.path).test(entry.url); } catch { pathOk = false; }
1269
+ } else {
1270
+ pathOk = entry.url.includes(step.path);
1271
+ }
1272
+ const statusOk = step.status == null ? true : Number(entry.status) === Number(step.status);
1273
+ const errcodeOk = step.errcode == null ? true : Number(entry.errcode) === Number(step.errcode);
1274
+ return pathOk && statusOk && errcodeOk;
1275
+ }
1276
+
1277
+ async function pollUntil(check, timeoutMs, intervalMs = 200) {
1278
+ const deadline = Date.now() + timeoutMs;
1279
+ let last = await check();
1280
+ while (!last.ok && Date.now() < deadline) {
1281
+ await sleep(intervalMs);
1282
+ last = await check();
1283
+ }
1284
+ return last;
1285
+ }
1286
+
1287
+ async function runAssertion(session, scenario, step, index, options) {
1288
+ const page = session.page;
1289
+ const timeout = step.timeoutMs ?? options.timeout ?? DEFAULT_TIMEOUT;
1290
+ const token = (suffix) => `omc-${index}-${suffix}-${Math.random().toString(36).slice(2, 8)}`;
1291
+
1292
+ switch (step.kind) {
1293
+ case "valueEquals": {
1294
+ const expected = normalizeComparable(step.expected);
1295
+ const within = step.withinMs ?? Math.min(timeout, 5000);
1296
+ let lastRaw = "";
1297
+ let lastHow = null;
1298
+ const result = await pollUntil(async () => {
1299
+ const located = await locate(session, step, token("value"));
1300
+ if (located.missing) return { ok: false, reason: located.info?.reason ?? "target not found", how: located.how, raw: null };
1301
+ lastHow = located.how;
1302
+ try {
1303
+ lastRaw = await located.locator.evaluate(readValueInPage);
1304
+ } catch (error) {
1305
+ return { ok: false, reason: `读取值失败:${truncate(error?.message ?? String(error), 200)}`, how: located.how, raw: null };
1306
+ }
1307
+ const actual = normalizeComparable(lastRaw);
1308
+ return { ok: actual === expected || numericEqual(actual, expected), how: located.how, raw: lastRaw, actual: actual, reason: null };
1309
+ }, within);
1310
+ return {
1311
+ ok: result.ok,
1312
+ expected: expected,
1313
+ actual: result.actual ?? (lastRaw == null ? null : normalizeComparable(lastRaw)),
1314
+ detail: { raw: truncate(lastRaw, 300), how: lastHow, withinMs: within },
1315
+ reason: result.reason ?? null,
1316
+ };
1317
+ }
1318
+ case "valueMatches": {
1319
+ const source = String(step.regex ?? step.expected);
1320
+ let regex;
1321
+ try {
1322
+ regex = new RegExp(source, step.flags ?? undefined);
1323
+ } catch (error) {
1324
+ return { ok: false, expected: source, actual: null, detail: { reason: `正则非法:${error.message}` }, reason: `正则非法:${error.message}` };
1325
+ }
1326
+ const within = step.withinMs ?? Math.min(timeout, 5000);
1327
+ let lastRaw = "";
1328
+ const result = await pollUntil(async () => {
1329
+ const located = await locate(session, step, token("match"));
1330
+ if (located.missing) return { ok: false, reason: located.info?.reason ?? "target not found" };
1331
+ try { lastRaw = await located.locator.evaluate(readValueInPage); } catch { return { ok: false, reason: "读取值失败" }; }
1332
+ return { ok: regex.test(lastRaw) || regex.test(normalizeComparable(lastRaw)) };
1333
+ }, within);
1334
+ return {
1335
+ ok: result.ok,
1336
+ expected: `/${source}/${step.flags ?? ""}`,
1337
+ actual: truncate(lastRaw, 300),
1338
+ detail: {},
1339
+ reason: result.reason ?? null,
1340
+ };
1341
+ }
1342
+ case "visible":
1343
+ case "hidden": {
1344
+ const located = await locate(session, step, token("vis"));
1345
+ let ok = false;
1346
+ let visible = false;
1347
+ if (!located.missing) {
1348
+ const wantVisible = step.kind === "visible";
1349
+ try {
1350
+ await located.locator.waitFor({ state: wantVisible ? "visible" : "hidden", timeout: timeout });
1351
+ ok = true;
1352
+ } catch { ok = false; }
1353
+ visible = await located.locator.isVisible().catch(() => false);
1354
+ } else if (step.kind === "hidden") {
1355
+ ok = true; // 元素被 v-if 移除也算隐藏
1356
+ }
1357
+ return {
1358
+ ok: ok,
1359
+ expected: step.kind === "visible" ? "visible" : "hidden",
1360
+ actual: located.missing ? "absent" : visible ? "visible" : "hidden",
1361
+ detail: { how: located.how, exists: !located.missing, tag: located.info?.targetTag ?? null },
1362
+ reason: ok ? null : (located.missing ? (located.info?.reason ?? "target not found") : `元素当前 ${visible ? "可见" : "不可见"}`),
1363
+ };
1364
+ }
1365
+ case "readonly": {
1366
+ const result = await pollUntil(async () => {
1367
+ const located = await locate(session, step, token("readonly"));
1368
+ if (located.missing) return { ok: false, reason: located.info?.reason ?? "target not found", state: null };
1369
+ try {
1370
+ const state = await located.locator.evaluate(inspectStateInPage);
1371
+ return { ok: Boolean(state.readonly || state.disabled), state: state, reason: null };
1372
+ } catch (error) {
1373
+ return { ok: false, reason: `读取只读状态失败:${truncate(error?.message ?? String(error), 200)}`, state: null };
1374
+ }
1375
+ }, Math.min(timeout, 8000));
1376
+ return {
1377
+ ok: result.ok,
1378
+ expected: "readonly",
1379
+ actual: result.state ? (result.state.readonly || result.state.disabled ? "readonly" : "editable") : "unknown",
1380
+ detail: result.state ?? {},
1381
+ reason: result.reason ?? null,
1382
+ };
1383
+ }
1384
+ case "required": {
1385
+ const result = await pollUntil(async () => {
1386
+ const located = await locate(session, step, token("required"));
1387
+ if (located.missing) return { ok: false, reason: located.info?.reason ?? "target not found", state: null };
1388
+ try {
1389
+ const state = await located.locator.evaluate(inspectStateInPage);
1390
+ return { ok: Boolean(state.required), state: state, reason: null };
1391
+ } catch (error) {
1392
+ return { ok: false, reason: `读取必填状态失败:${truncate(error?.message ?? String(error), 200)}`, state: null };
1393
+ }
1394
+ }, Math.min(timeout, 8000));
1395
+ return {
1396
+ ok: result.ok,
1397
+ expected: "required",
1398
+ actual: result.state ? (result.state.required ? "required" : "optional") : "unknown",
1399
+ detail: result.state ?? {},
1400
+ reason: result.reason ?? null,
1401
+ };
1402
+ }
1403
+ case "textContains": {
1404
+ const wanted = String(step.expected);
1405
+ let haystack = "";
1406
+ let how = "body";
1407
+ if (hasTarget(step)) {
1408
+ const located = await locate(session, step, token("text"));
1409
+ if (located.missing) {
1410
+ return { ok: false, expected: wanted, actual: null, detail: { how: located.how }, reason: located.info?.reason ?? "target not found" };
1411
+ }
1412
+ how = located.how;
1413
+ haystack = await located.locator.evaluate((el) => String(el.innerText ?? el.textContent ?? "")).catch(() => "");
1414
+ } else {
1415
+ haystack = await page.locator("body").innerText().catch(() => "");
1416
+ }
1417
+ const ok = haystack.includes(wanted);
1418
+ return {
1419
+ ok: ok,
1420
+ expected: `包含「${wanted}」`,
1421
+ actual: truncate(haystack, 300),
1422
+ detail: { how: how, length: haystack.length },
1423
+ reason: ok ? null : `文本中未出现「${wanted}」`,
1424
+ };
1425
+ }
1426
+ case "eventFired":
1427
+ case "eventNotFired":
1428
+ case "eventRegistered": {
1429
+ const dump = await readProbe(session);
1430
+ const event = String(step.event);
1431
+ const fired = (dump?.events ?? []).filter((entry) => entry.event === event);
1432
+ const registered = (dump?.registrations ?? []).filter((entry) => entry.event === event);
1433
+ const handlerErrors = (dump?.errors ?? []).filter((entry) => entry.event === event);
1434
+ let ok;
1435
+ let expected;
1436
+ if (step.kind === "eventFired") { ok = fired.length > 0; expected = `${event} 已触发`; }
1437
+ else if (step.kind === "eventNotFired") { ok = fired.length === 0; expected = `${event} 未触发`; }
1438
+ else { ok = registered.length > 0; expected = `${event} 已注册`; }
1439
+ if (handlerErrors.length) ok = false;
1440
+ const reason = ok ? null
1441
+ : handlerErrors.length
1442
+ ? `事件 ${event} 的处理函数抛错:${truncate(handlerErrors[0].message, 200)}`
1443
+ : step.kind === "eventFired"
1444
+ ? (registered.length ? `事件 ${event} 已注册(${registered.length} 个)但从未触发` : `事件 ${event} 从未注册:检查在线 JS 是否写了 form.on('${event}', ...)`)
1445
+ : step.kind === "eventNotFired"
1446
+ ? `事件 ${event} 不应触发,但触发了 ${fired.length} 次`
1447
+ : `事件 ${event} 从未注册`;
1448
+ return {
1449
+ ok: ok,
1450
+ expected: expected,
1451
+ actual: step.kind === "eventRegistered"
1452
+ ? `${registered.length} 个注册`
1453
+ : fired.length ? `${fired.length} 次触发` : (registered.length ? `${registered.length} 个注册,0 次触发` : "无注册"),
1454
+ detail: {
1455
+ fired: fired.length,
1456
+ registered: registered.length,
1457
+ lastAt: fired.length ? new Date(fired[fired.length - 1].at).toISOString() : null,
1458
+ registeredEvents: Array.from(new Set((dump?.registrations ?? []).map((entry) => entry.event))).slice(0, 20),
1459
+ probeErrors: handlerErrors.slice(0, 3),
1460
+ },
1461
+ reason: reason,
1462
+ };
1463
+ }
1464
+ case "request": {
1465
+ const within = step.withinMs ?? Math.min(timeout, 15000);
1466
+ const deadline = Date.now() + within;
1467
+ let matched = null;
1468
+ let seen = [];
1469
+ await sleep(30);
1470
+ while (true) {
1471
+ await drainNetwork(session);
1472
+ const candidates = session.network.filter((entry) => entry.at >= session.windowStartAt);
1473
+ matched = candidates.filter((entry) => matchRequest(entry, step)).slice(-1)[0] ?? null;
1474
+ if (matched) break;
1475
+ seen = candidates.slice(-6).map(summarizeNetwork);
1476
+ if (Date.now() >= deadline) break;
1477
+ await sleep(150);
1478
+ }
1479
+ return {
1480
+ ok: Boolean(matched),
1481
+ expected: [{ path: step.path, errcode: step.errcode ?? null, status: step.status ?? null }],
1482
+ actual: matched ? summarizeNetwork(matched) : null,
1483
+ detail: { windowStartAt: new Date(session.windowStartAt).toISOString(), withinMs: within, seen: seen },
1484
+ reason: matched ? null : `窗口内未捕获到匹配响应(path≈${step.path}${step.errcode != null ? `, errcode=${step.errcode}` : ""}),最近响应见 detail.seen`,
1485
+ };
1486
+ }
1487
+ case "noConsoleErrors": {
1488
+ const since = session.consoleBaseline ?? 0;
1489
+ const patterns = buildIgnorePatterns([...(scenario.ignoreConsole ?? []), ...(step.ignore ?? [])]);
1490
+ const allErrors = session.console.filter((entry, position) => position >= since && entry.type === "error");
1491
+ const errors = allErrors.filter((entry) => !patterns.some((pattern) => pattern.test(entry.text)));
1492
+ const pageErrors = session.pageErrors.slice(session.pageErrorBaseline ?? 0);
1493
+ return {
1494
+ ok: errors.length === 0,
1495
+ expected: "无 console error",
1496
+ actual: errors.length ? `${errors.length} 条` : "0 条",
1497
+ detail: {
1498
+ errors: errors.slice(0, 5),
1499
+ ignored: allErrors.length - errors.length,
1500
+ pageErrors: pageErrors.slice(0, 5),
1501
+ },
1502
+ reason: errors.length ? `控制台报错:${truncate(errors[0].text, 200)}` : null,
1503
+ };
1504
+ }
1505
+ case "probeLogContains": {
1506
+ const dump = await readProbe(session);
1507
+ const wanted = String(step.text ?? step.expected);
1508
+ const level = step.level ? String(step.level) : null;
1509
+ let test;
1510
+ if (step.useRegex === true) {
1511
+ const regex = new RegExp(wanted);
1512
+ test = (text) => regex.test(text);
1513
+ } else {
1514
+ test = (text) => text.includes(wanted);
1515
+ }
1516
+ const logs = (dump?.logs ?? []).filter((entry) => (!level || entry.level === level) && test(entry.text));
1517
+ return {
1518
+ ok: logs.length > 0,
1519
+ expected: `探针日志包含「${wanted}」${level ? `(level=${level})` : ""}`,
1520
+ actual: logs.length ? truncate(logs[logs.length - 1].text, 200) : "未匹配到日志",
1521
+ detail: {
1522
+ matched: logs.length,
1523
+ tail: (dump?.logs ?? []).slice(-8).map((entry) => `${entry.level}: ${truncate(entry.text, 160)}`),
1524
+ },
1525
+ reason: logs.length ? null : `在线 JS 没有输出包含「${wanted}」的 console 日志(detail.tail 是最近 8 条)`,
1526
+ };
1527
+ }
1528
+ default:
1529
+ return { ok: false, expected: step.kind, actual: null, detail: {}, reason: `未实现的断言「${step.kind}」` };
1530
+ }
1531
+ }
1532
+
1533
+ // ---------------------------------------------------------------------------
1534
+ // 执行与报告
1535
+ // ---------------------------------------------------------------------------
1536
+ async function captureFailure(session, outDir, index, tag, options) {
1537
+ // 默认不写截图(含失败);显式 --screenshots 才截图,复核时自己开。
1538
+ if (!options || options.screenshots !== true) return;
1539
+ const file = `fail-${index}-${sanitize(tag)}.png`;
1540
+ try {
1541
+ await session.page.screenshot({ path: join(outDir, file) });
1542
+ session.screenshots.push(file);
1543
+ } catch { /* 截图失败不掩盖原错误 */ }
1544
+ }
1545
+
1546
+ function formatLine(record) {
1547
+ const head = `${record.ok ? "PASS" : "FAIL"} step#${record.index} ${record.action}${record.kind ? ` ${record.kind}` : ""}`;
1548
+ const detail = record.detail ?? {};
1549
+ const bits = [];
1550
+ if (detail.label) bits.push(`label=${detail.label}`);
1551
+ if (detail.selector) bits.push(`selector=${detail.selector}`);
1552
+ if (detail.expected !== undefined) bits.push(`expected=${truncate(detail.expected, 120)}`);
1553
+ if (detail.actual !== undefined) bits.push(`actual=${truncate(detail.actual, 120)}`);
1554
+ if (detail.optionalUnmet) bits.push("(optional unmet)");
1555
+ if (!record.ok && detail.reason) bits.push(`reason=${truncate(detail.reason, 240)}`);
1556
+ if (!record.ok && detail.error) bits.push(`error=${truncate(detail.error, 240)}`);
1557
+ return bits.length ? `${head} ${bits.join(" ")}` : head;
1558
+ }
1559
+
1560
+ async function executeSteps(session, scenario, outDir, options) {
1561
+ const steps = [];
1562
+ const assertions = [];
1563
+ let failed = 0;
1564
+ let passed = 0;
1565
+ let stopped = false;
1566
+
1567
+ for (let index = 0; index < scenario.steps.length; index += 1) {
1568
+ const step = scenario.steps[index];
1569
+ const stepStartedAt = Date.now();
1570
+ const token = `omc-${index}-${Math.random().toString(36).slice(2, 8)}`;
1571
+ const record = { index: index, action: step.action, ok: true, ms: 0, detail: {} };
1572
+ if (step.kind) record.kind = step.kind;
1573
+ if (step.label) record.detail.label = step.label;
1574
+ if (step.selector) record.detail.selector = step.selector;
1575
+ if (step.action === "assert") {
1576
+ let result;
1577
+ try {
1578
+ result = await runAssertion(session, scenario, step, index, options);
1579
+ } catch (error) {
1580
+ result = { ok: false, expected: step.kind, actual: null, detail: {}, reason: truncate(error?.message ?? String(error), 400) };
1581
+ }
1582
+ const optionalUnmet = !result.ok && step.optional === true;
1583
+ record.ok = result.ok || optionalUnmet;
1584
+ record.detail = Object.assign({}, record.detail, result.detail ?? {}, {
1585
+ expected: result.expected ?? null,
1586
+ actual: result.actual ?? null,
1587
+ reason: result.reason ?? null,
1588
+ optional: step.optional === true,
1589
+ optionalUnmet: optionalUnmet,
1590
+ });
1591
+ assertions.push({
1592
+ step: index,
1593
+ kind: step.kind,
1594
+ ok: result.ok,
1595
+ optional: step.optional === true,
1596
+ expected: result.expected ?? null,
1597
+ actual: result.actual ?? null,
1598
+ detail: result.detail ?? null,
1599
+ });
1600
+ if (!result.ok) {
1601
+ await captureFailure(session, outDir, index, step.kind, options);
1602
+ if (!optionalUnmet) failed += 1;
1603
+ }
1604
+ } else {
1605
+ session.windowStartAt = stepStartedAt;
1606
+ try {
1607
+ const detail = await runAction(session, step, index, outDir, options, token);
1608
+ record.detail = Object.assign({}, record.detail, { result: detail });
1609
+ } catch (error) {
1610
+ record.ok = false;
1611
+ record.detail = Object.assign({}, record.detail, { error: truncate(error?.message ?? String(error), 600) });
1612
+ await captureFailure(session, outDir, index, step.action, options);
1613
+ failed += 1;
1614
+ }
1615
+ }
1616
+ record.ms = Date.now() - stepStartedAt;
1617
+ steps.push(record);
1618
+ console.log(formatLine(record));
1619
+ if (record.ok) passed += 1;
1620
+ if (!record.ok && options.failFast) {
1621
+ stopped = true;
1622
+ console.log(`[probe] --fail-fast:在 step#${index} 停止`);
1623
+ break;
1624
+ }
1625
+ if (options.screenshots && step.action !== "screenshot" && !stopped) {
1626
+ const file = `step-${pad(index)}-${sanitize(step.action + (step.kind ? `-${step.kind}` : ""))}.png`;
1627
+ try {
1628
+ await session.page.screenshot({ path: join(outDir, file) });
1629
+ session.screenshots.push(file);
1630
+ } catch { /* 截图失败不影响结果 */ }
1631
+ }
1632
+ }
1633
+
1634
+ return { steps: steps, assertions: assertions, passed: passed, failed: failed };
1635
+ }
1636
+
1637
+ async function writeReport(session, scenario, outDir, startedAt, result) {
1638
+ const probe = await readProbe(session);
1639
+ const report = {
1640
+ scenario: scenario.name,
1641
+ baseUrl: session.baseUrl,
1642
+ startedAt: new Date(startedAt).toISOString(),
1643
+ durationMs: Date.now() - startedAt,
1644
+ ok: result.failed === 0,
1645
+ passed: result.passed,
1646
+ failed: result.failed,
1647
+ steps: result.steps,
1648
+ assertions: result.assertions,
1649
+ console: session.console.slice(-400),
1650
+ pageErrors: session.pageErrors.slice(-100),
1651
+ network: session.network.slice(-300),
1652
+ probe: probe
1653
+ ? {
1654
+ formSeen: probe.formSeen,
1655
+ formWrapped: probe.formWrapped,
1656
+ hooks: probe.hooks,
1657
+ logs: (probe.logs ?? []).slice(-200),
1658
+ events: (probe.events ?? []).slice(-100),
1659
+ registrations: (probe.registrations ?? []).slice(-100),
1660
+ errors: (probe.errors ?? []).slice(-50),
1661
+ requests: (probe.requests ?? []).slice(-100),
1662
+ }
1663
+ : null,
1664
+ screenshots: session.screenshots,
1665
+ dataLinks: session.dataLinks,
1666
+ };
1667
+ const file = join(outDir, "probe-report.json");
1668
+ writeFileSync(file, JSON.stringify(report, null, 2));
1669
+ return { file: file, report: report };
1670
+ }
1671
+
1672
+ /**
1673
+ * 清掉上一次运行留下的、本脚本命名的产物,避免旧失败截图干扰复核。
1674
+ * 只删 fail-*.png / step-*.png / probe-report.json / trace.zip,不碰目录里其它文件。
1675
+ */
1676
+ function cleanOwnArtifacts(outDir) {
1677
+ if (!existsSync(outDir)) return;
1678
+ let names = [];
1679
+ try { names = readdirSync(outDir); } catch { return; }
1680
+ for (const name of names) {
1681
+ const ours = /^fail-.*\.png$/.test(name) || /^step-.*\.png$/.test(name) || /^self-test-.*\.png$/.test(name) ||
1682
+ name === "probe-report.json" || name === "trace.zip" || /^probe-step-.*\.json$/.test(name);
1683
+ if (!ours) continue;
1684
+ try { unlinkSync(join(outDir, name)); } catch { /* ignore */ }
1685
+ }
1686
+ }
1687
+
1688
+ async function runScenario({ browser, scenario, baseUrl, outDir, options, beforeRun, urlOverride }) {
1689
+ mkdirSync(outDir, { recursive: true });
1690
+ cleanOwnArtifacts(outDir);
1691
+ const session = await openSession({ browser: browser, options: options, scenario: scenario });
1692
+ session.baseUrl = urlOverride ?? baseUrl;
1693
+ const startedAt = Date.now();
1694
+ let result = { steps: [], assertions: [], passed: 0, failed: 0 };
1695
+ let fatal = null;
1696
+ let report = null;
1697
+
1698
+ try {
1699
+ if (typeof beforeRun === "function") await beforeRun(session);
1700
+ if (scenario.login !== false) await login(session, session.baseUrl, options);
1701
+ session.windowStartAt = Date.now();
1702
+ result = await executeSteps(session, scenario, outDir, options);
1703
+ } catch (error) {
1704
+ fatal = error;
1705
+ console.error(`[probe] 致命错误:${truncate(error?.stack ?? error?.message ?? String(error), 1200)}`);
1706
+ await captureFailure(session, outDir, "fatal", "run", options);
1707
+ result.failed += 1;
1708
+ } finally {
1709
+ if (options.trace) {
1710
+ try { await session.context.tracing.stop({ path: join(outDir, "trace.zip") }); } catch { /* ignore */ }
1711
+ }
1712
+ // 等所有响应体读完,dataLinks 才不会被最后一个 submit 的异步解析漏掉。
1713
+ await drainNetwork(session);
1714
+ const written = await writeReport(session, scenario, outDir, startedAt, result); report = written.report;
1715
+ console.log(`\nReport: ${written.file}`);
1716
+ console.log(`Summary: PASS=${result.passed} FAIL=${result.failed}${fatal ? " (fatal)" : ""}`);
1717
+ if (session.screenshots.length) console.log(`Screenshots: ${session.screenshots.length} → ${outDir}`);
1718
+ for (const link of session.dataLinks) console.log(`DATA-LINK ${link.url}`);
1719
+ await session.context.close().catch(() => {});
1720
+ }
1721
+ return {
1722
+ ok: result.failed === 0 && !fatal,
1723
+ passed: result.passed,
1724
+ failed: result.failed + (fatal ? 1 : 0),
1725
+ fatal: fatal,
1726
+ report: report,
1727
+ };
1728
+ }
1729
+
1730
+ // ---------------------------------------------------------------------------
1731
+ // --self-test:不连 CloudPivot,验证 harness 自身
1732
+ // ---------------------------------------------------------------------------
1733
+ const SELF_TEST_HTML = `<!doctype html>
1734
+ <html lang="zh"><head><meta charset="utf-8"><title>omc frontend probe self test</title>
1735
+ <style>
1736
+ body { font-family: sans-serif; padding: 16px; }
1737
+ .ant-form-item { display: flex; align-items: center; gap: 8px; margin: 8px 0; }
1738
+ .ant-form-item-label { width: 140px; text-align: right; }
1739
+ #detail { margin: 8px 0 8px 148px; padding: 6px 10px; background: #eef; }
1740
+ </style></head>
1741
+ <body>
1742
+ <div class="ant-form-item">
1743
+ <label class="ant-form-item-label ant-form-item-required" for="f-name">名称</label>
1744
+ <div class="ant-form-item-control"><input id="f-name" name="name" data-code="name"></div>
1745
+ </div>
1746
+ <div class="ant-form-item">
1747
+ <label class="ant-form-item-label" for="f-qty">数量</label>
1748
+ <div class="ant-form-item-control"><input id="f-qty" name="qty" data-code="qty" type="number"></div>
1749
+ </div>
1750
+ <div class="ant-form-item">
1751
+ <label class="ant-form-item-label" for="f-price">单价</label>
1752
+ <div class="ant-form-item-control"><input id="f-price" name="price" data-code="price" type="number"></div>
1753
+ </div>
1754
+ <div class="ant-form-item">
1755
+ <label class="ant-form-item-label">金额</label>
1756
+ <div class="ant-form-item-control"><span id="f-amount" data-code="amount">0</span></div>
1757
+ </div>
1758
+ <div class="ant-form-item">
1759
+ <label class="ant-form-item-label" for="f-code">编码</label>
1760
+ <div class="ant-form-item-control"><input id="f-code" name="code" data-code="code" readonly value="CODE-1"></div>
1761
+ </div>
1762
+ <div class="ant-form-item">
1763
+ <label class="ant-form-item-label">只读文本</label>
1764
+ <div class="field__control__readonly"><span>RO</span></div>
1765
+ </div>
1766
+ <div class="ant-form-item">
1767
+ <label class="ant-form-item-label" for="f-toggle">显示明细</label>
1768
+ <div class="ant-form-item-control"><input id="f-toggle" name="toggle" type="checkbox"></div>
1769
+ </div>
1770
+ <div id="detail" style="display:none">明细说明:这里是明细内容</div>
1771
+ <button id="submit" type="button">提交</button>
1772
+ <script>
1773
+ (function () {
1774
+ window.form = {
1775
+ handlers: {},
1776
+ on: function (event, callback) { (this.handlers[event] || (this.handlers[event] = [])).push(callback); },
1777
+ fire: function (event, arg) { (this.handlers[event] || []).slice().forEach(function (callback) { callback(arg); }); }
1778
+ };
1779
+ form.on('onLoad', function () { console.log('probe-hello onLoad'); });
1780
+ form.on('onSubmit', function () { console.log('probe-hello onSubmit'); });
1781
+ setTimeout(function () { form.fire('onLoad', { from: 'self-test' }); }, 30);
1782
+
1783
+ var qty = document.getElementById('f-qty');
1784
+ var price = document.getElementById('f-price');
1785
+ var amount = document.getElementById('f-amount');
1786
+ function calc() {
1787
+ amount.textContent = String((Number(qty.value) || 0) * (Number(price.value) || 0));
1788
+ }
1789
+ qty.addEventListener('input', calc);
1790
+ price.addEventListener('input', calc);
1791
+
1792
+ document.getElementById('f-toggle').addEventListener('change', function () {
1793
+ document.getElementById('detail').style.display = this.checked ? 'block' : 'none';
1794
+ });
1795
+
1796
+ document.getElementById('submit').addEventListener('click', function () {
1797
+ form.fire('onSubmit', { source: 'button' });
1798
+ fetch('/api/api/runtime/form/submit', {
1799
+ method: 'POST',
1800
+ headers: { 'content-type': 'application/json' },
1801
+ body: JSON.stringify({ name: document.getElementById('f-name').value })
1802
+ });
1803
+ });
1804
+ })();
1805
+ </script>
1806
+ </body></html>`;
1807
+
1808
+ function buildSelfTestScenario(options = {}) {
1809
+ const steps = [
1810
+ { action: "waitForText", text: "提交", timeoutMs: 10000 },
1811
+ { action: "fill", label: "名称", value: "自测" },
1812
+ { action: "fill", label: "数量", value: "3" },
1813
+ { action: "fill", label: "单价", value: "5" },
1814
+ { action: "assert", kind: "valueEquals", label: "金额", expected: "15" },
1815
+ { action: "assert", kind: "valueMatches", label: "金额", expected: "^1[0-9]$" },
1816
+ { action: "assert", kind: "valueEquals", code: "name", expected: "自测" },
1817
+ { action: "assert", kind: "required", label: "名称" },
1818
+ { action: "assert", kind: "readonly", label: "编码" },
1819
+ { action: "assert", kind: "readonly", label: "只读文本" },
1820
+ { action: "assert", kind: "hidden", selector: "#detail" },
1821
+ { action: "check", label: "显示明细" },
1822
+ { action: "assert", kind: "visible", selector: "#detail" },
1823
+ { action: "assert", kind: "textContains", selector: "#detail", expected: "明细说明" },
1824
+ { action: "uncheck", label: "显示明细" },
1825
+ { action: "assert", kind: "hidden", selector: "#detail" },
1826
+ { action: "assert", kind: "eventRegistered", event: "onLoad" },
1827
+ { action: "assert", kind: "eventFired", event: "onLoad" },
1828
+ { action: "assert", kind: "eventNotFired", event: "onEdit" },
1829
+ { action: "click", text: "提交" },
1830
+ { action: "assert", kind: "request", path: "/api/api/runtime/form/submit", errcode: 0, withinMs: 8000 },
1831
+ { action: "assert", kind: "eventFired", event: "onSubmit" },
1832
+ { action: "assert", kind: "probeLogContains", text: "probe-hello" },
1833
+ { action: "assert", kind: "noConsoleErrors" },
1834
+ { action: "eval", script: "document.title" },
1835
+ { action: "dumpProbe" },
1836
+ ];
1837
+ // 截图动作只有显式 --screenshots 时才放进自测,避免默认留下 PNG。
1838
+ if (options.screenshots === true) steps.push({ action: "screenshot", name: "self-test-final" });
1839
+ return {
1840
+ name: "self-test",
1841
+ description: "内联 HTML 验证 harness:fill / valueEquals / visible / hidden / readonly / required / eventFired / request / probeLogContains / DATA-LINK",
1842
+ login: false,
1843
+ // 自测的假页面发 /runtime/form/submit,响应带 data.id;用来离线断言 DATA-LINK 形状。
1844
+ schemaCode: "self_test_model",
1845
+ steps: steps,
1846
+ };
1847
+ }
1848
+
1849
+ async function runSelfTest(options) {
1850
+ // 自测默认落到系统临时目录;显式 --out 才用调用方目录。默认不写截图。
1851
+ const outDir = options.out
1852
+ ? resolve(process.cwd(), options.out, "self-test")
1853
+ : join(tmpdir(), "omc-frontend-probe-self-test");
1854
+ const scenario = buildSelfTestScenario(options);
1855
+ const errors = validateScenario(scenario, "self-test");
1856
+ if (errors.length) {
1857
+ console.error("[probe] self-test 场景非法:", errors);
1858
+ process.exit(3);
1859
+ }
1860
+ const browser = await launchBrowser(options);
1861
+ const selfTestHost = "http://frontend-probe.self-test";
1862
+ let exitCode = 3;
1863
+ try {
1864
+ const summary = await runScenario({
1865
+ browser: browser,
1866
+ scenario: scenario,
1867
+ baseUrl: selfTestHost,
1868
+ outDir: outDir,
1869
+ options: options,
1870
+ beforeRun: async (session) => {
1871
+ await session.context.route("**/*", async (route) => {
1872
+ const url = route.request().url();
1873
+ if (url.includes("/api/api/runtime/form/submit")) {
1874
+ await route.fulfill({
1875
+ status: 200,
1876
+ contentType: "application/json",
1877
+ body: JSON.stringify({ errcode: 0, errmsg: "ok", data: { id: "self-test-1" } }),
1878
+ });
1879
+ return;
1880
+ }
1881
+ if (/\/api\//.test(url)) {
1882
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ errcode: 0, errmsg: "ok" }) });
1883
+ return;
1884
+ }
1885
+ await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: SELF_TEST_HTML });
1886
+ });
1887
+ await session.page.goto(`${selfTestHost}/`, { waitUntil: "domcontentloaded", timeout: 20000 });
1888
+ },
1889
+ });
1890
+ // DATA-LINK 离线断言:假 submit 响应 data.id=self-test-1,链接形状必须可点开。
1891
+ const expectedLink = `${selfTestHost}/form/detail?schemaCode=self_test_model`
1892
+ + `&sheetCode=self_test_model&objectId=self-test-1&isWorkFlow=false`;
1893
+ const links = summary.report?.dataLinks ?? [];
1894
+ const linkOk = links.length === 1 && links[0].url === expectedLink;
1895
+ if (linkOk) console.log(`PASS dataLinks ${expectedLink}`);
1896
+ else console.error(`[probe] self-test DATA-LINK 断言失败:${truncate(JSON.stringify(links), 500)}`);
1897
+ if (summary.ok && linkOk) {
1898
+ console.log("SELF-TEST PASS");
1899
+ exitCode = 0;
1900
+ } else {
1901
+ console.error("SELF-TEST FAIL");
1902
+ exitCode = 1;
1903
+ }
1904
+ } catch (error) {
1905
+ console.error(`[probe] self-test 无法运行:${truncate(error?.stack ?? error?.message ?? String(error), 1500)}`);
1906
+ exitCode = 3;
1907
+ } finally {
1908
+ await browser.close().catch(() => {});
1909
+ }
1910
+ process.exit(exitCode);
1911
+ }
1912
+
1913
+ // ---------------------------------------------------------------------------
1914
+ // 入口
1915
+ // ---------------------------------------------------------------------------
1916
+ async function main() {
1917
+ const options = parseArgs(process.argv.slice(2));
1918
+ if (options.help) { printHelp(); return; }
1919
+ if (options.selfTest) { await runSelfTest(options); return; }
1920
+ if (options.validate) {
1921
+ const file = resolveInputPath(options.validate);
1922
+ let scenario;
1923
+ try {
1924
+ scenario = loadScenario(file);
1925
+ } catch (error) {
1926
+ console.error(JSON.stringify({ ok: false, file: file, error: error.message }, null, 2));
1927
+ process.exit(2);
1928
+ }
1929
+ const errors = validateScenario(scenario, file);
1930
+ console.log(JSON.stringify({
1931
+ ok: errors.length === 0,
1932
+ file: file,
1933
+ scenario: scenario?.name ?? null,
1934
+ steps: Array.isArray(scenario?.steps) ? scenario.steps.length : 0,
1935
+ errors: errors,
1936
+ }, null, 2));
1937
+ process.exit(errors.length === 0 ? 0 : 2);
1938
+ }
1939
+ if (!options.scenario) {
1940
+ printHelp();
1941
+ process.exit(2);
1942
+ }
1943
+
1944
+ const scenarioFile = resolveInputPath(options.scenario);
1945
+ let scenario;
1946
+ try {
1947
+ scenario = loadScenario(scenarioFile);
1948
+ } catch (error) {
1949
+ console.error(`[probe] ${error.message}`);
1950
+ process.exit(2);
1951
+ }
1952
+ const errors = validateScenario(scenario, scenarioFile);
1953
+ if (errors.length) {
1954
+ console.error(`[probe] 场景配置非法(${scenarioFile}):`);
1955
+ for (const error of errors) console.error(` - ${error}`);
1956
+ process.exit(2);
1957
+ }
1958
+
1959
+ const baseUrl = (options.baseUrl ?? process.env.BASE_URL ?? DEFAULT_BASE_URL).replace(/\/$/, "");
1960
+ const outDir = resolve(process.cwd(), options.out ?? DEFAULT_OUT);
1961
+ const optionsWithDefaults = Object.assign({}, options, { timeout: options.timeout ?? DEFAULT_TIMEOUT, baseUrl: baseUrl });
1962
+ console.log(`[probe] scenario=${scenario.name} baseUrl=${baseUrl} out=${outDir}`);
1963
+
1964
+ let browser;
1965
+ try {
1966
+ browser = await launchBrowser(optionsWithDefaults);
1967
+ } catch (error) {
1968
+ console.error(`[probe] 无法启动浏览器(PW_EXECUTABLE_PATH/PW_ROOT 不对?):${truncate(error?.message ?? String(error), 500)}`);
1969
+ process.exit(3);
1970
+ }
1971
+ try {
1972
+ const summary = await runScenario({
1973
+ browser: browser,
1974
+ scenario: scenario,
1975
+ baseUrl: baseUrl,
1976
+ outDir: outDir,
1977
+ options: optionsWithDefaults,
1978
+ });
1979
+ process.exitCode = summary.ok ? 0 : 1;
1980
+ } finally {
1981
+ await browser.close().catch(() => {});
1982
+ }
1983
+ process.exit(process.exitCode ?? 0);
1984
+ }
1985
+
1986
+ await main();