vibecode-anything 0.3.0 → 0.4.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.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,894 @@
1
+ import { loadPlaywright, launchBrowser } from "../core/adapters.js";
2
+ import { VibecodeError, errorMessage } from "../core/errors.js";
3
+ import { asciiLower, isForbiddenObjectKey, isRecordSafe, redactSensitiveText, resolveSafeTargetUrl } from "../core/security.js";
4
+ import { filterRuntimeHeaders, mergeHeaders } from "../ingestors/trace.js";
5
+ import { gotoWithSpaFallback, openBrowserPage, stripTags } from "../ingestors/web.js";
6
+ const PLAYWRIGHT_INSTALL_HINT = "npm install -D playwright && npx playwright install chromium";
7
+ const MAX_HTML_BYTES = 512 * 1024;
8
+ const MAX_CHECKS = 100;
9
+ const MAX_TAB_STEPS = 50;
10
+ const MAX_STATIC_ELEMENTS = 4000;
11
+ const DEFAULT_TIMEOUT_MS = 15_000;
12
+ const MAX_SELECTOR_CHARS = 2048;
13
+ // Total matchSimple() evaluations allowed per static evaluation; exceeding it fails closed instead of hanging.
14
+ const MAX_SELECTOR_WORK = 2_000_000;
15
+ const MAX_TEXT_NEEDLES = 32;
16
+ const MAX_ID_CHARS = 200;
17
+ const CLOSE_TIMEOUT_MS = 5_000;
18
+ const REDACTED_STORAGE_VALUE = "[REDACTED_STORAGE_VALUE]";
19
+ const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
20
+ const VALID_CHECK_KINDS = new Set(["hover", "focus", "keyboard_tab", "disabled", "empty_state", "error_state", "storage"]);
21
+ const SENSITIVE_STORAGE_KEY_RE = /token|auth|secret|session|password|passwd|cookie|jwt|key|credential|bearer|private/i;
22
+ const SIMPLE_ATTR_RE = /^\[\s*([A-Za-z0-9:_-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+)))?\s*\]/;
23
+ const isObject = isRecordSafe;
24
+ const isSpace = (c) => c === 32 || c === 9 || c === 10 || c === 13 || c === 12;
25
+ const isValidCheck = (v) => isObject(v) && typeof v.kind === "string" && VALID_CHECK_KINDS.has(v.kind);
26
+ const requiresPlaywright = (c) => c.kind === "hover" || c.kind === "focus" || c.kind === "storage" || (c.kind === "error_state" && isObject(c.trigger));
27
+ /** String() that never throws (null-prototype objects, hostile toString/Proxy traps). */
28
+ const safeString = (v) => {
29
+ try {
30
+ return String(v);
31
+ }
32
+ catch {
33
+ try {
34
+ return Object.prototype.toString.call(v);
35
+ }
36
+ catch {
37
+ return "[unprintable]";
38
+ }
39
+ }
40
+ };
41
+ const clip = (s, max) => (s.length > max ? `${s.slice(0, max)}...` : s);
42
+ /** Check ids flow into failures, diff keys and metrics: redact BEFORE clipping so a secret is never half-cut past the redactor. */
43
+ const checkIdOf = (raw, idx) => {
44
+ const id = (isObject(raw) && typeof raw.id === "string" && raw.id.trim()) ||
45
+ `${isObject(raw) && typeof raw.kind === "string" && raw.kind.trim() ? raw.kind.trim() : "check"}-${idx + 1}`;
46
+ return clip(redactSensitiveText(id), MAX_ID_CHARS).trim() || `check-${idx + 1}`;
47
+ };
48
+ const unsupportedKindMessage = (raw) => redactSensitiveText(`unsupported UI state check kind: ${clip(isObject(raw) ? safeString(raw.kind) : safeString(raw), 120)}`);
49
+ const normalizeNeedles = (raw, failures) => {
50
+ const all = typeof raw === "string" ? (raw ? [raw] : []) : Array.isArray(raw) ? raw.filter((s) => typeof s === "string" && s.length > 0) : [];
51
+ if (all.length > MAX_TEXT_NEEDLES)
52
+ failures.push(`expectTextContains has ${all.length} entries; maximum is ${MAX_TEXT_NEEDLES}`);
53
+ return all.slice(0, MAX_TEXT_NEEDLES);
54
+ };
55
+ /** expectedFocusOrder bounded to MAX_TAB_STEPS (entries past it can never be reached) with non-strings stringified safely. */
56
+ const focusOrderOf = (check, failures) => {
57
+ const raw = Array.isArray(check.expectedFocusOrder) ? check.expectedFocusOrder : [];
58
+ if (raw.length > MAX_TAB_STEPS)
59
+ failures.push(`expectedFocusOrder has ${raw.length} entries; maximum is ${MAX_TAB_STEPS}`);
60
+ return raw.slice(0, MAX_TAB_STEPS).map((s) => (typeof s === "string" ? s : safeString(s)));
61
+ };
62
+ /** Await a teardown step without letting it throw or hang forever; keep timer ref'd until finally clears it. */
63
+ async function settleQuietly(step) {
64
+ let timer;
65
+ try {
66
+ await Promise.race([
67
+ Promise.resolve().then(step),
68
+ new Promise((resolve) => { timer = setTimeout(resolve, CLOSE_TIMEOUT_MS); })
69
+ ]);
70
+ }
71
+ catch { /* ignore teardown errors */ }
72
+ finally {
73
+ clearTimeout(timer);
74
+ }
75
+ }
76
+ async function getPlaywright(deps, cwd) {
77
+ const explicit = Object.prototype.hasOwnProperty.call(deps, "playwright") ? deps.playwright : undefined;
78
+ if (explicit === null)
79
+ return null;
80
+ const candidate = explicit !== undefined ? explicit : await loadPlaywright(cwd ? { ...deps, cwd } : deps);
81
+ if (!candidate || typeof candidate !== "object")
82
+ return null;
83
+ const mod = candidate;
84
+ if (mod.chromium && typeof mod.chromium.launch === "function")
85
+ return mod;
86
+ if (mod.default?.chromium && typeof mod.default.chromium.launch === "function")
87
+ return mod.default;
88
+ return null;
89
+ }
90
+ function safeStorageVal(key, rawIn, forMessage) {
91
+ if (rawIn === null || rawIn === undefined)
92
+ return forMessage ? "<absent>" : null;
93
+ const raw = typeof rawIn === "string" ? rawIn : safeString(rawIn);
94
+ if (SENSITIVE_STORAGE_KEY_RE.test(key) || redactSensitiveText(raw) !== raw)
95
+ return REDACTED_STORAGE_VALUE;
96
+ const limit = forMessage ? 80 : 120;
97
+ const clipped = raw.length > limit ? `${raw.slice(0, limit)}...` : raw;
98
+ return forMessage ? JSON.stringify(clipped) : clipped;
99
+ }
100
+ function parseStaticHtml(html) {
101
+ let src = typeof html === "string" ? (html.length > MAX_HTML_BYTES ? html.slice(0, MAX_HTML_BYTES) : html) : "";
102
+ if (src.charCodeAt(0) === 0xfeff)
103
+ src = src.slice(1);
104
+ const lower = asciiLower(src), elements = [], stack = [], plainParts = [];
105
+ let plainLen = 0, bodyEl = null;
106
+ // Open-tag counts make unmatched closers O(1); phantom counts track tags opened past MAX_STATIC_ELEMENTS so their
107
+ // closers do not prematurely close real ancestors (10k nested <div> stays correct). The open stack is bounded by
108
+ // MAX_STATIC_ELEMENTS and needs no depth cap now that selector matching is a non-recursive DP.
109
+ const openCount = new Map(), phantom = new Map();
110
+ const bump = (m, k, d) => { const v = (m.get(k) ?? 0) + d; if (v > 0)
111
+ m.set(k, v);
112
+ else
113
+ m.delete(k); };
114
+ const pushText = (seg) => {
115
+ if (!seg)
116
+ return;
117
+ const dec = stripTags(seg.includes("<") ? seg.replaceAll("<", "&lt;") : seg).replaceAll("&quot;", '"').replaceAll("&#39;", "'");
118
+ if (!dec)
119
+ return;
120
+ if (plainLen > 0) {
121
+ plainParts.push(" ");
122
+ plainLen += 1;
123
+ }
124
+ plainParts.push(dec);
125
+ plainLen += dec.length;
126
+ };
127
+ for (let i = 0; i < src.length;) {
128
+ const lt = src.indexOf("<", i);
129
+ if (lt === -1) {
130
+ pushText(src.slice(i));
131
+ break;
132
+ }
133
+ if (lt > i)
134
+ pushText(src.slice(i, lt));
135
+ // Search from lt + 2 so the spec's abrupt empty comments `<!-->` and `<!--->` close immediately.
136
+ if (src.startsWith("<!--", lt)) {
137
+ const end = src.indexOf("-->", lt + 2);
138
+ if (end === -1)
139
+ break;
140
+ i = end + 3;
141
+ continue;
142
+ }
143
+ const ch1 = lower[lt + 1] ?? "";
144
+ if (ch1 === "!" || ch1 === "?") {
145
+ const gt = src.indexOf(">", lt + 2);
146
+ if (gt === -1)
147
+ break;
148
+ i = gt + 1;
149
+ continue;
150
+ }
151
+ if (ch1 === "/") {
152
+ let end = lt + 2;
153
+ while (end < src.length && /[a-z0-9:_-]/.test(lower[end]))
154
+ end++;
155
+ const closeTag = lower.slice(lt + 2, end);
156
+ if (phantom.has(closeTag))
157
+ bump(phantom, closeTag, -1);
158
+ else if (openCount.has(closeTag)) {
159
+ for (let s = stack.length - 1; s >= 0; s--) {
160
+ if (stack[s].tag === closeTag) {
161
+ for (let k = stack.length - 1; k >= s; k--) {
162
+ stack[k].textEnd = plainLen;
163
+ bump(openCount, stack[k].tag, -1);
164
+ }
165
+ stack.length = s;
166
+ break;
167
+ }
168
+ }
169
+ }
170
+ const gt = src.indexOf(">", end);
171
+ if (gt === -1)
172
+ break;
173
+ i = gt + 1;
174
+ continue;
175
+ }
176
+ if (ch1 < "a" || ch1 > "z") {
177
+ pushText("<");
178
+ i = lt + 1;
179
+ continue;
180
+ }
181
+ let pos = lt + 1;
182
+ while (pos < src.length && /[a-z0-9:_-]/.test(lower[pos]))
183
+ pos++;
184
+ const tag = lower.slice(lt + 1, pos), attrs = new Map();
185
+ let selfClosing = false;
186
+ while (pos < src.length) {
187
+ while (pos < src.length && isSpace(src.charCodeAt(pos)))
188
+ pos++;
189
+ const ch = src.charCodeAt(pos);
190
+ if (pos >= src.length || ch === 62) {
191
+ if (ch === 62)
192
+ pos++;
193
+ break;
194
+ }
195
+ if (ch === 47) {
196
+ if (src.charCodeAt(pos + 1) === 62)
197
+ selfClosing = true;
198
+ pos++;
199
+ continue;
200
+ }
201
+ const kStart = pos;
202
+ while (pos < src.length && !isSpace(src.charCodeAt(pos)) && src.charCodeAt(pos) !== 61 && src.charCodeAt(pos) !== 62 && src.charCodeAt(pos) !== 47)
203
+ pos++;
204
+ const key = lower.slice(kStart, pos);
205
+ while (pos < src.length && isSpace(src.charCodeAt(pos)))
206
+ pos++;
207
+ let val = "";
208
+ if (src.charCodeAt(pos) === 61) {
209
+ pos++;
210
+ while (pos < src.length && isSpace(src.charCodeAt(pos)))
211
+ pos++;
212
+ const q = src.charCodeAt(pos);
213
+ if (q === 34 || q === 39) {
214
+ const close = src.indexOf(src[pos], pos + 1);
215
+ val = close === -1 ? src.slice(pos + 1) : src.slice(pos + 1, close);
216
+ pos = close === -1 ? src.length : close + 1;
217
+ }
218
+ else {
219
+ const vStart = pos;
220
+ while (pos < src.length && !isSpace(src.charCodeAt(pos)) && src.charCodeAt(pos) !== 62)
221
+ pos++;
222
+ val = src.slice(vStart, pos);
223
+ }
224
+ }
225
+ if (key && !attrs.has(key))
226
+ attrs.set(key, val);
227
+ }
228
+ if (tag === "script" || tag === "style") {
229
+ // HTML ignores the self-closing flag on non-void elements: `<script/>` still opens a raw-text block,
230
+ // so its body must never leak into visible text (spoofing empty/error-state text checks).
231
+ const needle = `</${tag}`;
232
+ let cStart = -1;
233
+ for (let scan = pos; scan < lower.length;) {
234
+ const idx = lower.indexOf(needle, scan);
235
+ if (idx === -1)
236
+ break;
237
+ const after = idx + needle.length;
238
+ if (after >= lower.length || lower.charCodeAt(after) === 62 || lower.charCodeAt(after) === 47 || isSpace(lower.charCodeAt(after))) {
239
+ cStart = idx;
240
+ break;
241
+ }
242
+ scan = after;
243
+ }
244
+ const cGt = cStart === -1 ? -1 : src.indexOf(">", cStart + needle.length);
245
+ if (cGt === -1)
246
+ break;
247
+ i = cGt + 1;
248
+ continue;
249
+ }
250
+ const opens = !selfClosing && !VOID_TAGS.has(tag);
251
+ if (elements.length < MAX_STATIC_ELEMENTS) {
252
+ const clsRaw = attrs.get("class") ?? "";
253
+ const el = {
254
+ index: elements.length, tag, attrs, classes: new Set(clsRaw ? clsRaw.trim().split(/\s+/).filter(Boolean) : []),
255
+ parent: stack.length > 0 ? stack[stack.length - 1] : null, textStart: plainLen, textEnd: plainLen
256
+ };
257
+ elements.push(el);
258
+ if (tag === "body" && !bodyEl)
259
+ bodyEl = el;
260
+ if (opens) {
261
+ stack.push(el);
262
+ bump(openCount, tag, 1);
263
+ }
264
+ }
265
+ else if (opens)
266
+ bump(phantom, tag, 1);
267
+ i = pos;
268
+ }
269
+ for (const open of stack)
270
+ open.textEnd = plainLen;
271
+ return { elements, fullText: plainParts.join(""), bodyEl };
272
+ }
273
+ function splitOutsideBrackets(raw, onComma) {
274
+ const out = [];
275
+ let start = 0, bracket = 0, quote = "";
276
+ for (let i = 0; i <= raw.length; i++) {
277
+ const ch = i < raw.length ? raw[i] : "";
278
+ if (quote) {
279
+ if (ch === quote)
280
+ quote = "";
281
+ continue;
282
+ }
283
+ if (ch === '"' || ch === "'") {
284
+ quote = ch;
285
+ continue;
286
+ }
287
+ if (ch === "[") {
288
+ bracket++;
289
+ continue;
290
+ }
291
+ if (ch === "]" && bracket > 0) {
292
+ bracket--;
293
+ continue;
294
+ }
295
+ if (i === raw.length || (bracket === 0 && (onComma ? ch === "," : isSpace(raw.charCodeAt(i))))) {
296
+ const seg = raw.slice(start, i).trim();
297
+ if (seg)
298
+ out.push(seg);
299
+ start = i + 1;
300
+ }
301
+ }
302
+ return out;
303
+ }
304
+ function parseSimpleSelector(raw) {
305
+ const s = raw.trim();
306
+ if (!s || s.length > 512)
307
+ return null;
308
+ const out = { classes: [], attrs: [] };
309
+ let i = 0;
310
+ if (s[0] === "*") {
311
+ out.tag = "*";
312
+ i = 1;
313
+ }
314
+ else if (/[A-Za-z]/.test(s[0])) {
315
+ while (i < s.length && /[A-Za-z0-9:_-]/.test(s[i]))
316
+ i++;
317
+ out.tag = asciiLower(s.slice(0, i));
318
+ }
319
+ while (i < s.length) {
320
+ const ch = s[i];
321
+ if (ch === "#" || ch === ".") {
322
+ let end = i + 1;
323
+ while (end < s.length && !/[#.\[\]:\s>]/.test(s[end]))
324
+ end++;
325
+ const tok = s.slice(i + 1, end);
326
+ if (!tok)
327
+ return null;
328
+ if (ch === "#")
329
+ out.id = tok;
330
+ else
331
+ out.classes.push(tok);
332
+ i = end;
333
+ }
334
+ else if (ch === "[") {
335
+ const m = SIMPLE_ATTR_RE.exec(s.slice(i));
336
+ if (!m)
337
+ return null;
338
+ out.attrs.push({ name: asciiLower(m[1]), value: m[2] ?? m[3] ?? m[4] });
339
+ i += m[0].length;
340
+ }
341
+ else
342
+ return null;
343
+ }
344
+ return out;
345
+ }
346
+ /**
347
+ * Descendant-combinator matcher in O(elements) per comma-chain via a top-down greedy prefix DP
348
+ * (the old ancestor recursion was O(depth^chainLength): `.nope div div ... div` on 256-deep HTML never returned).
349
+ * Results are cached per selector and all work is charged to a per-evaluation budget that fails closed.
350
+ */
351
+ function queryStatic(elements, selector, budget) {
352
+ if (typeof selector !== "string" || selector.length > MAX_SELECTOR_CHARS || !selector.trim())
353
+ return [];
354
+ const cached = budget.cache.get(selector);
355
+ if (cached)
356
+ return cached;
357
+ if (budget.exhausted)
358
+ return [];
359
+ const chains = [];
360
+ for (const part of splitOutsideBrackets(selector, true)) {
361
+ const chain = splitOutsideBrackets(part, false).map(parseSimpleSelector);
362
+ if (chain.length > 0 && chain.every((c) => c !== null))
363
+ chains.push(chain);
364
+ }
365
+ const matchSimple = (el, sel) => {
366
+ if ((sel.tag && sel.tag !== "*" && el.tag !== sel.tag) || (sel.id !== undefined && el.attrs.get("id") !== sel.id))
367
+ return false;
368
+ for (const cls of sel.classes)
369
+ if (!el.classes.has(cls))
370
+ return false;
371
+ for (const a of sel.attrs)
372
+ if (!el.attrs.has(a.name) || (a.value !== undefined && el.attrs.get(a.name) !== a.value))
373
+ return false;
374
+ return true;
375
+ };
376
+ const hit = new Uint8Array(elements.length), prefix = new Int32Array(elements.length);
377
+ for (const chain of chains) {
378
+ const cost = elements.length * 2;
379
+ if (budget.left < cost) {
380
+ budget.exhausted = true;
381
+ return [];
382
+ }
383
+ budget.left -= cost;
384
+ const last = chain.length - 1;
385
+ // prefix[i] = how many leading compounds match greedily on the root..element path (parents precede children).
386
+ for (const el of elements) {
387
+ const p = el.parent ? prefix[el.parent.index] : 0;
388
+ if (p >= last && matchSimple(el, chain[last]))
389
+ hit[el.index] = 1;
390
+ prefix[el.index] = p < last && matchSimple(el, chain[p]) ? p + 1 : p;
391
+ }
392
+ }
393
+ const result = elements.filter((el) => hit[el.index] === 1);
394
+ budget.cache.set(selector, result);
395
+ return result;
396
+ }
397
+ const parseTabindex = (el) => {
398
+ if (!el.attrs.has("tabindex"))
399
+ return null;
400
+ const raw = (el.attrs.get("tabindex") ?? "").trim();
401
+ const n = /^-?\d+$/.test(raw) ? Number.parseInt(raw, 10) : NaN;
402
+ return Number.isSafeInteger(n) ? n : null;
403
+ };
404
+ const isStaticHidden = (el) => {
405
+ if (el.attrs.has("hidden") || (el.attrs.get("aria-hidden") ?? "").trim().toLowerCase() === "true")
406
+ return true;
407
+ const style = asciiLower(el.attrs.get("style") ?? "").replace(/\s+/g, "");
408
+ return style.includes("display:none") || style.includes("visibility:hidden");
409
+ };
410
+ function evaluateDomSnapshot(check, snap, failures) {
411
+ if (check.selector && !snap.found) {
412
+ failures.push(`selector ${check.selector} not found`);
413
+ return;
414
+ }
415
+ if (check.selector) {
416
+ for (const cls of typeof check.expectClass === "string" ? check.expectClass.trim().split(/\s+/).filter(Boolean) : []) {
417
+ if (!snap.classes.has(cls))
418
+ failures.push(`expected ${check.selector} to have class ${JSON.stringify(redactSensitiveText(cls))}`);
419
+ }
420
+ if (isObject(check.expectAttr)) {
421
+ for (const [k, v] of Object.entries(check.expectAttr)) {
422
+ if (isForbiddenObjectKey(k))
423
+ continue;
424
+ const actual = snap.getAttr(k);
425
+ if (actual !== safeString(v)) {
426
+ failures.push(`attribute ${redactSensitiveText(k)} on ${check.selector}: expected ${JSON.stringify(redactSensitiveText(safeString(v)))}, got ${actual === null ? "null" : JSON.stringify(redactSensitiveText(actual))}`);
427
+ }
428
+ }
429
+ }
430
+ }
431
+ if (check.expectVisible && !snap.visOk)
432
+ failures.push(`expected ${check.expectVisible} to be visible`);
433
+ const needles = normalizeNeedles(check.expectTextContains, failures);
434
+ if (check.kind === "focus") {
435
+ const wantFocused = check.expectFocused !== false;
436
+ if (snap.isFocused !== wantFocused)
437
+ failures.push(`expected ${check.selector} to ${wantFocused ? "be focused" : "not be focused"}`);
438
+ if (check.expectVisibleFocusRing === true && !snap.hasFocusRing)
439
+ failures.push(`expected visible focus ring on ${check.selector} (outline and box-shadow are none)`);
440
+ }
441
+ else if (check.kind === "disabled") {
442
+ const want = check.expectDisabled !== false;
443
+ if (snap.disabled !== want)
444
+ failures.push(`expected ${check.selector} to be ${want ? "disabled" : "enabled"}, got ${snap.disabled ? "disabled" : "enabled"}`);
445
+ }
446
+ else if (check.kind === "error_state") {
447
+ const wantAlert = check.expectRoleAlert ?? (!check.expectAriaInvalid && needles.length === 0 && !check.selector);
448
+ if (wantAlert && !snap.hasRoleAlert)
449
+ failures.push('missing [role="alert"] element');
450
+ if (check.expectAriaInvalid) {
451
+ if (!snap.invFound)
452
+ failures.push(`aria-invalid target ${check.expectAriaInvalid} not found`);
453
+ else if (!snap.invTrue)
454
+ failures.push(`expected ${check.expectAriaInvalid} to have aria-invalid="true"`);
455
+ }
456
+ }
457
+ for (const needle of needles)
458
+ if (!snap.text.includes(needle))
459
+ failures.push(`${check.kind} text missing ${JSON.stringify(redactSensitiveText(needle))}`);
460
+ }
461
+ /** O(N) ReDoS-free static HTML fallback evaluator for web_ui_states checks without Playwright. */
462
+ export function evaluateStaticUiStates(html, checks) {
463
+ const parsed = parseStaticHtml(html);
464
+ const bodyText = parsed.bodyEl ? parsed.fullText.slice(parsed.bodyEl.textStart, parsed.bodyEl.textEnd).trim() : parsed.fullText;
465
+ const focusableEntries = [];
466
+ for (const el of parsed.elements) {
467
+ if (el.attrs.has("disabled") || isStaticHidden(el))
468
+ continue;
469
+ const ti = parseTabindex(el);
470
+ if (ti !== null && ti < 0)
471
+ continue;
472
+ const nativeFocus = (el.tag === "a" && el.attrs.has("href")) || el.tag === "button" || el.tag === "select" || el.tag === "textarea" ||
473
+ (el.tag === "input" && (el.attrs.get("type") ?? "").trim().toLowerCase() !== "hidden");
474
+ if (nativeFocus || ti !== null)
475
+ focusableEntries.push({ el, order: ti !== null && ti > 0 ? ti : Number.MAX_SAFE_INTEGER });
476
+ }
477
+ focusableEntries.sort((a, b) => (a.order !== b.order ? a.order - b.order : a.el.index - b.el.index));
478
+ const focusPos = new Map(focusableEntries.map((f, i) => [f.el, i]));
479
+ const outcomes = [];
480
+ const budget = { left: MAX_SELECTOR_WORK, exhausted: false, cache: new Map() };
481
+ const query = (sel) => queryStatic(parsed.elements, sel, budget);
482
+ for (let idx = 0; idx < (Array.isArray(checks) ? Math.min(checks.length, MAX_CHECKS) : 0); idx++) {
483
+ const rawCheck = checks[idx], id = checkIdOf(rawCheck, idx);
484
+ if (!isValidCheck(rawCheck)) {
485
+ outcomes.push({ id, kind: "disabled", status: "fail", failures: [unsupportedKindMessage(rawCheck)] });
486
+ continue;
487
+ }
488
+ const check = rawCheck;
489
+ if (requiresPlaywright(check)) {
490
+ outcomes.push({ id, kind: check.kind, status: "skipped", failures: [], reason: "Requires Playwright browser runtime" });
491
+ continue;
492
+ }
493
+ const failures = [];
494
+ const wasExhausted = budget.exhausted;
495
+ try {
496
+ evaluateStaticCheck(check, failures);
497
+ }
498
+ catch (err) {
499
+ failures.push(`${check.kind} check error: ${errorMessage(err)}`);
500
+ }
501
+ if (budget.exhausted && !wasExhausted)
502
+ failures.push(`static selector evaluation budget of ${MAX_SELECTOR_WORK} steps exceeded; selectors were not fully evaluated`);
503
+ else if (budget.exhausted)
504
+ failures.push("static selector evaluation budget exhausted by earlier checks");
505
+ outcomes.push({ id, kind: check.kind, status: failures.length === 0 ? "pass" : "fail", failures: failures.map(redactSensitiveText) });
506
+ }
507
+ return { outcomes, passed: outcomes.filter((o) => o.status === "pass").length, failed: outcomes.filter((o) => o.status === "fail").length, skipped: outcomes.filter((o) => o.status === "skipped").length };
508
+ function evaluateStaticCheck(check, failures) {
509
+ if (check.kind === "keyboard_tab") {
510
+ const expectedOrder = focusOrderOf(check, failures);
511
+ if (expectedOrder.length === 0) {
512
+ if (focusableEntries.length === 0)
513
+ failures.push("no keyboard-focusable elements found");
514
+ }
515
+ else {
516
+ let prevPos = -1, prevSel = "";
517
+ for (const targetSel of expectedOrder) {
518
+ const allMatches = query(targetSel);
519
+ if (allMatches.length === 0) {
520
+ failures.push(`expected focus target ${targetSel} not found`);
521
+ continue;
522
+ }
523
+ const trapEl = allMatches.find((el) => { const ti = parseTabindex(el); return ti !== null && ti < 0; });
524
+ const focusMatches = allMatches.map((el) => focusPos.get(el)).filter((p) => p !== undefined).sort((a, b) => a - b);
525
+ if (focusMatches.length === 0) {
526
+ failures.push(trapEl ? `focus trap: ${targetSel} has negative tabindex (${trapEl.attrs.get("tabindex")}) and is unreachable via Tab`
527
+ : allMatches.some((el) => el.attrs.has("disabled")) ? `expected focus target ${targetSel} is disabled and not keyboard-focusable`
528
+ : `expected focus target ${targetSel} is not keyboard-focusable`);
529
+ continue;
530
+ }
531
+ const nextPos = focusMatches.find((p) => p > prevPos);
532
+ if (nextPos === undefined)
533
+ failures.push(`focus order mismatch: ${targetSel} appears before ${prevSel} in Tab order`);
534
+ else {
535
+ prevPos = nextPos;
536
+ prevSel = targetSel;
537
+ }
538
+ }
539
+ }
540
+ }
541
+ else if (check.kind === "disabled" && !check.selector) {
542
+ failures.push("disabled check requires selector");
543
+ }
544
+ else {
545
+ const matched = check.selector ? query(check.selector) : [], el = matched[0] ?? null;
546
+ const vis = check.expectVisible ? query(check.expectVisible) : [];
547
+ const inv = check.expectAriaInvalid ? query(check.expectAriaInvalid) : [];
548
+ // Matches are in document order and spans nest, so keeping only non-overlapping spans bounds the joined
549
+ // text by the page text (`*` on 256-deep nesting previously built hundreds of MB of duplicate text).
550
+ const textParts = [];
551
+ let keptEnd = -1;
552
+ for (const m of matched)
553
+ if (m.textStart >= keptEnd) {
554
+ textParts.push(parsed.fullText.slice(m.textStart, m.textEnd));
555
+ keptEnd = Math.max(m.textEnd, m.textStart + 1);
556
+ }
557
+ evaluateDomSnapshot(check, {
558
+ found: !check.selector || Boolean(el), classes: el ? el.classes : new Set(), getAttr: (k) => el?.attrs.get(asciiLower(k)) ?? null,
559
+ disabled: Boolean(el && (el.attrs.has("disabled") || (el.attrs.get("aria-disabled") ?? "").trim().toLowerCase() === "true")),
560
+ isFocused: false, hasFocusRing: false, visOk: !check.expectVisible || (vis.length > 0 && !vis.every(isStaticHidden)),
561
+ hasRoleAlert: check.kind === "error_state" && query('[role="alert"]').length > 0,
562
+ invFound: !check.expectAriaInvalid || inv.length > 0, invTrue: Boolean(inv[0] && (inv[0].attrs.get("aria-invalid") ?? "").trim().toLowerCase() === "true"),
563
+ text: check.selector ? textParts.join(" ").trim() : bodyText
564
+ }, failures);
565
+ }
566
+ }
567
+ }
568
+ async function runPlaywrightCheck(page, check, id, timeoutMs) {
569
+ const failures = [];
570
+ let diffEntry;
571
+ const attrKeys = isObject(check.expectAttr) ? Object.keys(check.expectAttr).filter((k) => !isForbiddenObjectKey(k)) : [];
572
+ try {
573
+ if (check.kind === "keyboard_tab") {
574
+ const expectedOrder = focusOrderOf(check, failures);
575
+ // Non-numeric counts (NaN, "abc") previously produced NaN steps -> zero Tab presses -> vacuous pass.
576
+ const rawCount = typeof check.count === "number" && !Number.isNaN(check.count) ? check.count : expectedOrder.length;
577
+ const steps = Math.min(MAX_TAB_STEPS, Math.max(0, Math.floor(rawCount)));
578
+ if (steps <= 0)
579
+ failures.push("keyboard_tab check requires count > 0 or non-empty expectedFocusOrder");
580
+ else {
581
+ if (check.selector && typeof page.focus === "function")
582
+ await page.focus(check.selector, { timeout: timeoutMs });
583
+ const observed = [];
584
+ for (let step = 0; step < steps; step++) {
585
+ if (page.keyboard && typeof page.keyboard.press === "function")
586
+ await page.keyboard.press("Tab");
587
+ else
588
+ await page.press("body", "Tab", { timeout: timeoutMs });
589
+ observed.push(await page.evaluate((selectors) => {
590
+ const el = document.activeElement;
591
+ if (!el)
592
+ return { descriptor: "none", elKey: "none", matched: [], reset: true };
593
+ const tag = String(el.tagName || "").toLowerCase(), idAttr = String(el.getAttribute?.("id") || el.id || "").trim();
594
+ const testId = String(el.getAttribute?.("data-testid") || "").trim(), name = String(el.getAttribute?.("name") || "").trim();
595
+ const cls = String(el.getAttribute?.("class") || el.className || "").trim();
596
+ const descriptor = idAttr ? `#${idAttr}` : testId ? `[data-testid="${testId}"]` : name ? `${tag}[name="${name}"]` : cls ? `${tag}.${cls.split(/\s+/)[0]}` : tag || "unknown";
597
+ let sibIdx = 0;
598
+ for (let prev = el.previousElementSibling; prev; prev = prev.previousElementSibling)
599
+ sibIdx++;
600
+ const elKey = idAttr ? `${tag}#${idAttr}` : `${descriptor}@${sibIdx}:${String(el.textContent || "").trim().slice(0, 24)}`;
601
+ const matched = [];
602
+ for (let i = 0; i < selectors.length; i++) {
603
+ const sel = selectors[i];
604
+ let ok = false;
605
+ if (typeof el.matches === "function") {
606
+ try {
607
+ ok = el.matches(sel);
608
+ }
609
+ catch {
610
+ ok = false;
611
+ }
612
+ }
613
+ else
614
+ ok = sel === descriptor || sel === tag || (sel.startsWith("#") && idAttr === sel.slice(1)) || (sel.startsWith(".") && cls.split(/\s+/).includes(sel.slice(1)));
615
+ if (ok)
616
+ matched.push(i);
617
+ }
618
+ return { descriptor, elKey, matched, reset: tag === "body" || tag === "html" };
619
+ }, expectedOrder));
620
+ }
621
+ const descriptors = observed.map((o) => o.descriptor);
622
+ let trapReported = false;
623
+ for (let i = 1; i < observed.length; i++) {
624
+ const sameExp = expectedOrder[i] !== undefined && expectedOrder[i] === expectedOrder[i - 1];
625
+ if (!trapReported && !sameExp && observed[i].elKey !== "none" && observed[i].elKey === observed[i - 1].elKey) {
626
+ failures.push(`focus trap detected: keyboard Tab stuck on ${observed[i].descriptor} (observed: ${descriptors.join(" -> ")})`);
627
+ trapReported = true;
628
+ }
629
+ }
630
+ // Cycle trap (A -> B -> A) without focus ever leaving to <body>/none, unless the expected order itself revisits.
631
+ if (!trapReported && new Set(expectedOrder).size === expectedOrder.length) {
632
+ const seen = new Set();
633
+ for (const o of observed) {
634
+ if (o.reset || o.elKey === "none") {
635
+ seen.clear();
636
+ continue;
637
+ }
638
+ if (seen.has(o.elKey)) {
639
+ failures.push(`focus trap detected: keyboard Tab cycles back to ${o.descriptor} without leaving the focus loop (observed: ${descriptors.join(" -> ")})`);
640
+ break;
641
+ }
642
+ seen.add(o.elKey);
643
+ }
644
+ }
645
+ let cursor = -1;
646
+ for (let expIdx = 0; expIdx < expectedOrder.length; expIdx++) {
647
+ const next = observed.findIndex((o, pos) => pos > cursor && o.matched.includes(expIdx));
648
+ if (next === -1) {
649
+ failures.push(observed.some((o) => o.matched.includes(expIdx))
650
+ ? `focus order mismatch: ${expectedOrder[expIdx]} appeared out of order (observed: ${descriptors.join(" -> ")})`
651
+ : `expected focus target ${expectedOrder[expIdx]} was not reached in ${steps} Tab presses (observed: ${descriptors.join(" -> ")})`);
652
+ }
653
+ else
654
+ cursor = next;
655
+ }
656
+ if (failures.length > 0)
657
+ diffEntry = { observedFocusOrder: descriptors.map(redactSensitiveText), expectedFocusOrder: expectedOrder.map(redactSensitiveText) };
658
+ }
659
+ }
660
+ else if (check.kind === "storage") {
661
+ const area = check.area ?? "localStorage", key = typeof check.key === "string" ? check.key : "";
662
+ if (area !== "localStorage" && area !== "sessionStorage")
663
+ failures.push(`invalid storage area: ${clip(safeString(area), 80)}`);
664
+ else if (!key)
665
+ failures.push("storage check requires key");
666
+ else {
667
+ const rawActual = await page.evaluate((arg) => {
668
+ const store = arg.area === "sessionStorage" ? window.sessionStorage : window.localStorage;
669
+ const val = store ? store.getItem(arg.key) : null;
670
+ return val === null || val === undefined ? null : String(val);
671
+ }, { area, key });
672
+ const actual = rawActual === null || rawActual === undefined ? null : safeString(rawActual);
673
+ // Expectations from JSON may be numbers/booleans; storage values are always strings.
674
+ const expEquals = check.expectEquals === undefined ? undefined : safeString(check.expectEquals);
675
+ const expContains = check.expectContains === undefined ? undefined : safeString(check.expectContains);
676
+ const safeKey = redactSensitiveText(key);
677
+ const dispActual = safeStorageVal(key, actual, true);
678
+ const hasAnyExp = check.expectAbsent === true || check.expectExists !== undefined || expEquals !== undefined || expContains !== undefined;
679
+ if ((check.expectAbsent === true || check.expectExists === false) && actual !== null)
680
+ failures.push(`expected ${area}[${JSON.stringify(safeKey)}] to be absent, got ${dispActual}`);
681
+ if ((check.expectExists === true || !hasAnyExp) && actual === null)
682
+ failures.push(`expected ${area}[${JSON.stringify(safeKey)}] to exist`);
683
+ if (expEquals !== undefined && actual !== expEquals)
684
+ failures.push(`storage ${area}[${JSON.stringify(safeKey)}] expected ${safeStorageVal(key, expEquals, true)}, got ${dispActual}`);
685
+ if (expContains !== undefined && (actual === null || !actual.includes(expContains)))
686
+ failures.push(`storage ${area}[${JSON.stringify(safeKey)}] missing substring ${safeStorageVal(key, expContains, true)} (got ${dispActual})`);
687
+ if (failures.length > 0) {
688
+ diffEntry = {
689
+ area, key: safeKey, actual: safeStorageVal(key, actual, false),
690
+ ...(expEquals !== undefined ? { expected: safeStorageVal(key, expEquals, false) } : {}),
691
+ ...(expContains !== undefined ? { expectContains: safeStorageVal(key, expContains, false) } : {})
692
+ };
693
+ }
694
+ }
695
+ }
696
+ else if ((check.kind === "hover" || check.kind === "focus" || check.kind === "disabled") && !check.selector) {
697
+ failures.push(`${check.kind} check requires selector`);
698
+ }
699
+ else {
700
+ if (check.kind === "hover") {
701
+ if (typeof page.hover !== "function")
702
+ throw new Error("Playwright page.hover is not available");
703
+ await page.hover(check.selector, { timeout: timeoutMs });
704
+ }
705
+ else if (check.kind === "focus") {
706
+ if (typeof page.focus === "function")
707
+ await page.focus(check.selector, { timeout: timeoutMs });
708
+ else
709
+ await page.evaluate((sel) => { document.querySelector(sel)?.focus?.(); }, check.selector);
710
+ }
711
+ else if (check.kind === "error_state" && isObject(check.trigger)) {
712
+ const { action, selector, value, key } = check.trigger;
713
+ if (action === "click")
714
+ await page.click(selector, { timeout: timeoutMs });
715
+ else if (action === "fill")
716
+ await page.fill(selector, safeString(value ?? ""), { timeout: timeoutMs });
717
+ else if (action === "press")
718
+ await page.press(selector, key || "Enter", { timeout: timeoutMs });
719
+ else
720
+ failures.push(`unsupported trigger action: ${clip(safeString(action), 80)}`);
721
+ }
722
+ const rawSnap = await page.evaluate((arg) => {
723
+ const isVis = (el) => {
724
+ if (!el || el.getAttribute?.("hidden") !== null || String(el.getAttribute?.("aria-hidden") || "").trim().toLowerCase() === "true")
725
+ return false;
726
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
727
+ const st = window.getComputedStyle(el);
728
+ if (st && (st.display === "none" || st.visibility === "hidden" || st.opacity === "0"))
729
+ return false;
730
+ }
731
+ if (typeof el.getBoundingClientRect === "function") {
732
+ const r = el.getBoundingClientRect();
733
+ if (r && r.width <= 0 && r.height <= 0)
734
+ return false;
735
+ }
736
+ return true;
737
+ };
738
+ const el = arg.selector ? document.querySelector(arg.selector) : null;
739
+ const visEl = arg.expectVisible ? document.querySelector(arg.expectVisible) : null;
740
+ const invEl = arg.expectAriaInvalid ? document.querySelector(arg.expectAriaInvalid) : null;
741
+ const attrs = {};
742
+ for (const k of arg.attrKeys)
743
+ attrs[k] = el?.getAttribute?.(k) ?? null;
744
+ const clsStr = el ? String(el.getAttribute?.("class") || el.className || "") : "";
745
+ let hasFocusRing = false;
746
+ if (arg.checkFocusRing && el && typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
747
+ const st = window.getComputedStyle(el), outline = String(st?.outlineStyle || st?.outline || "").trim();
748
+ const ow = String(st?.outlineWidth || "").trim(), bs = String(st?.boxShadow || "").trim();
749
+ const hasOutline = Boolean(outline) && !/^(?:0(?:px)?\s+)?none$/i.test(outline) && !outline.toLowerCase().startsWith("none ") && outline !== "0" && outline !== "0px" && ow !== "0px" && ow !== "0";
750
+ hasFocusRing = hasOutline || (Boolean(bs) && bs.toLowerCase() !== "none");
751
+ }
752
+ const textNode = arg.preferVisibleText ? (visEl ?? el ?? document.body) : (el ?? document.body);
753
+ return {
754
+ found: !arg.selector || Boolean(el), classes: clsStr.trim() ? clsStr.trim().split(/\s+/) : [], attrs,
755
+ disabled: Boolean(el && (el.disabled === true || el.getAttribute?.("disabled") !== null || String(el.getAttribute?.("aria-disabled") || "").trim().toLowerCase() === "true")),
756
+ isFocused: Boolean(el && document.activeElement && document.activeElement === el), hasFocusRing,
757
+ visOk: !arg.expectVisible || isVis(visEl), hasRoleAlert: arg.checkAlert ? Boolean(document.querySelector('[role="alert"]')) : false,
758
+ invFound: !arg.expectAriaInvalid || Boolean(invEl), invTrue: String(invEl?.getAttribute?.("aria-invalid") || "").trim().toLowerCase() === "true",
759
+ text: textNode ? String(textNode.innerText || textNode.textContent || "") : ""
760
+ };
761
+ }, {
762
+ selector: check.selector ?? "", expectVisible: check.expectVisible ?? "", expectAriaInvalid: check.expectAriaInvalid ?? "",
763
+ attrKeys, checkFocusRing: check.kind === "focus" && check.expectVisibleFocusRing === true,
764
+ checkAlert: check.kind === "error_state", preferVisibleText: check.kind === "hover"
765
+ });
766
+ evaluateDomSnapshot(check, { ...rawSnap, classes: new Set(rawSnap.classes), getAttr: (k) => (Object.prototype.hasOwnProperty.call(rawSnap.attrs, k) ? rawSnap.attrs[k] : null) }, failures);
767
+ }
768
+ }
769
+ catch (err) {
770
+ failures.push(`${check.kind} check error: ${errorMessage(err)}`);
771
+ }
772
+ return { outcome: { id, kind: check.kind, status: failures.length === 0 ? "pass" : "fail", failures: failures.map(redactSensitiveText) }, ...(diffEntry ? { diffEntry } : {}) };
773
+ }
774
+ function assembleOutcome(backend, safeUrl, outcomes, extraDiffs, extraMetrics = {}) {
775
+ const failures = [], diffChecks = {};
776
+ for (const o of outcomes) {
777
+ if (o.status !== "fail")
778
+ continue;
779
+ for (const f of o.failures)
780
+ failures.push(redactSensitiveText(`[${o.id}] ${f}`));
781
+ const safeKey = redactSensitiveText(o.id);
782
+ if (!isForbiddenObjectKey(safeKey)) {
783
+ const extra = extraDiffs.get(o.id);
784
+ Object.defineProperty(diffChecks, safeKey, { value: extra ? { kind: o.kind, ...extra, failures: o.failures } : { kind: o.kind, failures: o.failures }, enumerable: true, writable: true, configurable: true });
785
+ }
786
+ }
787
+ return {
788
+ status: failures.length === 0 ? "pass" : "fail", score: failures.length === 0 ? 1 : 0, failures,
789
+ ...(Object.keys(diffChecks).length > 0 ? { diff: { url: safeUrl, checks: diffChecks } } : {}),
790
+ metrics: {
791
+ backend, url: safeUrl, ...extraMetrics, totalChecks: outcomes.length,
792
+ passed: outcomes.filter((o) => o.status === "pass").length,
793
+ failed: outcomes.filter((o) => o.status === "fail").length,
794
+ skipped: outcomes.filter((o) => o.status === "skipped").length, checks: outcomes
795
+ }
796
+ };
797
+ }
798
+ async function fetchStaticHtml(url, timeoutMs, headers, deps) {
799
+ if (typeof deps.fetchRoute === "function") {
800
+ const obs = await deps.fetchRoute(url, timeoutMs, headers);
801
+ return { status: obs.status, html: String(obs.html ?? "").slice(0, MAX_HTML_BYTES) };
802
+ }
803
+ const ctrl = new AbortController(), timer = setTimeout(() => ctrl.abort(), timeoutMs);
804
+ const cleanHeaders = filterRuntimeHeaders(headers);
805
+ try {
806
+ const res = await fetch(url, { signal: ctrl.signal, redirect: "follow", ...(Object.keys(cleanHeaders).length > 0 ? { headers: cleanHeaders } : {}) });
807
+ if (!res.body)
808
+ return { status: res.status, html: (await res.text()).slice(0, MAX_HTML_BYTES) };
809
+ const reader = res.body.getReader(), chunks = [];
810
+ let total = 0;
811
+ while (total < MAX_HTML_BYTES) {
812
+ const { done, value } = await reader.read();
813
+ if (done || !value)
814
+ break;
815
+ const take = Math.min(value.byteLength, MAX_HTML_BYTES - total);
816
+ chunks.push(take === value.byteLength ? value : value.subarray(0, take));
817
+ total += take;
818
+ }
819
+ await reader.cancel().catch(() => { });
820
+ return { status: res.status, html: Buffer.concat(chunks).toString("utf8") };
821
+ }
822
+ finally {
823
+ clearTimeout(timer);
824
+ }
825
+ }
826
+ /** Verifies interactive UI states, keyboard Tab order, disabled/empty/error states, and browser storage. */
827
+ export async function verifyUiStates(invariant, ctx, deps = {}) {
828
+ if (!ctx.target)
829
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <url> for web_ui_states verification.");
830
+ const input = invariant.input || {}, rawChecks = input["checks"];
831
+ if (!Array.isArray(rawChecks) || rawChecks.length === 0) {
832
+ return { status: "fail", score: 0, failures: ["web_ui_states requires a non-empty input.checks array"], metrics: { backend: "none", totalChecks: 0, passed: 0, failed: 0, skipped: 0 } };
833
+ }
834
+ const checks = rawChecks.slice(0, MAX_CHECKS);
835
+ const timeoutMs = typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : DEFAULT_TIMEOUT_MS;
836
+ let url;
837
+ try {
838
+ const rawRoute = typeof input.path === "string" && input.path.trim() ? input.path : "/";
839
+ url = resolveSafeTargetUrl(rawRoute, safeString(ctx.target)).toString();
840
+ }
841
+ catch (err) {
842
+ const msg = errorMessage(err).replace(/^Unsupported URL protocol\b/i, "unsupported URL scheme");
843
+ return { status: "fail", score: 0, failures: [redactSensitiveText(`invalid web_ui_states URL: ${msg}`)], metrics: { backend: "none", totalChecks: checks.length, passed: 0, failed: checks.length, skipped: 0 } };
844
+ }
845
+ const safeUrl = redactSensitiveText(url);
846
+ const mergedHeaders = mergeHeaders(isObject(input.headers) ? input.headers : undefined, ctx.headers);
847
+ const pw = await getPlaywright(deps, ctx.cwd);
848
+ if (!pw) {
849
+ if (checks.every((c) => isValidCheck(c) && requiresPlaywright(c))) {
850
+ throw new VibecodeError("ADAPTER_MISSING", "web_ui_states checks require Playwright browser runtime (hover, focus, storage, or triggered error_state)", { adapter: "playwright", installHint: PLAYWRIGHT_INSTALL_HINT });
851
+ }
852
+ let fetched;
853
+ try {
854
+ fetched = await fetchStaticHtml(url, timeoutMs, mergedHeaders, deps);
855
+ }
856
+ catch (err) {
857
+ return { status: "fail", score: 0, failures: [redactSensitiveText(`fetch failed for ${safeUrl}: ${errorMessage(err)}`)], metrics: { backend: "static", url: safeUrl, totalChecks: checks.length, passed: 0, failed: checks.length, skipped: 0 } };
858
+ }
859
+ return assembleOutcome("static", safeUrl, evaluateStaticUiStates(fetched.html, checks).outcomes, new Map(), { httpStatus: fetched.status });
860
+ }
861
+ const browser = await launchBrowser(pw, { headless: true, featureName: "web_ui_states verification" });
862
+ try {
863
+ const pageHandle = await openBrowserPage(browser, { viewport: input.viewport || ctx.viewport || { width: 1280, height: 720 }, headers: mergedHeaders, storageState: ctx.storageState || input.storageState });
864
+ const page = pageHandle.page;
865
+ try {
866
+ try {
867
+ await gotoWithSpaFallback(pageHandle.page, url, input.waitUntil || "networkidle", timeoutMs);
868
+ }
869
+ catch (err) {
870
+ return { status: "fail", score: 0, failures: [redactSensitiveText(`navigation failed for ${safeUrl}: ${errorMessage(err)}`)], metrics: { backend: "playwright", url: safeUrl, totalChecks: checks.length, passed: 0, failed: checks.length, skipped: 0 } };
871
+ }
872
+ const outcomes = [], extraDiffs = new Map();
873
+ for (let i = 0; i < checks.length; i++) {
874
+ const rawCheck = checks[i], id = checkIdOf(rawCheck, i);
875
+ if (!isValidCheck(rawCheck)) {
876
+ outcomes.push({ id, kind: "disabled", status: "fail", failures: [unsupportedKindMessage(rawCheck)] });
877
+ continue;
878
+ }
879
+ const { outcome, diffEntry } = await runPlaywrightCheck(page, rawCheck, id, timeoutMs);
880
+ outcomes.push(outcome);
881
+ if (diffEntry)
882
+ extraDiffs.set(outcome.id, diffEntry);
883
+ }
884
+ return assembleOutcome("playwright", safeUrl, outcomes, extraDiffs);
885
+ }
886
+ finally {
887
+ await settleQuietly(() => pageHandle.close());
888
+ }
889
+ }
890
+ finally {
891
+ await settleQuietly(() => browser.close());
892
+ }
893
+ }
894
+ export const verifyInvariant = verifyUiStates;