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.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,1343 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError } from "./errors.js";
|
|
5
|
+
import { isSensitiveHeader } from "../ingestors/trace.js";
|
|
6
|
+
const SUGGESTED_FILENAME = "vibecode-contract.spec.ts";
|
|
7
|
+
const EXPORTABLE_TYPES = new Set(["web_route", "web_flow", "web_network", "http"]);
|
|
8
|
+
const VALID_WAIT_UNTIL = new Set(["load", "domcontentloaded", "networkidle", "commit"]);
|
|
9
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
10
|
+
const SENSITIVE_HEADER_RE = /^(?:api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|x[_-](?:csrf|xsrf)[_-]token|csrf[_-]token|xsrf[_-]token|authorization|proxy[_-]authorization|cookie|set[_-]cookie)$/i;
|
|
11
|
+
const SENSITIVE_QUERY_PARAM_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|secret|client[_-]?secret|password|passwd|auth|jwt|session[_-]?id|sig|signature|private[_-]?key)$/i;
|
|
12
|
+
const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer)$/i;
|
|
13
|
+
const SENSITIVE_SELECTOR_RE = /(?:type\s*=\s*["']?password|password|passwd|secret|token|api[-_]?key|auth)/i;
|
|
14
|
+
const VAULT_PATH_RE = /(?:[A-Za-z]:)?[^\s"'`<>]*\.vibecode-vault[^\s"'`<>]*/gi;
|
|
15
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
|
|
16
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s@"'`<>]+)@/g;
|
|
17
|
+
const BEARER_OR_BASIC_VALUE_RE = /^\s*(?:bearer|basic)\s+\S+/i;
|
|
18
|
+
const INLINE_AUTH_TOKEN_RE = /\b(Bearer|Basic)\s+\S+/gi;
|
|
19
|
+
function isRecord(value) {
|
|
20
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
21
|
+
}
|
|
22
|
+
function isSensitiveHeaderName(name) {
|
|
23
|
+
const trimmed = String(name).trim();
|
|
24
|
+
return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
|
|
25
|
+
}
|
|
26
|
+
function isSensitiveQueryName(name) {
|
|
27
|
+
return SENSITIVE_QUERY_PARAM_RE.test(String(name).trim());
|
|
28
|
+
}
|
|
29
|
+
function redactVaultPaths(text) {
|
|
30
|
+
return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
|
|
31
|
+
}
|
|
32
|
+
function sanitizeFragment(rawFragment) {
|
|
33
|
+
if (!rawFragment)
|
|
34
|
+
return "";
|
|
35
|
+
const body = rawFragment.startsWith("#") ? rawFragment.slice(1) : rawFragment;
|
|
36
|
+
if (!body)
|
|
37
|
+
return "";
|
|
38
|
+
if (body.includes("=")) {
|
|
39
|
+
const params = new URLSearchParams(body);
|
|
40
|
+
const safe = new URLSearchParams();
|
|
41
|
+
let keptParam = false;
|
|
42
|
+
for (const [k, v] of params.entries()) {
|
|
43
|
+
if (isSensitiveQueryName(k))
|
|
44
|
+
continue;
|
|
45
|
+
keptParam = true;
|
|
46
|
+
safe.append(k, sanitizeFreeText(v));
|
|
47
|
+
}
|
|
48
|
+
const serialized = safe.toString();
|
|
49
|
+
return keptParam && serialized ? `#${serialized}` : "";
|
|
50
|
+
}
|
|
51
|
+
const clean = sanitizeFreeText(body);
|
|
52
|
+
return clean ? `#${clean}` : "";
|
|
53
|
+
}
|
|
54
|
+
function sanitizeUrlString(rawUrl) {
|
|
55
|
+
const withoutVault = redactVaultPaths(rawUrl);
|
|
56
|
+
const withoutBasicAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
|
|
57
|
+
try {
|
|
58
|
+
const parsed = new URL(withoutBasicAuth);
|
|
59
|
+
parsed.username = "";
|
|
60
|
+
parsed.password = "";
|
|
61
|
+
const safeParams = new URLSearchParams();
|
|
62
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
63
|
+
if (isSensitiveQueryName(k))
|
|
64
|
+
continue;
|
|
65
|
+
safeParams.append(k, sanitizeFreeText(v));
|
|
66
|
+
}
|
|
67
|
+
const serialized = safeParams.toString();
|
|
68
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
69
|
+
parsed.hash = sanitizeFragment(parsed.hash);
|
|
70
|
+
return parsed.toString();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return withoutBasicAuth;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function sanitizePathWithQuery(rawPath) {
|
|
77
|
+
const cleaned = redactVaultPaths(rawPath.trim());
|
|
78
|
+
if (!cleaned)
|
|
79
|
+
return "/";
|
|
80
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(cleaned)) {
|
|
81
|
+
return sanitizeUrlString(cleaned);
|
|
82
|
+
}
|
|
83
|
+
const withoutAuth = cleaned.replace(URL_BASIC_AUTH_RE, "$1");
|
|
84
|
+
const qIdx = withoutAuth.indexOf("?");
|
|
85
|
+
if (qIdx < 0) {
|
|
86
|
+
const hOnlyIdx = withoutAuth.indexOf("#");
|
|
87
|
+
if (hOnlyIdx < 0)
|
|
88
|
+
return sanitizeFreeText(withoutAuth);
|
|
89
|
+
return `${sanitizeFreeText(withoutAuth.slice(0, hOnlyIdx))}${sanitizeFragment(withoutAuth.slice(hOnlyIdx))}`;
|
|
90
|
+
}
|
|
91
|
+
const hashIdx = withoutAuth.indexOf("#", qIdx);
|
|
92
|
+
const basePath = sanitizeFreeText(withoutAuth.slice(0, qIdx));
|
|
93
|
+
const rawQuery = hashIdx >= 0 ? withoutAuth.slice(qIdx + 1, hashIdx) : withoutAuth.slice(qIdx + 1);
|
|
94
|
+
const hashPart = hashIdx >= 0 ? sanitizeFragment(withoutAuth.slice(hashIdx)) : "";
|
|
95
|
+
const rawParams = new URLSearchParams(rawQuery);
|
|
96
|
+
const safeParams = new URLSearchParams();
|
|
97
|
+
for (const [k, v] of rawParams.entries()) {
|
|
98
|
+
if (isSensitiveQueryName(k))
|
|
99
|
+
continue;
|
|
100
|
+
safeParams.append(k, sanitizeFreeText(v));
|
|
101
|
+
}
|
|
102
|
+
const serialized = safeParams.toString();
|
|
103
|
+
return `${basePath}${serialized ? `?${serialized}` : ""}${hashPart}`;
|
|
104
|
+
}
|
|
105
|
+
function sanitizeFreeText(text) {
|
|
106
|
+
const noVault = redactVaultPaths(text);
|
|
107
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlString(match));
|
|
108
|
+
const noAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
|
|
109
|
+
return noAuth.replace(INLINE_AUTH_TOKEN_RE, (match, scheme) => /^\[REDACTED\]$/i.test(match.slice(scheme.length).trim()) ? match : `${scheme} [REDACTED]`);
|
|
110
|
+
}
|
|
111
|
+
function sanitizeComment(text, maxLen = 220) {
|
|
112
|
+
const sanitized = sanitizeFreeText(text)
|
|
113
|
+
// eslint-disable-next-line no-control-regex
|
|
114
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
115
|
+
.replace(/[\r\n\u2028\u2029]+/g, " ")
|
|
116
|
+
// eslint-disable-next-line no-control-regex
|
|
117
|
+
.replace(/[\x00-\x1F\x7F]/g, " ")
|
|
118
|
+
.replace(/\*\//g, "* /")
|
|
119
|
+
.replace(/<\/(script)/gi, "<\\/$1")
|
|
120
|
+
.replace(/\s+/g, " ")
|
|
121
|
+
.trim();
|
|
122
|
+
if (sanitized.length <= maxLen)
|
|
123
|
+
return sanitized;
|
|
124
|
+
return `${sanitized.slice(0, maxLen - 3)}...`;
|
|
125
|
+
}
|
|
126
|
+
function sanitizeTargetString(raw) {
|
|
127
|
+
if (typeof raw !== "string")
|
|
128
|
+
return "";
|
|
129
|
+
const trimmed = raw.trim();
|
|
130
|
+
if (!trimmed)
|
|
131
|
+
return "";
|
|
132
|
+
if (/\.vibecode-vault/i.test(trimmed))
|
|
133
|
+
return "";
|
|
134
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
|
|
135
|
+
return sanitizeUrlString(trimmed);
|
|
136
|
+
}
|
|
137
|
+
return sanitizeFreeText(trimmed);
|
|
138
|
+
}
|
|
139
|
+
function sanitizeHeaders(rawHeaders) {
|
|
140
|
+
const headers = {};
|
|
141
|
+
if (!isRecord(rawHeaders))
|
|
142
|
+
return headers;
|
|
143
|
+
for (const rawKey of Object.keys(rawHeaders)) {
|
|
144
|
+
const key = rawKey.trim();
|
|
145
|
+
const rawVal = rawHeaders[rawKey];
|
|
146
|
+
if (!key || FORBIDDEN_KEYS.has(key) || rawVal === undefined || rawVal === null)
|
|
147
|
+
continue;
|
|
148
|
+
const strVal = String(rawVal);
|
|
149
|
+
if (isSensitiveHeaderName(key) ||
|
|
150
|
+
strVal.trim() === "[REDACTED]" ||
|
|
151
|
+
BEARER_OR_BASIC_VALUE_RE.test(strVal)) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
headers[key] = sanitizeFreeText(strVal);
|
|
155
|
+
}
|
|
156
|
+
return headers;
|
|
157
|
+
}
|
|
158
|
+
function sanitizeQueryRecord(rawQuery) {
|
|
159
|
+
const out = {};
|
|
160
|
+
if (!isRecord(rawQuery))
|
|
161
|
+
return out;
|
|
162
|
+
for (const rawKey of Object.keys(rawQuery)) {
|
|
163
|
+
const key = rawKey.trim();
|
|
164
|
+
const rawVal = rawQuery[rawKey];
|
|
165
|
+
if (!key || FORBIDDEN_KEYS.has(key) || rawVal === undefined || rawVal === null)
|
|
166
|
+
continue;
|
|
167
|
+
if (isSensitiveQueryName(key))
|
|
168
|
+
continue;
|
|
169
|
+
out[key] = sanitizeFreeText(String(rawVal));
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
function isSecretJsonPath(jsonPath) {
|
|
174
|
+
const cleaned = jsonPath.replace(/\[[^\]]*\]/g, "");
|
|
175
|
+
const parts = cleaned.split(".").filter(Boolean);
|
|
176
|
+
const last = parts[parts.length - 1] ?? "";
|
|
177
|
+
return Boolean(last && SECRET_FIELD_NAME_RE.test(last));
|
|
178
|
+
}
|
|
179
|
+
function sanitizeDeepValue(value, depth = 0, seen = new Set(), maskSecrets = true) {
|
|
180
|
+
if (depth > 20)
|
|
181
|
+
return null;
|
|
182
|
+
if (typeof value === "string")
|
|
183
|
+
return sanitizeFreeText(value);
|
|
184
|
+
if (value === null || typeof value !== "object")
|
|
185
|
+
return value;
|
|
186
|
+
if (seen.has(value))
|
|
187
|
+
return null;
|
|
188
|
+
seen.add(value);
|
|
189
|
+
try {
|
|
190
|
+
if (Array.isArray(value)) {
|
|
191
|
+
return value.map((item) => sanitizeDeepValue(item, depth + 1, seen, maskSecrets));
|
|
192
|
+
}
|
|
193
|
+
const obj = value;
|
|
194
|
+
const out = {};
|
|
195
|
+
for (const k of Object.keys(obj)) {
|
|
196
|
+
if (FORBIDDEN_KEYS.has(k))
|
|
197
|
+
continue;
|
|
198
|
+
const v = obj[k];
|
|
199
|
+
if (v === undefined)
|
|
200
|
+
continue;
|
|
201
|
+
if (maskSecrets && SECRET_FIELD_NAME_RE.test(k)) {
|
|
202
|
+
out[k] = typeof v === "object" && v !== null ? sanitizeDeepValue(v, depth + 1, seen, true) : "[REDACTED]";
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
out[k] = sanitizeDeepValue(v, depth + 1, seen, maskSecrets);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
seen.delete(value);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function sanitizeSchemaDeep(schema, inSecretField = false, depth = 0, seen = new Set()) {
|
|
215
|
+
if (depth > 20)
|
|
216
|
+
return null;
|
|
217
|
+
if (typeof schema === "string")
|
|
218
|
+
return sanitizeFreeText(schema);
|
|
219
|
+
if (schema === null || typeof schema !== "object")
|
|
220
|
+
return schema;
|
|
221
|
+
if (seen.has(schema))
|
|
222
|
+
return {};
|
|
223
|
+
seen.add(schema);
|
|
224
|
+
try {
|
|
225
|
+
if (Array.isArray(schema)) {
|
|
226
|
+
return schema.map((item) => sanitizeSchemaDeep(item, inSecretField, depth + 1, seen));
|
|
227
|
+
}
|
|
228
|
+
const obj = schema;
|
|
229
|
+
const out = {};
|
|
230
|
+
for (const k of Object.keys(obj)) {
|
|
231
|
+
if (FORBIDDEN_KEYS.has(k))
|
|
232
|
+
continue;
|
|
233
|
+
const v = obj[k];
|
|
234
|
+
if (v === undefined)
|
|
235
|
+
continue;
|
|
236
|
+
if (inSecretField && (k === "example" || k === "examples" || k === "default" || k === "const" || k === "enum")) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (k === "properties" && isRecord(v)) {
|
|
240
|
+
const props = {};
|
|
241
|
+
for (const propKey of Object.keys(v)) {
|
|
242
|
+
if (FORBIDDEN_KEYS.has(propKey))
|
|
243
|
+
continue;
|
|
244
|
+
props[propKey] = sanitizeSchemaDeep(v[propKey], inSecretField || SECRET_FIELD_NAME_RE.test(propKey), depth + 1, seen);
|
|
245
|
+
}
|
|
246
|
+
out.properties = props;
|
|
247
|
+
}
|
|
248
|
+
else if (k === "example" || k === "default" || k === "const" || k === "enum" || k === "examples") {
|
|
249
|
+
out[k] = sanitizeDeepValue(v, depth + 1, seen, true);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
out[k] = sanitizeSchemaDeep(v, inSecretField, depth + 1, seen);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
seen.delete(schema);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function sanitizeExpectedStatus(raw) {
|
|
262
|
+
if (typeof raw === "number" && Number.isInteger(raw) && raw >= 100 && raw <= 599) {
|
|
263
|
+
return raw;
|
|
264
|
+
}
|
|
265
|
+
if (Array.isArray(raw)) {
|
|
266
|
+
const valid = raw.filter((s) => typeof s === "number" && Number.isInteger(s) && s >= 100 && s <= 599);
|
|
267
|
+
return valid.length > 0 ? valid : undefined;
|
|
268
|
+
}
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
function sanitizeBodyExact(raw) {
|
|
272
|
+
const trimmed = raw.trim();
|
|
273
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
274
|
+
try {
|
|
275
|
+
const parsed = JSON.parse(trimmed);
|
|
276
|
+
const sanitized = sanitizeDeepValue(parsed, 0, new Set(), true);
|
|
277
|
+
return JSON.stringify(sanitized);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// Fall through to free-text sanitization
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return sanitizeFreeText(raw);
|
|
284
|
+
}
|
|
285
|
+
function safeJsonLiteral(value) {
|
|
286
|
+
const serialized = JSON.stringify(value === undefined ? null : value) ?? "null";
|
|
287
|
+
return serialized
|
|
288
|
+
.replace(/</g, "\\u003c")
|
|
289
|
+
.replace(/>/g, "\\u003e")
|
|
290
|
+
.replace(/&/g, "\\u0026")
|
|
291
|
+
.replace(/\u2028/g, "\\u2028")
|
|
292
|
+
.replace(/\u2029/g, "\\u2029");
|
|
293
|
+
}
|
|
294
|
+
function toStringArray(value) {
|
|
295
|
+
if (typeof value === "string")
|
|
296
|
+
return [value];
|
|
297
|
+
if (Array.isArray(value))
|
|
298
|
+
return value.filter((item) => typeof item === "string");
|
|
299
|
+
return [];
|
|
300
|
+
}
|
|
301
|
+
function normalizeWaitUntil(raw) {
|
|
302
|
+
if (typeof raw === "string" && VALID_WAIT_UNTIL.has(raw)) {
|
|
303
|
+
return raw;
|
|
304
|
+
}
|
|
305
|
+
return "networkidle";
|
|
306
|
+
}
|
|
307
|
+
function sanitizeViewport(raw) {
|
|
308
|
+
if (!isRecord(raw))
|
|
309
|
+
return undefined;
|
|
310
|
+
const width = raw.width;
|
|
311
|
+
const height = raw.height;
|
|
312
|
+
if (typeof width === "number" &&
|
|
313
|
+
typeof height === "number" &&
|
|
314
|
+
Number.isFinite(width) &&
|
|
315
|
+
Number.isFinite(height) &&
|
|
316
|
+
width > 0 &&
|
|
317
|
+
height > 0) {
|
|
318
|
+
return { width: Math.round(width), height: Math.round(height) };
|
|
319
|
+
}
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
322
|
+
function expectsStatusGe500(expectedStatus) {
|
|
323
|
+
if (typeof expectedStatus === "number")
|
|
324
|
+
return expectedStatus >= 500;
|
|
325
|
+
if (Array.isArray(expectedStatus))
|
|
326
|
+
return expectedStatus.some((s) => typeof s === "number" && s >= 500);
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
function validateContractInput(contract) {
|
|
330
|
+
if (!isRecord(contract)) {
|
|
331
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract must be a non-null object.");
|
|
332
|
+
}
|
|
333
|
+
if (!Array.isArray(contract.invariants)) {
|
|
334
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract must contain an invariants array.");
|
|
335
|
+
}
|
|
336
|
+
if (contract.target !== undefined && !isRecord(contract.target)) {
|
|
337
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract target must be an object when provided.");
|
|
338
|
+
}
|
|
339
|
+
for (let i = 0; i < contract.invariants.length; i++) {
|
|
340
|
+
const inv = contract.invariants[i];
|
|
341
|
+
if (!isRecord(inv) || typeof inv.id !== "string" || typeof inv.type !== "string") {
|
|
342
|
+
throw new VibecodeError("CONTRACT_INVALID", `Contract invariant at index ${i} must be an object with string id and type.`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function resolveDefaultTargetForContract(contract, explicitTarget) {
|
|
347
|
+
const explicit = sanitizeTargetString(explicitTarget);
|
|
348
|
+
if (explicit)
|
|
349
|
+
return explicit;
|
|
350
|
+
const sources = Array.isArray(contract.target?.sources) ? contract.target.sources : [];
|
|
351
|
+
for (const src of sources) {
|
|
352
|
+
if (isRecord(src) && typeof src.kind === "string" && typeof src.ref === "string") {
|
|
353
|
+
const k = src.kind.toLowerCase();
|
|
354
|
+
if (k === "web" || k === "url" || k === "api" || k === "http") {
|
|
355
|
+
const clean = sanitizeTargetString(src.ref);
|
|
356
|
+
if (clean)
|
|
357
|
+
return clean;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
for (const src of sources) {
|
|
362
|
+
if (isRecord(src) && typeof src.ref === "string") {
|
|
363
|
+
const clean = sanitizeTargetString(src.ref);
|
|
364
|
+
if (clean)
|
|
365
|
+
return clean;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return "";
|
|
369
|
+
}
|
|
370
|
+
function resolveInvariantDefaultTarget(contract, inv, explicitTarget) {
|
|
371
|
+
const explicit = sanitizeTargetString(explicitTarget);
|
|
372
|
+
if (explicit)
|
|
373
|
+
return explicit;
|
|
374
|
+
const sources = Array.isArray(contract.target?.sources) ? contract.target.sources : [];
|
|
375
|
+
const kindMatches = (kind) => {
|
|
376
|
+
const k = kind.toLowerCase();
|
|
377
|
+
if (inv.type === "http")
|
|
378
|
+
return k === "api" || k === "http" || k === "web" || k === "url";
|
|
379
|
+
return k === "web" || k === "url" || k === "api" || k === "http";
|
|
380
|
+
};
|
|
381
|
+
if (inv.sourceId) {
|
|
382
|
+
const byId = sources.find((s) => isRecord(s) && s.id === inv.sourceId);
|
|
383
|
+
if (byId && typeof byId.ref === "string") {
|
|
384
|
+
const clean = sanitizeTargetString(byId.ref);
|
|
385
|
+
if (clean)
|
|
386
|
+
return clean;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const byKind = sources.find((s) => isRecord(s) && typeof s.kind === "string" && kindMatches(s.kind));
|
|
390
|
+
if (byKind && typeof byKind.ref === "string") {
|
|
391
|
+
const clean = sanitizeTargetString(byKind.ref);
|
|
392
|
+
if (clean)
|
|
393
|
+
return clean;
|
|
394
|
+
}
|
|
395
|
+
return resolveDefaultTargetForContract(contract, explicitTarget);
|
|
396
|
+
}
|
|
397
|
+
function prepareDomAssertions(raw) {
|
|
398
|
+
if (!Array.isArray(raw))
|
|
399
|
+
return [];
|
|
400
|
+
const out = [];
|
|
401
|
+
for (const item of raw) {
|
|
402
|
+
if (!isRecord(item) || typeof item.selector !== "string" || !item.selector.trim())
|
|
403
|
+
continue;
|
|
404
|
+
const entry = {
|
|
405
|
+
selector: sanitizeFreeText(item.selector.trim())
|
|
406
|
+
};
|
|
407
|
+
if (typeof item.count === "number" && Number.isFinite(item.count)) {
|
|
408
|
+
entry.count = item.count;
|
|
409
|
+
}
|
|
410
|
+
if (typeof item.minCount === "number" && Number.isFinite(item.minCount)) {
|
|
411
|
+
entry.minCount = item.minCount;
|
|
412
|
+
}
|
|
413
|
+
out.push(entry);
|
|
414
|
+
}
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
function prepareNetworkExpectations(raw) {
|
|
418
|
+
if (!Array.isArray(raw))
|
|
419
|
+
return [];
|
|
420
|
+
const out = [];
|
|
421
|
+
for (const item of raw) {
|
|
422
|
+
if (!isRecord(item))
|
|
423
|
+
continue;
|
|
424
|
+
const call = item;
|
|
425
|
+
const method = typeof call.method === "string" && call.method.trim() ? call.method.trim().toUpperCase() : "GET";
|
|
426
|
+
const entry = { method };
|
|
427
|
+
if (typeof call.pathPattern === "string" && call.pathPattern.length > 0) {
|
|
428
|
+
entry.pathPattern = sanitizeFreeText(call.pathPattern);
|
|
429
|
+
}
|
|
430
|
+
if (typeof call.path === "string" && call.path.trim().length > 0) {
|
|
431
|
+
entry.path = sanitizePathWithQuery(call.path);
|
|
432
|
+
}
|
|
433
|
+
if (typeof call.status === "number" && Number.isFinite(call.status)) {
|
|
434
|
+
entry.status = call.status;
|
|
435
|
+
}
|
|
436
|
+
if (typeof call.contentType === "string" && call.contentType.trim().length > 0) {
|
|
437
|
+
entry.contentType = sanitizeFreeText(call.contentType.trim());
|
|
438
|
+
}
|
|
439
|
+
if (isRecord(call.jsonSchema)) {
|
|
440
|
+
entry.jsonSchema = sanitizeSchemaDeep(call.jsonSchema);
|
|
441
|
+
}
|
|
442
|
+
out.push(entry);
|
|
443
|
+
}
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
function prepareFlowSteps(rawSteps, defaultTimeoutMs) {
|
|
447
|
+
if (!Array.isArray(rawSteps))
|
|
448
|
+
return [];
|
|
449
|
+
const out = [];
|
|
450
|
+
for (const raw of rawSteps) {
|
|
451
|
+
if (!isRecord(raw) || typeof raw.action !== "string")
|
|
452
|
+
continue;
|
|
453
|
+
const step = raw;
|
|
454
|
+
const action = step.action;
|
|
455
|
+
if (action !== "fill" &&
|
|
456
|
+
action !== "click" &&
|
|
457
|
+
action !== "press" &&
|
|
458
|
+
action !== "goto" &&
|
|
459
|
+
action !== "select" &&
|
|
460
|
+
action !== "waitFor" &&
|
|
461
|
+
action !== "waitForSelector") {
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const timeoutMs = typeof step.timeoutMs === "number" && Number.isFinite(step.timeoutMs) && step.timeoutMs > 0
|
|
465
|
+
? step.timeoutMs
|
|
466
|
+
: action === "goto"
|
|
467
|
+
? defaultTimeoutMs
|
|
468
|
+
: action === "waitFor" || action === "waitForSelector"
|
|
469
|
+
? Math.min(defaultTimeoutMs, 5000)
|
|
470
|
+
: Math.min(defaultTimeoutMs, 5000);
|
|
471
|
+
const selector = typeof step.selector === "string" ? sanitizeFreeText(step.selector) : "";
|
|
472
|
+
const isSensitiveFill = action === "fill" && SENSITIVE_SELECTOR_RE.test(selector);
|
|
473
|
+
const rawVal = step.value !== undefined && step.value !== null ? sanitizeFreeText(String(step.value)) : "";
|
|
474
|
+
out.push({
|
|
475
|
+
action,
|
|
476
|
+
selector,
|
|
477
|
+
value: isSensitiveFill && rawVal.length > 0 ? "[REDACTED]" : rawVal,
|
|
478
|
+
key: typeof step.key === "string" && step.key.length > 0 ? sanitizeFreeText(step.key) : "Enter",
|
|
479
|
+
path: sanitizePathWithQuery(typeof step.url === "string" && step.url.trim()
|
|
480
|
+
? step.url
|
|
481
|
+
: typeof step.path === "string" && step.path.trim()
|
|
482
|
+
? step.path
|
|
483
|
+
: "/"),
|
|
484
|
+
waitUntil: normalizeWaitUntil(step.waitUntil),
|
|
485
|
+
text: typeof step.text === "string"
|
|
486
|
+
? sanitizeFreeText(step.text)
|
|
487
|
+
: step.value !== undefined && step.value !== null
|
|
488
|
+
? sanitizeFreeText(String(step.value))
|
|
489
|
+
: "",
|
|
490
|
+
timeoutMs
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
return out;
|
|
494
|
+
}
|
|
495
|
+
function prepareInvariant(contract, inv, explicitTarget) {
|
|
496
|
+
if (!EXPORTABLE_TYPES.has(inv.type))
|
|
497
|
+
return null;
|
|
498
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
499
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
500
|
+
const defaultTarget = resolveInvariantDefaultTarget(contract, inv, explicitTarget);
|
|
501
|
+
const safeId = sanitizeFreeText(inv.id);
|
|
502
|
+
const safeDesc = sanitizeFreeText(inv.description || inv.id);
|
|
503
|
+
const isHard = inv.severity === "hard";
|
|
504
|
+
if (inv.type === "web_route") {
|
|
505
|
+
const rawRoute = typeof input.urlPath === "string" && input.urlPath.trim()
|
|
506
|
+
? input.urlPath
|
|
507
|
+
: typeof input.path === "string" && input.path.trim()
|
|
508
|
+
? input.path
|
|
509
|
+
: "/";
|
|
510
|
+
const landmarks = Array.isArray(expected.landmarks)
|
|
511
|
+
? expected.landmarks
|
|
512
|
+
.filter((lm) => isRecord(lm) && typeof lm.tag === "string" && lm.tag.trim().length > 0)
|
|
513
|
+
.map((lm) => ({
|
|
514
|
+
tag: sanitizeFreeText(lm.tag.trim()),
|
|
515
|
+
...(lm.required !== undefined ? { required: Boolean(lm.required) } : {}),
|
|
516
|
+
...(typeof lm.textContains === "string" ? { textContains: sanitizeFreeText(lm.textContains) } : {})
|
|
517
|
+
}))
|
|
518
|
+
: [];
|
|
519
|
+
const interactiveLandmarks = Array.isArray(expected.interactiveLandmarks)
|
|
520
|
+
? expected.interactiveLandmarks
|
|
521
|
+
.filter((il) => isRecord(il) &&
|
|
522
|
+
((typeof il.role === "string" && il.role.trim().length > 0) ||
|
|
523
|
+
(typeof il.tag === "string" && il.tag.trim().length > 0)))
|
|
524
|
+
.map((il) => ({
|
|
525
|
+
role: typeof il.role === "string" ? sanitizeFreeText(il.role.trim()) : "",
|
|
526
|
+
tag: typeof il.tag === "string" ? sanitizeFreeText(il.tag.trim()) : "",
|
|
527
|
+
...(typeof il.name === "string" && il.name.trim().length > 0
|
|
528
|
+
? { name: sanitizeFreeText(il.name.trim()) }
|
|
529
|
+
: {})
|
|
530
|
+
}))
|
|
531
|
+
: [];
|
|
532
|
+
const visibleText = [
|
|
533
|
+
...toStringArray(expected.visibleText),
|
|
534
|
+
...toStringArray(expected.bodyContains)
|
|
535
|
+
].map(sanitizeFreeText);
|
|
536
|
+
const hiddenText = toStringArray(expected.hiddenText).map(sanitizeFreeText);
|
|
537
|
+
const enforceNoPageErrors = Boolean(expected.noUncaughtExceptions) ||
|
|
538
|
+
expected.noPageErrors === true ||
|
|
539
|
+
(expected.noPageErrors !== false && isHard);
|
|
540
|
+
const enforceNoServerErrors = !expectsStatusGe500(expected.status) &&
|
|
541
|
+
(expected.noServerErrors === true || (expected.noServerErrors !== false && isHard));
|
|
542
|
+
const routeStatus = sanitizeExpectedStatus(expected.status);
|
|
543
|
+
return {
|
|
544
|
+
id: safeId,
|
|
545
|
+
description: safeDesc,
|
|
546
|
+
type: "web_route",
|
|
547
|
+
defaultTarget,
|
|
548
|
+
routePath: sanitizePathWithQuery(rawRoute),
|
|
549
|
+
query: sanitizeQueryRecord(input.query),
|
|
550
|
+
headers: sanitizeHeaders(input.headers),
|
|
551
|
+
viewport: sanitizeViewport(input.viewport),
|
|
552
|
+
waitUntil: normalizeWaitUntil(input.waitUntil),
|
|
553
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
554
|
+
? input.timeoutMs
|
|
555
|
+
: 15000,
|
|
556
|
+
...(routeStatus !== undefined ? { status: routeStatus } : {}),
|
|
557
|
+
...(typeof expected.titleContains === "string" && expected.titleContains.length > 0
|
|
558
|
+
? { titleContains: sanitizeFreeText(expected.titleContains) }
|
|
559
|
+
: {}),
|
|
560
|
+
landmarks,
|
|
561
|
+
interactiveLandmarks,
|
|
562
|
+
visibleText,
|
|
563
|
+
hiddenText,
|
|
564
|
+
domAssertions: prepareDomAssertions(expected.domAssertions),
|
|
565
|
+
noConsoleErrors: Boolean(expected.noConsoleErrors),
|
|
566
|
+
enforceNoPageErrors,
|
|
567
|
+
enforceNoServerErrors
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
if (inv.type === "web_flow") {
|
|
571
|
+
const rawStart = typeof input.startPath === "string" && input.startPath.trim()
|
|
572
|
+
? input.startPath
|
|
573
|
+
: typeof input.path === "string" && input.path.trim()
|
|
574
|
+
? input.path
|
|
575
|
+
: "/";
|
|
576
|
+
const timeoutMs = typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
577
|
+
? input.timeoutMs
|
|
578
|
+
: 15000;
|
|
579
|
+
const enforceNoPageErrors = Boolean(expected.noUncaughtExceptions) ||
|
|
580
|
+
expected.noPageErrors === true ||
|
|
581
|
+
(expected.noPageErrors !== false && isHard);
|
|
582
|
+
const enforceNoServerErrors = !expectsStatusGe500(expected.status) &&
|
|
583
|
+
(expected.noServerErrors === true || (expected.noServerErrors !== false && isHard));
|
|
584
|
+
return {
|
|
585
|
+
id: safeId,
|
|
586
|
+
description: safeDesc,
|
|
587
|
+
type: "web_flow",
|
|
588
|
+
defaultTarget,
|
|
589
|
+
startPath: sanitizePathWithQuery(rawStart),
|
|
590
|
+
query: sanitizeQueryRecord(input.query),
|
|
591
|
+
headers: sanitizeHeaders(input.headers),
|
|
592
|
+
viewport: sanitizeViewport(input.viewport),
|
|
593
|
+
waitUntil: normalizeWaitUntil(input.waitUntil),
|
|
594
|
+
timeoutMs,
|
|
595
|
+
steps: prepareFlowSteps(input.steps, timeoutMs),
|
|
596
|
+
...(typeof expected.finalUrlIncludes === "string" && expected.finalUrlIncludes.length > 0
|
|
597
|
+
? { finalUrlIncludes: sanitizeFreeText(expected.finalUrlIncludes) }
|
|
598
|
+
: {}),
|
|
599
|
+
visibleText: toStringArray(expected.visibleText).map(sanitizeFreeText),
|
|
600
|
+
hiddenText: toStringArray(expected.hiddenText).map(sanitizeFreeText),
|
|
601
|
+
domAssertions: prepareDomAssertions(expected.domAssertions),
|
|
602
|
+
networkCalls: prepareNetworkExpectations(expected.networkCalls),
|
|
603
|
+
noConsoleErrors: Boolean(expected.noConsoleErrors),
|
|
604
|
+
enforceNoPageErrors,
|
|
605
|
+
enforceNoServerErrors
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
if (inv.type === "web_network") {
|
|
609
|
+
const rawTrigger = typeof input.triggerPath === "string" && input.triggerPath.trim()
|
|
610
|
+
? input.triggerPath
|
|
611
|
+
: typeof input.startPath === "string" && input.startPath.trim()
|
|
612
|
+
? input.startPath
|
|
613
|
+
: typeof input.path === "string" && input.path.trim()
|
|
614
|
+
? input.path
|
|
615
|
+
: "/";
|
|
616
|
+
return {
|
|
617
|
+
id: safeId,
|
|
618
|
+
description: safeDesc,
|
|
619
|
+
type: "web_network",
|
|
620
|
+
defaultTarget,
|
|
621
|
+
triggerPath: sanitizePathWithQuery(rawTrigger),
|
|
622
|
+
query: sanitizeQueryRecord(input.query),
|
|
623
|
+
headers: sanitizeHeaders(input.headers),
|
|
624
|
+
viewport: sanitizeViewport(input.viewport),
|
|
625
|
+
waitUntil: normalizeWaitUntil(input.waitUntil),
|
|
626
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
627
|
+
? input.timeoutMs
|
|
628
|
+
: 15000,
|
|
629
|
+
networkCalls: prepareNetworkExpectations(expected.networkCalls)
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
// http
|
|
633
|
+
const jsonPaths = Array.isArray(expected.jsonPaths)
|
|
634
|
+
? expected.jsonPaths
|
|
635
|
+
.filter((jp) => isRecord(jp) && typeof jp.path === "string")
|
|
636
|
+
.map((jp) => {
|
|
637
|
+
const safePath = sanitizeFreeText(jp.path);
|
|
638
|
+
return {
|
|
639
|
+
path: safePath,
|
|
640
|
+
...(Object.prototype.hasOwnProperty.call(jp, "equals")
|
|
641
|
+
? { equals: isSecretJsonPath(safePath) ? "[REDACTED]" : sanitizeDeepValue(jp.equals) }
|
|
642
|
+
: {}),
|
|
643
|
+
...(typeof jp.matches === "string" ? { matches: sanitizeFreeText(jp.matches) } : {})
|
|
644
|
+
};
|
|
645
|
+
})
|
|
646
|
+
: [];
|
|
647
|
+
const hasBody = input.body !== undefined && input.body !== null;
|
|
648
|
+
const httpStatus = sanitizeExpectedStatus(expected.status);
|
|
649
|
+
return {
|
|
650
|
+
id: safeId,
|
|
651
|
+
description: safeDesc,
|
|
652
|
+
type: "http",
|
|
653
|
+
defaultTarget,
|
|
654
|
+
method: typeof input.method === "string" && input.method.trim() ? input.method.trim().toUpperCase() : "GET",
|
|
655
|
+
path: sanitizePathWithQuery(typeof input.path === "string" ? input.path : "/"),
|
|
656
|
+
query: sanitizeQueryRecord(input.query),
|
|
657
|
+
headers: sanitizeHeaders(input.headers),
|
|
658
|
+
body: hasBody ? sanitizeDeepValue(input.body) : null,
|
|
659
|
+
hasBody,
|
|
660
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
661
|
+
? input.timeoutMs
|
|
662
|
+
: 10000,
|
|
663
|
+
...(httpStatus !== undefined ? { status: httpStatus } : {}),
|
|
664
|
+
...(typeof expected.maxLatencyMs === "number" && Number.isFinite(expected.maxLatencyMs)
|
|
665
|
+
? { maxLatencyMs: expected.maxLatencyMs }
|
|
666
|
+
: {}),
|
|
667
|
+
expectedHeaders: sanitizeHeaders(expected.headers),
|
|
668
|
+
...(expected.bodyExact !== undefined ? { bodyExact: sanitizeBodyExact(String(expected.bodyExact)) } : {}),
|
|
669
|
+
bodyContains: toStringArray(expected.bodyContains).map(sanitizeFreeText),
|
|
670
|
+
...(isRecord(expected.jsonSchema) ? { jsonSchema: sanitizeSchemaDeep(expected.jsonSchema) } : {}),
|
|
671
|
+
...(expected.jsonSubset !== undefined ? { jsonSubset: sanitizeDeepValue(expected.jsonSubset) } : {}),
|
|
672
|
+
jsonPaths
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function buildInteractiveSelector(il) {
|
|
676
|
+
const parts = [];
|
|
677
|
+
const safeRole = il.role.replace(/[^a-zA-Z0-9_-]/g, "");
|
|
678
|
+
const safeTag = il.tag.replace(/[^a-zA-Z0-9_-]/g, "");
|
|
679
|
+
if (safeRole)
|
|
680
|
+
parts.push(`[role="${safeRole}"]`);
|
|
681
|
+
if (safeTag)
|
|
682
|
+
parts.push(safeTag);
|
|
683
|
+
return parts.length > 0 ? parts.join(", ") : "*";
|
|
684
|
+
}
|
|
685
|
+
function emitNetworkCallAssertions(lines, calls) {
|
|
686
|
+
for (const call of calls) {
|
|
687
|
+
lines.push(" {");
|
|
688
|
+
const predicates = [
|
|
689
|
+
`c.method.toUpperCase() === ${safeJsonLiteral(call.method)}`
|
|
690
|
+
];
|
|
691
|
+
if (call.pathPattern !== undefined) {
|
|
692
|
+
lines.push(` const pathRe = new RegExp(${safeJsonLiteral(call.pathPattern)});`);
|
|
693
|
+
predicates.push("pathRe.test(c.pathname)");
|
|
694
|
+
}
|
|
695
|
+
else if (call.path !== undefined) {
|
|
696
|
+
predicates.push(`(c.pathname === ${safeJsonLiteral(call.path)} || c.pathname.includes(${safeJsonLiteral(call.path)}))`);
|
|
697
|
+
}
|
|
698
|
+
if (call.status !== undefined) {
|
|
699
|
+
predicates.push(`c.status === ${safeJsonLiteral(call.status)}`);
|
|
700
|
+
}
|
|
701
|
+
if (call.contentType !== undefined) {
|
|
702
|
+
predicates.push(`c.contentType.toLowerCase().includes(${safeJsonLiteral(call.contentType.toLowerCase())})`);
|
|
703
|
+
}
|
|
704
|
+
lines.push(` const matchedCall = telemetry.networkCalls.find((c) => ${predicates.join(" && ")});`);
|
|
705
|
+
lines.push(" expect(matchedCall).toBeDefined();");
|
|
706
|
+
if (call.jsonSchema !== undefined) {
|
|
707
|
+
lines.push(" const matchedBody = matchedCall && matchedCall.bodyPromise ? await matchedCall.bodyPromise : undefined;");
|
|
708
|
+
lines.push(" expect(matchedBody).toBeDefined();");
|
|
709
|
+
lines.push(` expect(validateSchema(${safeJsonLiteral(call.jsonSchema)}, matchedBody)).toEqual([]);`);
|
|
710
|
+
}
|
|
711
|
+
lines.push(" }");
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
function emitPlaywrightHelpers(lines, specs) {
|
|
715
|
+
if (specs.length === 0)
|
|
716
|
+
return;
|
|
717
|
+
const needsPageTelemetry = specs.some((s) => s.type === "web_route" || s.type === "web_flow" || s.type === "web_network");
|
|
718
|
+
const needsJsonPath = specs.some((s) => s.type === "http" && s.jsonPaths.length > 0);
|
|
719
|
+
const needsJsonSubset = specs.some((s) => s.type === "http" && s.jsonSubset !== undefined);
|
|
720
|
+
const needsJsonSchema = specs.some((s) => (s.type === "http" && s.jsonSchema !== undefined) ||
|
|
721
|
+
((s.type === "web_network" || s.type === "web_flow") &&
|
|
722
|
+
s.networkCalls.some((c) => c.jsonSchema !== undefined)));
|
|
723
|
+
lines.push("function resolveTarget(kind: \"web\" | \"http\", fallback: string): string {");
|
|
724
|
+
lines.push(" const specific =");
|
|
725
|
+
lines.push(' kind === "http"');
|
|
726
|
+
lines.push(" ? process.env.VIBECODE_API_TARGET || process.env.VIBECODE_HTTP_TARGET");
|
|
727
|
+
lines.push(" : process.env.VIBECODE_WEB_TARGET || process.env.VIBECODE_API_TARGET || process.env.VIBECODE_HTTP_TARGET;");
|
|
728
|
+
lines.push(" if (specific && specific.trim()) return specific.trim();");
|
|
729
|
+
lines.push(" const raw = process.env.VIBECODE_TARGET;");
|
|
730
|
+
lines.push(" if (raw && raw.trim()) {");
|
|
731
|
+
lines.push(" const trimmed = raw.trim();");
|
|
732
|
+
lines.push(' if (trimmed.startsWith("{")) {');
|
|
733
|
+
lines.push(" try {");
|
|
734
|
+
lines.push(" const parsed = JSON.parse(trimmed) as Record<string, unknown>;");
|
|
735
|
+
lines.push(' if (parsed && typeof parsed === "object") {');
|
|
736
|
+
lines.push(' const keys = kind === "http" ? ["http", "api", "default"] : ["web", "web_route", "http", "api", "default"];');
|
|
737
|
+
lines.push(" for (const key of keys) {");
|
|
738
|
+
lines.push(" const candidate = parsed[key];");
|
|
739
|
+
lines.push(' if (typeof candidate === "string" && candidate.trim()) return candidate.trim();');
|
|
740
|
+
lines.push(" }");
|
|
741
|
+
lines.push(" }");
|
|
742
|
+
lines.push(" } catch {");
|
|
743
|
+
lines.push(" // Treat as plain URL string");
|
|
744
|
+
lines.push(" }");
|
|
745
|
+
lines.push(" }");
|
|
746
|
+
lines.push(" return trimmed;");
|
|
747
|
+
lines.push(" }");
|
|
748
|
+
lines.push(" return fallback || BASE_TARGET;");
|
|
749
|
+
lines.push("}");
|
|
750
|
+
lines.push("");
|
|
751
|
+
lines.push("function resolveUrl(baseUrl: string, pathOrUrl: string, query?: Record<string, string>): string {");
|
|
752
|
+
lines.push(' if (!baseUrl && !/^https?:\\/\\//i.test(pathOrUrl)) {');
|
|
753
|
+
lines.push(' throw new Error("Missing target URL: set VIBECODE_TARGET.");');
|
|
754
|
+
lines.push(" }");
|
|
755
|
+
lines.push(' const normalizedBase = /^https?:\\/\\//i.test(baseUrl) ? baseUrl : "http://" + baseUrl;');
|
|
756
|
+
lines.push(' const url = /^https?:\\/\\//i.test(pathOrUrl) ? new URL(pathOrUrl) : new URL(pathOrUrl || "/", normalizedBase);');
|
|
757
|
+
lines.push(" if (query) {");
|
|
758
|
+
lines.push(" for (const [k, v] of Object.entries(query)) {");
|
|
759
|
+
lines.push(" url.searchParams.set(k, String(v));");
|
|
760
|
+
lines.push(" }");
|
|
761
|
+
lines.push(" }");
|
|
762
|
+
lines.push(" return url.toString();");
|
|
763
|
+
lines.push("}");
|
|
764
|
+
lines.push("");
|
|
765
|
+
lines.push("function applyAuthHeaders(headers: Record<string, string>): Record<string, string> {");
|
|
766
|
+
lines.push(" const out: Record<string, string> = { ...headers };");
|
|
767
|
+
lines.push(" const raw = process.env.VIBECODE_AUTH_HEADER;");
|
|
768
|
+
lines.push(" if (!raw || !raw.trim()) return out;");
|
|
769
|
+
lines.push(' const idx = raw.indexOf(":");');
|
|
770
|
+
lines.push(" if (idx > 0) {");
|
|
771
|
+
lines.push(" const name = raw.slice(0, idx).trim();");
|
|
772
|
+
lines.push(" const value = raw.slice(idx + 1).trim();");
|
|
773
|
+
lines.push(" if (name) {");
|
|
774
|
+
lines.push(" out[name] = value;");
|
|
775
|
+
lines.push(" return out;");
|
|
776
|
+
lines.push(" }");
|
|
777
|
+
lines.push(" }");
|
|
778
|
+
lines.push(' out["Authorization"] = raw.trim();');
|
|
779
|
+
lines.push(" return out;");
|
|
780
|
+
lines.push("}");
|
|
781
|
+
lines.push("");
|
|
782
|
+
if (needsJsonPath) {
|
|
783
|
+
lines.push("function queryJsonPath(doc: unknown, jsonPath: string): { found: boolean; value: unknown } {");
|
|
784
|
+
lines.push(' if (typeof jsonPath !== "string" || !jsonPath.startsWith("$")) return { found: false, value: undefined };');
|
|
785
|
+
lines.push(" let cur: unknown = doc;");
|
|
786
|
+
lines.push(" const tokens: Array<string | number> = [];");
|
|
787
|
+
lines.push(' const re = /\\.([A-Za-z_$][A-Za-z0-9_$-]*)|\\[(\\d+)\\]|\\[(?:"([^"]*)"|\'([^\']*)\')\\]/g;');
|
|
788
|
+
lines.push(" let i = 1;");
|
|
789
|
+
lines.push(" while (i < jsonPath.length) {");
|
|
790
|
+
lines.push(" re.lastIndex = i;");
|
|
791
|
+
lines.push(" const m = re.exec(jsonPath);");
|
|
792
|
+
lines.push(" if (!m || m.index !== i) return { found: false, value: undefined };");
|
|
793
|
+
lines.push(" if (m[1] !== undefined) tokens.push(m[1]);");
|
|
794
|
+
lines.push(" else if (m[2] !== undefined) tokens.push(Number(m[2]));");
|
|
795
|
+
lines.push(" else if (m[3] !== undefined) tokens.push(m[3]);");
|
|
796
|
+
lines.push(" else if (m[4] !== undefined) tokens.push(m[4]);");
|
|
797
|
+
lines.push(" i = re.lastIndex;");
|
|
798
|
+
lines.push(" }");
|
|
799
|
+
lines.push(" for (const tok of tokens) {");
|
|
800
|
+
lines.push(" if (cur === null || cur === undefined) return { found: false, value: undefined };");
|
|
801
|
+
lines.push(' if (typeof tok === "number") {');
|
|
802
|
+
lines.push(" if (!Array.isArray(cur) || tok < 0 || tok >= cur.length) return { found: false, value: undefined };");
|
|
803
|
+
lines.push(" cur = cur[tok];");
|
|
804
|
+
lines.push(" } else {");
|
|
805
|
+
lines.push(' if (typeof cur !== "object" || !(tok in cur)) return { found: false, value: undefined };');
|
|
806
|
+
lines.push(" cur = (cur as Record<string, unknown>)[tok];");
|
|
807
|
+
lines.push(" }");
|
|
808
|
+
lines.push(" }");
|
|
809
|
+
lines.push(" return { found: true, value: cur };");
|
|
810
|
+
lines.push("}");
|
|
811
|
+
lines.push("");
|
|
812
|
+
}
|
|
813
|
+
if (needsJsonSubset) {
|
|
814
|
+
lines.push("function matchesJsonSubset(actual: unknown, expected: unknown): boolean {");
|
|
815
|
+
lines.push(" if (Array.isArray(expected)) {");
|
|
816
|
+
lines.push(" if (!Array.isArray(actual) || actual.length < expected.length) return false;");
|
|
817
|
+
lines.push(" for (let i = 0; i < expected.length; i++) {");
|
|
818
|
+
lines.push(" if (!matchesJsonSubset(actual[i], expected[i])) return false;");
|
|
819
|
+
lines.push(" }");
|
|
820
|
+
lines.push(" return true;");
|
|
821
|
+
lines.push(" }");
|
|
822
|
+
lines.push(' if (expected !== null && typeof expected === "object") {');
|
|
823
|
+
lines.push(' if (actual === null || typeof actual !== "object" || Array.isArray(actual)) return false;');
|
|
824
|
+
lines.push(" const actObj = actual as Record<string, unknown>;");
|
|
825
|
+
lines.push(" for (const [k, v] of Object.entries(expected as Record<string, unknown>)) {");
|
|
826
|
+
lines.push(" if (!(k in actObj) || !matchesJsonSubset(actObj[k], v)) return false;");
|
|
827
|
+
lines.push(" }");
|
|
828
|
+
lines.push(" return true;");
|
|
829
|
+
lines.push(" }");
|
|
830
|
+
lines.push(" return actual === expected;");
|
|
831
|
+
lines.push("}");
|
|
832
|
+
lines.push("");
|
|
833
|
+
}
|
|
834
|
+
if (needsJsonSchema) {
|
|
835
|
+
lines.push('function validateSchema(schema: Record<string, unknown>, value: unknown, path = "$"): string[] {');
|
|
836
|
+
lines.push(" const errors: string[] = [];");
|
|
837
|
+
lines.push(' if (!schema || typeof schema !== "object") return errors;');
|
|
838
|
+
lines.push(" if (schema.nullable === true && value === null) return errors;");
|
|
839
|
+
lines.push(" if (schema.type !== undefined) {");
|
|
840
|
+
lines.push(" const types = Array.isArray(schema.type) ? schema.type : [schema.type];");
|
|
841
|
+
lines.push(" const matches = (typ: unknown): boolean => {");
|
|
842
|
+
lines.push(' if (typ === "null") return value === null;');
|
|
843
|
+
lines.push(' if (typ === "array") return Array.isArray(value);');
|
|
844
|
+
lines.push(' if (typ === "object") return value !== null && typeof value === "object" && !Array.isArray(value);');
|
|
845
|
+
lines.push(' if (typ === "integer") return typeof value === "number" && Number.isInteger(value);');
|
|
846
|
+
lines.push(' if (typ === "number") return typeof value === "number" && Number.isFinite(value);');
|
|
847
|
+
lines.push(' if (typ === "string") return typeof value === "string";');
|
|
848
|
+
lines.push(' if (typ === "boolean") return typeof value === "boolean";');
|
|
849
|
+
lines.push(" return true;");
|
|
850
|
+
lines.push(" };");
|
|
851
|
+
lines.push(' if (!types.some(matches)) errors.push(path + ": expected type " + JSON.stringify(schema.type));');
|
|
852
|
+
lines.push(" }");
|
|
853
|
+
lines.push(' if (Object.prototype.hasOwnProperty.call(schema, "const") && JSON.stringify(value) !== JSON.stringify(schema.const)) {');
|
|
854
|
+
lines.push(' errors.push(path + ": expected const " + JSON.stringify(schema.const));');
|
|
855
|
+
lines.push(" }");
|
|
856
|
+
lines.push(" if (Array.isArray(schema.enum) && !schema.enum.some((e) => JSON.stringify(e) === JSON.stringify(value))) {");
|
|
857
|
+
lines.push(' errors.push(path + ": value not in enum");');
|
|
858
|
+
lines.push(" }");
|
|
859
|
+
lines.push(' if (typeof value === "string") {');
|
|
860
|
+
lines.push(' if (typeof schema.minLength === "number" && value.length < schema.minLength) errors.push(path + ": string shorter than minLength");');
|
|
861
|
+
lines.push(' if (typeof schema.maxLength === "number" && value.length > schema.maxLength) errors.push(path + ": string longer than maxLength");');
|
|
862
|
+
lines.push(' if (typeof schema.pattern === "string" && !new RegExp(schema.pattern).test(value)) errors.push(path + ": string pattern mismatch");');
|
|
863
|
+
lines.push(" }");
|
|
864
|
+
lines.push(' if (typeof value === "number") {');
|
|
865
|
+
lines.push(' if (typeof schema.minimum === "number" && value < schema.minimum) errors.push(path + ": number below minimum");');
|
|
866
|
+
lines.push(' if (typeof schema.maximum === "number" && value > schema.maximum) errors.push(path + ": number above maximum");');
|
|
867
|
+
lines.push(" }");
|
|
868
|
+
lines.push(" if (Array.isArray(value)) {");
|
|
869
|
+
lines.push(' if (typeof schema.minItems === "number" && value.length < schema.minItems) errors.push(path + ": fewer items than minItems");');
|
|
870
|
+
lines.push(' if (typeof schema.maxItems === "number" && value.length > schema.maxItems) errors.push(path + ": more items than maxItems");');
|
|
871
|
+
lines.push(' if (schema.items && typeof schema.items === "object" && !Array.isArray(schema.items)) {');
|
|
872
|
+
lines.push(" for (let i = 0; i < value.length; i++) {");
|
|
873
|
+
lines.push(' errors.push(...validateSchema(schema.items as Record<string, unknown>, value[i], path + "[" + i + "]"));');
|
|
874
|
+
lines.push(" }");
|
|
875
|
+
lines.push(" }");
|
|
876
|
+
lines.push(" }");
|
|
877
|
+
lines.push(' if (value !== null && typeof value === "object" && !Array.isArray(value)) {');
|
|
878
|
+
lines.push(" const rec = value as Record<string, unknown>;");
|
|
879
|
+
lines.push(" if (Array.isArray(schema.required)) {");
|
|
880
|
+
lines.push(" for (const reqKey of schema.required) {");
|
|
881
|
+
lines.push(' if (typeof reqKey === "string" && !(reqKey in rec)) errors.push(path + "." + reqKey + ": missing required property");');
|
|
882
|
+
lines.push(" }");
|
|
883
|
+
lines.push(" }");
|
|
884
|
+
lines.push(' if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {');
|
|
885
|
+
lines.push(" for (const [k, sub] of Object.entries(schema.properties as Record<string, unknown>)) {");
|
|
886
|
+
lines.push(' if (k in rec && sub && typeof sub === "object" && !Array.isArray(sub)) {');
|
|
887
|
+
lines.push(' errors.push(...validateSchema(sub as Record<string, unknown>, rec[k], path + "." + k));');
|
|
888
|
+
lines.push(" }");
|
|
889
|
+
lines.push(" }");
|
|
890
|
+
lines.push(" }");
|
|
891
|
+
lines.push(" }");
|
|
892
|
+
lines.push(" return errors;");
|
|
893
|
+
lines.push("}");
|
|
894
|
+
lines.push("");
|
|
895
|
+
}
|
|
896
|
+
if (needsPageTelemetry) {
|
|
897
|
+
lines.push("interface TelemetryResponseLike {");
|
|
898
|
+
lines.push(" url(): string;");
|
|
899
|
+
lines.push(" status(): number;");
|
|
900
|
+
lines.push(" request(): { method(): string };");
|
|
901
|
+
lines.push(" headers(): Record<string, string>;");
|
|
902
|
+
lines.push(" json?(): Promise<unknown>;");
|
|
903
|
+
lines.push("}");
|
|
904
|
+
lines.push("");
|
|
905
|
+
lines.push("interface TelemetryPageLike {");
|
|
906
|
+
lines.push(' on(event: "console", listener: (msg: { type(): string; text(): string }) => void): unknown;');
|
|
907
|
+
lines.push(' on(event: "pageerror", listener: (err: Error) => void): unknown;');
|
|
908
|
+
lines.push(' on(event: "response", listener: (res: TelemetryResponseLike) => void): unknown;');
|
|
909
|
+
lines.push("}");
|
|
910
|
+
lines.push("");
|
|
911
|
+
lines.push("interface NetworkCallRecord {");
|
|
912
|
+
lines.push(" method: string;");
|
|
913
|
+
lines.push(" pathname: string;");
|
|
914
|
+
lines.push(" status: number;");
|
|
915
|
+
lines.push(" contentType: string;");
|
|
916
|
+
lines.push(" bodyPromise?: Promise<unknown>;");
|
|
917
|
+
lines.push("}");
|
|
918
|
+
lines.push("");
|
|
919
|
+
lines.push("function attachPageTelemetry(page: TelemetryPageLike, captureJsonBodies = false) {");
|
|
920
|
+
lines.push(" const consoleErrors: string[] = [];");
|
|
921
|
+
lines.push(" const pageErrors: string[] = [];");
|
|
922
|
+
lines.push(" const serverErrors: NetworkCallRecord[] = [];");
|
|
923
|
+
lines.push(" const networkCalls: NetworkCallRecord[] = [];");
|
|
924
|
+
lines.push(' page.on("console", (msg) => {');
|
|
925
|
+
lines.push(' if (msg.type() === "error") consoleErrors.push(msg.text());');
|
|
926
|
+
lines.push(" });");
|
|
927
|
+
lines.push(' page.on("pageerror", (err) => {');
|
|
928
|
+
lines.push(" pageErrors.push(err?.message || String(err));");
|
|
929
|
+
lines.push(" });");
|
|
930
|
+
lines.push(' page.on("response", (res) => {');
|
|
931
|
+
lines.push(" try {");
|
|
932
|
+
lines.push(" const parsed = new URL(res.url());");
|
|
933
|
+
lines.push(" const headers = res.headers();");
|
|
934
|
+
lines.push(' const contentType = headers["content-type"] || "";');
|
|
935
|
+
lines.push(" const rec: NetworkCallRecord = {");
|
|
936
|
+
lines.push(" method: res.request().method().toUpperCase(),");
|
|
937
|
+
lines.push(" pathname: parsed.pathname,");
|
|
938
|
+
lines.push(" status: res.status(),");
|
|
939
|
+
lines.push(" contentType,");
|
|
940
|
+
lines.push(' ...(captureJsonBodies && typeof res.json === "function" ? { bodyPromise: res.json().catch(() => undefined) } : {})');
|
|
941
|
+
lines.push(" };");
|
|
942
|
+
lines.push(" networkCalls.push(rec);");
|
|
943
|
+
lines.push(" if (rec.status >= 500) serverErrors.push(rec);");
|
|
944
|
+
lines.push(" } catch {");
|
|
945
|
+
lines.push(" // Ignore non-HTTP URLs (e.g. data:, blob:)");
|
|
946
|
+
lines.push(" }");
|
|
947
|
+
lines.push(" });");
|
|
948
|
+
lines.push(" return { consoleErrors, pageErrors, serverErrors, networkCalls };");
|
|
949
|
+
lines.push("}");
|
|
950
|
+
lines.push("");
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
function emitWebRouteTest(lines, spec) {
|
|
954
|
+
const label = `${spec.id}: ${spec.description}`;
|
|
955
|
+
lines.push(` test(${safeJsonLiteral(label)}, async ({ page }) => {`);
|
|
956
|
+
lines.push(` const baseTarget = resolveTarget("web", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
957
|
+
lines.push(Object.keys(spec.query).length > 0
|
|
958
|
+
? ` const targetUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.routePath)}, ${safeJsonLiteral(spec.query)});`
|
|
959
|
+
: ` const targetUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.routePath)});`);
|
|
960
|
+
if (spec.viewport) {
|
|
961
|
+
lines.push(` await page.setViewportSize({ width: ${spec.viewport.width}, height: ${spec.viewport.height} });`);
|
|
962
|
+
}
|
|
963
|
+
lines.push(` const extraHeaders = applyAuthHeaders(${safeJsonLiteral(spec.headers)});`);
|
|
964
|
+
lines.push(" if (Object.keys(extraHeaders).length > 0) {");
|
|
965
|
+
lines.push(" await page.setExtraHTTPHeaders(extraHeaders);");
|
|
966
|
+
lines.push(" }");
|
|
967
|
+
lines.push(" const telemetry = attachPageTelemetry(page);");
|
|
968
|
+
lines.push(` const response = await page.goto(targetUrl, { waitUntil: ${safeJsonLiteral(spec.waitUntil)}, timeout: ${safeJsonLiteral(spec.timeoutMs)} });`);
|
|
969
|
+
lines.push(" const status = response ? response.status() : 200;");
|
|
970
|
+
if (spec.status !== undefined) {
|
|
971
|
+
if (Array.isArray(spec.status)) {
|
|
972
|
+
lines.push(` expect(${safeJsonLiteral(spec.status)}).toContain(status);`);
|
|
973
|
+
}
|
|
974
|
+
else {
|
|
975
|
+
lines.push(` expect(status).toBe(${safeJsonLiteral(spec.status)});`);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (spec.enforceNoServerErrors) {
|
|
979
|
+
lines.push(" expect(status).toBeLessThan(500);");
|
|
980
|
+
lines.push(" expect(telemetry.serverErrors).toEqual([]);");
|
|
981
|
+
}
|
|
982
|
+
if (spec.titleContains !== undefined) {
|
|
983
|
+
lines.push(` expect(await page.title()).toContain(${safeJsonLiteral(spec.titleContains)});`);
|
|
984
|
+
}
|
|
985
|
+
for (const lm of spec.landmarks) {
|
|
986
|
+
if (lm.required === false)
|
|
987
|
+
continue;
|
|
988
|
+
lines.push(" {");
|
|
989
|
+
lines.push(` const landmark = page.locator(${safeJsonLiteral(lm.tag)});`);
|
|
990
|
+
lines.push(" expect(await landmark.count()).toBeGreaterThan(0);");
|
|
991
|
+
if (lm.textContains) {
|
|
992
|
+
lines.push(" const landmarkTexts = await landmark.allInnerTexts();");
|
|
993
|
+
lines.push(` expect(landmarkTexts.some((t) => t.includes(${safeJsonLiteral(lm.textContains)}))).toBe(true);`);
|
|
994
|
+
}
|
|
995
|
+
lines.push(" }");
|
|
996
|
+
}
|
|
997
|
+
for (const il of spec.interactiveLandmarks) {
|
|
998
|
+
const selector = buildInteractiveSelector(il);
|
|
999
|
+
lines.push(" {");
|
|
1000
|
+
lines.push(` const interactive = page.locator(${safeJsonLiteral(selector)});`);
|
|
1001
|
+
lines.push(" expect(await interactive.count()).toBeGreaterThan(0);");
|
|
1002
|
+
if (il.name) {
|
|
1003
|
+
lines.push(" const names = await interactive.evaluateAll((els) =>");
|
|
1004
|
+
lines.push(" els.map((el) =>");
|
|
1005
|
+
lines.push(' (el.getAttribute("aria-label") || (el as { innerText?: string }).innerText || el.textContent || el.getAttribute("title") || el.getAttribute("placeholder") || "")');
|
|
1006
|
+
lines.push(" .trim()");
|
|
1007
|
+
lines.push(" .toLowerCase()");
|
|
1008
|
+
lines.push(" )");
|
|
1009
|
+
lines.push(" );");
|
|
1010
|
+
lines.push(` expect(names.some((n) => n.includes(${safeJsonLiteral(il.name.toLowerCase())}))).toBe(true);`);
|
|
1011
|
+
}
|
|
1012
|
+
lines.push(" }");
|
|
1013
|
+
}
|
|
1014
|
+
if (spec.visibleText.length > 0 || spec.hiddenText.length > 0) {
|
|
1015
|
+
lines.push(' const bodyText = await page.locator("body").innerText();');
|
|
1016
|
+
for (const needle of spec.visibleText) {
|
|
1017
|
+
lines.push(` expect(bodyText).toContain(${safeJsonLiteral(needle)});`);
|
|
1018
|
+
}
|
|
1019
|
+
for (const needle of spec.hiddenText) {
|
|
1020
|
+
lines.push(` expect(bodyText).not.toContain(${safeJsonLiteral(needle)});`);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
for (const dom of spec.domAssertions) {
|
|
1024
|
+
lines.push(" {");
|
|
1025
|
+
lines.push(` const count = await page.locator(${safeJsonLiteral(dom.selector)}).count();`);
|
|
1026
|
+
if (typeof dom.count === "number") {
|
|
1027
|
+
lines.push(` expect(count).toBe(${safeJsonLiteral(dom.count)});`);
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
lines.push(` expect(count).toBeGreaterThanOrEqual(${safeJsonLiteral(dom.minCount ?? 1)});`);
|
|
1031
|
+
}
|
|
1032
|
+
lines.push(" }");
|
|
1033
|
+
}
|
|
1034
|
+
if (spec.noConsoleErrors) {
|
|
1035
|
+
lines.push(" expect(telemetry.consoleErrors).toEqual([]);");
|
|
1036
|
+
}
|
|
1037
|
+
if (spec.enforceNoPageErrors) {
|
|
1038
|
+
lines.push(" expect(telemetry.pageErrors).toEqual([]);");
|
|
1039
|
+
}
|
|
1040
|
+
lines.push(" });");
|
|
1041
|
+
lines.push("");
|
|
1042
|
+
}
|
|
1043
|
+
function emitWebFlowTest(lines, spec) {
|
|
1044
|
+
const label = `${spec.id}: ${spec.description}`;
|
|
1045
|
+
const captureJsonBodies = spec.networkCalls.some((c) => c.jsonSchema !== undefined);
|
|
1046
|
+
lines.push(` test(${safeJsonLiteral(label)}, async ({ page }) => {`);
|
|
1047
|
+
lines.push(` const baseTarget = resolveTarget("web", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
1048
|
+
lines.push(Object.keys(spec.query).length > 0
|
|
1049
|
+
? ` const startUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.startPath)}, ${safeJsonLiteral(spec.query)});`
|
|
1050
|
+
: ` const startUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.startPath)});`);
|
|
1051
|
+
if (spec.viewport) {
|
|
1052
|
+
lines.push(` await page.setViewportSize({ width: ${spec.viewport.width}, height: ${spec.viewport.height} });`);
|
|
1053
|
+
}
|
|
1054
|
+
lines.push(` const extraHeaders = applyAuthHeaders(${safeJsonLiteral(spec.headers)});`);
|
|
1055
|
+
lines.push(" if (Object.keys(extraHeaders).length > 0) {");
|
|
1056
|
+
lines.push(" await page.setExtraHTTPHeaders(extraHeaders);");
|
|
1057
|
+
lines.push(" }");
|
|
1058
|
+
lines.push(captureJsonBodies
|
|
1059
|
+
? " const telemetry = attachPageTelemetry(page, true);"
|
|
1060
|
+
: " const telemetry = attachPageTelemetry(page);");
|
|
1061
|
+
lines.push(` await page.goto(startUrl, { waitUntil: ${safeJsonLiteral(spec.waitUntil)}, timeout: ${safeJsonLiteral(spec.timeoutMs)} });`);
|
|
1062
|
+
for (const step of spec.steps) {
|
|
1063
|
+
if (step.action === "fill") {
|
|
1064
|
+
lines.push(` await page.fill(${safeJsonLiteral(step.selector)}, ${safeJsonLiteral(step.value)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1065
|
+
}
|
|
1066
|
+
else if (step.action === "click") {
|
|
1067
|
+
lines.push(` await page.click(${safeJsonLiteral(step.selector)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1068
|
+
}
|
|
1069
|
+
else if (step.action === "press") {
|
|
1070
|
+
lines.push(` await page.press(${safeJsonLiteral(step.selector)}, ${safeJsonLiteral(step.key)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1071
|
+
}
|
|
1072
|
+
else if (step.action === "goto") {
|
|
1073
|
+
lines.push(` await page.goto(resolveUrl(baseTarget, ${safeJsonLiteral(step.path)}), { waitUntil: ${safeJsonLiteral(step.waitUntil)}, timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1074
|
+
}
|
|
1075
|
+
else if (step.action === "select") {
|
|
1076
|
+
lines.push(` await page.selectOption(${safeJsonLiteral(step.selector)}, ${safeJsonLiteral(step.value)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1077
|
+
}
|
|
1078
|
+
else if (step.action === "waitFor") {
|
|
1079
|
+
lines.push(` await page.waitForFunction((txt: string) => Boolean(document.body && document.body.innerText.includes(txt)), ${safeJsonLiteral(step.text)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1080
|
+
}
|
|
1081
|
+
else if (step.action === "waitForSelector") {
|
|
1082
|
+
lines.push(` await page.waitForSelector(${safeJsonLiteral(step.selector)}, { timeout: ${safeJsonLiteral(step.timeoutMs)} });`);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (spec.finalUrlIncludes !== undefined) {
|
|
1086
|
+
lines.push(` expect(page.url()).toContain(${safeJsonLiteral(spec.finalUrlIncludes)});`);
|
|
1087
|
+
}
|
|
1088
|
+
if (spec.visibleText.length > 0 || spec.hiddenText.length > 0) {
|
|
1089
|
+
lines.push(' const bodyText = await page.locator("body").innerText();');
|
|
1090
|
+
for (const needle of spec.visibleText) {
|
|
1091
|
+
lines.push(` expect(bodyText).toContain(${safeJsonLiteral(needle)});`);
|
|
1092
|
+
}
|
|
1093
|
+
for (const needle of spec.hiddenText) {
|
|
1094
|
+
lines.push(` expect(bodyText).not.toContain(${safeJsonLiteral(needle)});`);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
for (const dom of spec.domAssertions) {
|
|
1098
|
+
lines.push(" {");
|
|
1099
|
+
lines.push(` const count = await page.locator(${safeJsonLiteral(dom.selector)}).count();`);
|
|
1100
|
+
if (typeof dom.count === "number") {
|
|
1101
|
+
lines.push(` expect(count).toBe(${safeJsonLiteral(dom.count)});`);
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
lines.push(` expect(count).toBeGreaterThanOrEqual(${safeJsonLiteral(dom.minCount ?? 1)});`);
|
|
1105
|
+
}
|
|
1106
|
+
lines.push(" }");
|
|
1107
|
+
}
|
|
1108
|
+
if (spec.networkCalls.length > 0) {
|
|
1109
|
+
emitNetworkCallAssertions(lines, spec.networkCalls);
|
|
1110
|
+
}
|
|
1111
|
+
if (spec.noConsoleErrors) {
|
|
1112
|
+
lines.push(" expect(telemetry.consoleErrors).toEqual([]);");
|
|
1113
|
+
}
|
|
1114
|
+
if (spec.enforceNoPageErrors) {
|
|
1115
|
+
lines.push(" expect(telemetry.pageErrors).toEqual([]);");
|
|
1116
|
+
}
|
|
1117
|
+
if (spec.enforceNoServerErrors) {
|
|
1118
|
+
const expected500 = spec.networkCalls.filter((c) => typeof c.status === "number" && c.status >= 500);
|
|
1119
|
+
if (expected500.length > 0) {
|
|
1120
|
+
lines.push(` const expected500: Array<{ method: string; pathPattern: string | null; path: string | null; status: number }> = ${safeJsonLiteral(expected500.map((c) => ({ method: c.method, pathPattern: c.pathPattern ?? null, path: c.path ?? null, status: c.status })))};`);
|
|
1121
|
+
lines.push(" const unexpectedServerErrors = telemetry.serverErrors.filter((c) =>");
|
|
1122
|
+
lines.push(" !expected500.some((exp) => exp.method === c.method && exp.status === c.status && (exp.pathPattern ? new RegExp(exp.pathPattern).test(c.pathname) : exp.path ? (c.pathname === exp.path || c.pathname.includes(exp.path)) : true))");
|
|
1123
|
+
lines.push(" );");
|
|
1124
|
+
lines.push(" expect(unexpectedServerErrors).toEqual([]);");
|
|
1125
|
+
}
|
|
1126
|
+
else {
|
|
1127
|
+
lines.push(" expect(telemetry.serverErrors).toEqual([]);");
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
lines.push(" });");
|
|
1131
|
+
lines.push("");
|
|
1132
|
+
}
|
|
1133
|
+
function emitWebNetworkTest(lines, spec) {
|
|
1134
|
+
const label = `${spec.id}: ${spec.description}`;
|
|
1135
|
+
const captureJsonBodies = spec.networkCalls.some((c) => c.jsonSchema !== undefined);
|
|
1136
|
+
lines.push(` test(${safeJsonLiteral(label)}, async ({ page }) => {`);
|
|
1137
|
+
lines.push(` const baseTarget = resolveTarget("web", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
1138
|
+
lines.push(Object.keys(spec.query).length > 0
|
|
1139
|
+
? ` const triggerUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.triggerPath)}, ${safeJsonLiteral(spec.query)});`
|
|
1140
|
+
: ` const triggerUrl = resolveUrl(baseTarget, ${safeJsonLiteral(spec.triggerPath)});`);
|
|
1141
|
+
if (spec.viewport) {
|
|
1142
|
+
lines.push(` await page.setViewportSize({ width: ${spec.viewport.width}, height: ${spec.viewport.height} });`);
|
|
1143
|
+
}
|
|
1144
|
+
lines.push(` const extraHeaders = applyAuthHeaders(${safeJsonLiteral(spec.headers)});`);
|
|
1145
|
+
lines.push(" if (Object.keys(extraHeaders).length > 0) {");
|
|
1146
|
+
lines.push(" await page.setExtraHTTPHeaders(extraHeaders);");
|
|
1147
|
+
lines.push(" }");
|
|
1148
|
+
lines.push(captureJsonBodies
|
|
1149
|
+
? " const telemetry = attachPageTelemetry(page, true);"
|
|
1150
|
+
: " const telemetry = attachPageTelemetry(page);");
|
|
1151
|
+
lines.push(` await page.goto(triggerUrl, { waitUntil: ${safeJsonLiteral(spec.waitUntil)}, timeout: ${safeJsonLiteral(spec.timeoutMs)} });`);
|
|
1152
|
+
if (spec.networkCalls.length > 0) {
|
|
1153
|
+
emitNetworkCallAssertions(lines, spec.networkCalls);
|
|
1154
|
+
}
|
|
1155
|
+
lines.push(" });");
|
|
1156
|
+
lines.push("");
|
|
1157
|
+
}
|
|
1158
|
+
function emitHttpTest(lines, spec) {
|
|
1159
|
+
const label = `${spec.id}: ${spec.description}`;
|
|
1160
|
+
const sendBody = spec.hasBody && spec.method !== "GET" && spec.method !== "HEAD";
|
|
1161
|
+
lines.push(` test(${safeJsonLiteral(label)}, async ({ request }) => {`);
|
|
1162
|
+
lines.push(` const baseTarget = resolveTarget("http", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
1163
|
+
lines.push(Object.keys(spec.query).length > 0
|
|
1164
|
+
? ` const url = resolveUrl(baseTarget, ${safeJsonLiteral(spec.path)}, ${safeJsonLiteral(spec.query)});`
|
|
1165
|
+
: ` const url = resolveUrl(baseTarget, ${safeJsonLiteral(spec.path)});`);
|
|
1166
|
+
lines.push(` const headers = applyAuthHeaders(${safeJsonLiteral(spec.headers)});`);
|
|
1167
|
+
if (sendBody) {
|
|
1168
|
+
lines.push(` const data = ${safeJsonLiteral(spec.body)};`);
|
|
1169
|
+
lines.push(' if (typeof data !== "string" && !Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {');
|
|
1170
|
+
lines.push(' headers["content-type"] = "application/json";');
|
|
1171
|
+
lines.push(" }");
|
|
1172
|
+
}
|
|
1173
|
+
lines.push(" const startedAt = Date.now();");
|
|
1174
|
+
lines.push(" const response = await request.fetch(url, {");
|
|
1175
|
+
lines.push(` method: ${safeJsonLiteral(spec.method)},`);
|
|
1176
|
+
lines.push(" headers,");
|
|
1177
|
+
if (sendBody) {
|
|
1178
|
+
lines.push(" data,");
|
|
1179
|
+
}
|
|
1180
|
+
lines.push(` timeout: ${safeJsonLiteral(spec.timeoutMs)}`);
|
|
1181
|
+
lines.push(" });");
|
|
1182
|
+
lines.push(" const durationMs = Date.now() - startedAt;");
|
|
1183
|
+
lines.push(" const bodyText = await response.text();");
|
|
1184
|
+
if (spec.status !== undefined) {
|
|
1185
|
+
if (Array.isArray(spec.status)) {
|
|
1186
|
+
lines.push(` expect(${safeJsonLiteral(spec.status)}).toContain(response.status());`);
|
|
1187
|
+
}
|
|
1188
|
+
else {
|
|
1189
|
+
lines.push(` expect(response.status()).toBe(${safeJsonLiteral(spec.status)});`);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (spec.maxLatencyMs !== undefined) {
|
|
1193
|
+
lines.push(` expect(durationMs).toBeLessThanOrEqual(${safeJsonLiteral(spec.maxLatencyMs)});`);
|
|
1194
|
+
}
|
|
1195
|
+
if (Object.keys(spec.expectedHeaders).length > 0) {
|
|
1196
|
+
lines.push(" const responseHeaders = response.headers();");
|
|
1197
|
+
for (const [hdrKey, hdrVal] of Object.entries(spec.expectedHeaders)) {
|
|
1198
|
+
lines.push(" {");
|
|
1199
|
+
lines.push(` const actualHeader = Object.entries(responseHeaders).find(([k]) => k.toLowerCase() === ${safeJsonLiteral(hdrKey.toLowerCase())})?.[1];`);
|
|
1200
|
+
lines.push(" expect(actualHeader).toBeDefined();");
|
|
1201
|
+
lines.push(` expect((actualHeader ?? "").toLowerCase()).toContain(${safeJsonLiteral(hdrVal.toLowerCase())});`);
|
|
1202
|
+
lines.push(" }");
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
if (spec.bodyExact !== undefined) {
|
|
1206
|
+
lines.push(` expect(bodyText).toBe(${safeJsonLiteral(spec.bodyExact)});`);
|
|
1207
|
+
}
|
|
1208
|
+
for (const needle of spec.bodyContains) {
|
|
1209
|
+
lines.push(` expect(bodyText).toContain(${safeJsonLiteral(needle)});`);
|
|
1210
|
+
}
|
|
1211
|
+
const needsJson = spec.jsonSchema !== undefined || spec.jsonSubset !== undefined || spec.jsonPaths.length > 0;
|
|
1212
|
+
if (needsJson) {
|
|
1213
|
+
lines.push(" const parsedJson: unknown = JSON.parse(bodyText);");
|
|
1214
|
+
if (spec.jsonSchema !== undefined) {
|
|
1215
|
+
lines.push(` expect(validateSchema(${safeJsonLiteral(spec.jsonSchema)}, parsedJson)).toEqual([]);`);
|
|
1216
|
+
}
|
|
1217
|
+
if (spec.jsonSubset !== undefined) {
|
|
1218
|
+
lines.push(` expect(matchesJsonSubset(parsedJson, ${safeJsonLiteral(spec.jsonSubset)})).toBe(true);`);
|
|
1219
|
+
}
|
|
1220
|
+
for (const jp of spec.jsonPaths) {
|
|
1221
|
+
lines.push(" {");
|
|
1222
|
+
lines.push(` const q = queryJsonPath(parsedJson, ${safeJsonLiteral(jp.path)});`);
|
|
1223
|
+
lines.push(" expect(q.found).toBe(true);");
|
|
1224
|
+
if (Object.prototype.hasOwnProperty.call(jp, "equals")) {
|
|
1225
|
+
lines.push(` expect(q.value).toEqual(${safeJsonLiteral(jp.equals)});`);
|
|
1226
|
+
}
|
|
1227
|
+
else if (typeof jp.matches === "string") {
|
|
1228
|
+
lines.push(` expect(String(q.value)).toMatch(new RegExp(${safeJsonLiteral(jp.matches)}));`);
|
|
1229
|
+
}
|
|
1230
|
+
lines.push(" }");
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
lines.push(" });");
|
|
1234
|
+
lines.push("");
|
|
1235
|
+
}
|
|
1236
|
+
export function exportPlaywrightTests(contract, options = {}) {
|
|
1237
|
+
validateContractInput(contract);
|
|
1238
|
+
const includeSkippedComments = options.includeSkippedComments !== false;
|
|
1239
|
+
let excludedHoldoutCount = 0;
|
|
1240
|
+
const skippedIds = [];
|
|
1241
|
+
const specs = [];
|
|
1242
|
+
for (const inv of contract.invariants) {
|
|
1243
|
+
if (inv.holdout === true) {
|
|
1244
|
+
excludedHoldoutCount += 1;
|
|
1245
|
+
continue;
|
|
1246
|
+
}
|
|
1247
|
+
const prepared = prepareInvariant(contract, inv, options.target);
|
|
1248
|
+
if (!prepared) {
|
|
1249
|
+
skippedIds.push(inv.id);
|
|
1250
|
+
continue;
|
|
1251
|
+
}
|
|
1252
|
+
specs.push(prepared);
|
|
1253
|
+
}
|
|
1254
|
+
const defaultTarget = resolveDefaultTargetForContract(contract, options.target);
|
|
1255
|
+
const suiteName = sanitizeComment(contract.target?.name || "vibecode-contract");
|
|
1256
|
+
const lines = [];
|
|
1257
|
+
lines.push(`// Standalone Playwright test suite generated from contract "${suiteName}".`);
|
|
1258
|
+
lines.push("// Zero runtime dependency on vibecode-anything.");
|
|
1259
|
+
if (typeof options.contractPath === "string" &&
|
|
1260
|
+
options.contractPath.trim() &&
|
|
1261
|
+
!/\.vibecode-vault/i.test(options.contractPath)) {
|
|
1262
|
+
lines.push(`// Source contract: ${sanitizeComment(options.contractPath)}`);
|
|
1263
|
+
}
|
|
1264
|
+
if (excludedHoldoutCount > 0) {
|
|
1265
|
+
lines.push(`// Excluded ${excludedHoldoutCount} holdout invariant(s) (never exported to standalone tests).`);
|
|
1266
|
+
}
|
|
1267
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
1268
|
+
const safeSkipped = skippedIds.map((id) => sanitizeComment(id, 64)).join(", ");
|
|
1269
|
+
lines.push(`// Skipped ${skippedIds.length} unsupported invariant(s): ${safeSkipped}`);
|
|
1270
|
+
lines.push('// Run "vibecode-anything verify" for non-Playwright invariants (CLI, visual, video, repo).');
|
|
1271
|
+
}
|
|
1272
|
+
lines.push("// Runtime env hooks: VIBECODE_TARGET (override base URL), VIBECODE_AUTH_HEADER (\"Key: Value\"), VIBECODE_STORAGE_STATE (Playwright storageState path).");
|
|
1273
|
+
lines.push("");
|
|
1274
|
+
lines.push('import { test, expect } from "@playwright/test";');
|
|
1275
|
+
lines.push("");
|
|
1276
|
+
lines.push(`const DEFAULT_TARGET = ${safeJsonLiteral(defaultTarget)};`);
|
|
1277
|
+
lines.push("const BASE_TARGET = (process.env.VIBECODE_TARGET || DEFAULT_TARGET).trim();");
|
|
1278
|
+
lines.push("");
|
|
1279
|
+
lines.push("if (process.env.VIBECODE_STORAGE_STATE) {");
|
|
1280
|
+
lines.push(" test.use({ storageState: process.env.VIBECODE_STORAGE_STATE });");
|
|
1281
|
+
lines.push("}");
|
|
1282
|
+
lines.push("");
|
|
1283
|
+
emitPlaywrightHelpers(lines, specs);
|
|
1284
|
+
const suiteTitle = sanitizeFreeText(contract.target?.name || "vibecode-contract");
|
|
1285
|
+
lines.push(`test.describe(${safeJsonLiteral(suiteTitle)}, () => {`);
|
|
1286
|
+
for (const spec of specs) {
|
|
1287
|
+
if (spec.type === "web_route") {
|
|
1288
|
+
emitWebRouteTest(lines, spec);
|
|
1289
|
+
}
|
|
1290
|
+
else if (spec.type === "web_flow") {
|
|
1291
|
+
emitWebFlowTest(lines, spec);
|
|
1292
|
+
}
|
|
1293
|
+
else if (spec.type === "web_network") {
|
|
1294
|
+
emitWebNetworkTest(lines, spec);
|
|
1295
|
+
}
|
|
1296
|
+
else {
|
|
1297
|
+
emitHttpTest(lines, spec);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
lines.push("});");
|
|
1301
|
+
lines.push("");
|
|
1302
|
+
return {
|
|
1303
|
+
format: "playwright",
|
|
1304
|
+
suggestedFilename: SUGGESTED_FILENAME,
|
|
1305
|
+
code: lines.join("\n"),
|
|
1306
|
+
exportedCount: specs.length,
|
|
1307
|
+
skippedCount: skippedIds.length,
|
|
1308
|
+
skippedIds,
|
|
1309
|
+
excludedHoldoutCount
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
export function writePlaywrightTests(contract, options) {
|
|
1313
|
+
if (!isRecord(options) ||
|
|
1314
|
+
typeof options.outPath !== "string" ||
|
|
1315
|
+
!options.outPath.trim() ||
|
|
1316
|
+
options.outPath.includes("\0")) {
|
|
1317
|
+
throw new VibecodeError("CONTRACT_INVALID", "writePlaywrightTests requires a valid non-empty outPath.");
|
|
1318
|
+
}
|
|
1319
|
+
const result = exportPlaywrightTests(contract, options);
|
|
1320
|
+
const resolvedOut = path.resolve(options.outPath.trim());
|
|
1321
|
+
const parentDir = path.dirname(resolvedOut);
|
|
1322
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
1323
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
1324
|
+
try {
|
|
1325
|
+
fs.writeFileSync(tmpPath, result.code, "utf8");
|
|
1326
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
1327
|
+
}
|
|
1328
|
+
catch (err) {
|
|
1329
|
+
try {
|
|
1330
|
+
if (fs.existsSync(tmpPath)) {
|
|
1331
|
+
fs.rmSync(tmpPath, { force: true });
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
catch {
|
|
1335
|
+
// ignore cleanup error
|
|
1336
|
+
}
|
|
1337
|
+
throw err;
|
|
1338
|
+
}
|
|
1339
|
+
return {
|
|
1340
|
+
...result,
|
|
1341
|
+
outPath: resolvedOut
|
|
1342
|
+
};
|
|
1343
|
+
}
|