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,1813 @@
|
|
|
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 { serializeYaml } from "./openapi-export.js";
|
|
6
|
+
import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
|
|
7
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:8080";
|
|
8
|
+
const DEFAULT_TITLE = "vibecode-load-suite";
|
|
9
|
+
const DEFAULT_VUS = 10;
|
|
10
|
+
const DEFAULT_DURATION_SEC = 30;
|
|
11
|
+
const DEFAULT_NODE_BENCH_ITERATIONS = 20;
|
|
12
|
+
const MAX_VUS = 10000;
|
|
13
|
+
const MAX_DURATION_SEC = 86400;
|
|
14
|
+
const MAX_ITERATIONS = 1000000;
|
|
15
|
+
const MAX_JSON_DEPTH = 24;
|
|
16
|
+
const MAX_SCHEMA_DEPTH = 12;
|
|
17
|
+
const MAX_SCHEMA_KEYS = 100;
|
|
18
|
+
const MAX_ARRAY_ITEMS = 128;
|
|
19
|
+
const MAX_REGEX_LENGTH = 256;
|
|
20
|
+
const MAX_PRETTY_WARNINGS = 10;
|
|
21
|
+
const MAX_PRETTY_SKIPPED = 12;
|
|
22
|
+
const STRICT_DEFAULT_P95_MS = 250;
|
|
23
|
+
const STRICT_DEFAULT_P99_MS = 500;
|
|
24
|
+
const RELAXED_DEFAULT_P95_MS = 1000;
|
|
25
|
+
const RELAXED_DEFAULT_P99_MS = 2000;
|
|
26
|
+
const VALID_FORMATS = new Set(["k6", "artillery", "node-bench"]);
|
|
27
|
+
const SUPPORTED_HTTP_METHODS = new Set([
|
|
28
|
+
"GET",
|
|
29
|
+
"POST",
|
|
30
|
+
"PUT",
|
|
31
|
+
"PATCH",
|
|
32
|
+
"DELETE",
|
|
33
|
+
"HEAD",
|
|
34
|
+
"OPTIONS"
|
|
35
|
+
]);
|
|
36
|
+
const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
37
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
38
|
+
const TRANSPORT_SKIP_HEADERS = new Set([
|
|
39
|
+
"content-length",
|
|
40
|
+
"transfer-encoding",
|
|
41
|
+
"connection",
|
|
42
|
+
"host"
|
|
43
|
+
]);
|
|
44
|
+
const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
45
|
+
const HEADER_CONTROL_CHAR_RE = /[\r\n\0\x00-\x08\x0b-\x1f\x7f\u2028\u2029]/;
|
|
46
|
+
const CONTROL_CHAR_STRIP_RE = /[\r\n\u2028\u2029\x00-\x1f\x7f]+/g;
|
|
47
|
+
const SENSITIVE_HEADER_NAME_RE = /(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|api[-_]?key|apikey|token|secret|bearer|csrf|xsrf|password|passwd|passphrase|credential|private[-_]?key|session[-_]?id|jwt|(?:^|[-_])auth(?:$|[-_]))/i;
|
|
48
|
+
const SENSITIVE_QUERY_NAME_RE = /(?:token|api[-_]?key|apikey|secret|password|passwd|passphrase|jwt|session[-_]?id|private[-_]?key|authorization|cookie|csrf|xsrf|bearer|credential|(?:^|[-_])(?:auth|sig|signature)(?:$|[-_]))/i;
|
|
49
|
+
const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf)/i;
|
|
50
|
+
const AUTH_SCHEME_VALUE_RE = /(?:^|\s)(?:bearer|basic|token|apikey)\s+\S+|(?:^|\s)digest\s+(?:[a-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")|[a-z0-9._~+/:-]{6,})/i;
|
|
51
|
+
const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
52
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
|
|
53
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
|
|
54
|
+
const INLINE_BEARER_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
|
|
55
|
+
const INLINE_BASIC_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
|
|
56
|
+
const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+[A-Za-z0-9._~+/=:-]{4,}/gi;
|
|
57
|
+
const INLINE_DIGEST_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|[A-Za-z0-9._~+/:-]{6,}={0,2})/gi;
|
|
58
|
+
const INLINE_COOKIE_RE = /\b(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;|]+(?:\s*;\s*[A-Za-z0-9_.-]+=[^\s,\r\n;|]+)*/gi;
|
|
59
|
+
const INLINE_SENSITIVE_HEADER_RE = /\b(Authorization|Proxy-Authorization|X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token)\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest)\s+(?:\[REDACTED\]|[^\s,;|]+)|[A-Za-z0-9._-]+\s+[^\s,;|]+|[^\s,;|]+)/gi;
|
|
60
|
+
const INLINE_KV_SECRET_RE = /\b([A-Za-z0-9_.-]*(?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|id[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key|session[_-]?id|password|passwd|passphrase|secret|token|jwt|credentials?|authorization|cookie|csrf[_-]?token|xsrf[_-]?token)[A-Za-z0-9_.-]*)(["']?)\s*([:=])\s*(?:"([^"]*)"|'([^']*)'|([^\s,;&"'`<>]+))/gi;
|
|
61
|
+
const ANSI = {
|
|
62
|
+
reset: "\x1b[0m",
|
|
63
|
+
bold: "\x1b[1m",
|
|
64
|
+
dim: "\x1b[2m",
|
|
65
|
+
red: "\x1b[31m",
|
|
66
|
+
green: "\x1b[32m",
|
|
67
|
+
yellow: "\x1b[33m",
|
|
68
|
+
cyan: "\x1b[36m"
|
|
69
|
+
};
|
|
70
|
+
function isRecord(value) {
|
|
71
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
72
|
+
}
|
|
73
|
+
function isForbiddenKey(key) {
|
|
74
|
+
return FORBIDDEN_KEYS.has(key);
|
|
75
|
+
}
|
|
76
|
+
function stripControlAndTrim(raw) {
|
|
77
|
+
return String(raw).replace(CONTROL_CHAR_STRIP_RE, "").trim();
|
|
78
|
+
}
|
|
79
|
+
function isSensitiveHeaderName(name) {
|
|
80
|
+
const normalized = stripControlAndTrim(name);
|
|
81
|
+
if (!normalized)
|
|
82
|
+
return false;
|
|
83
|
+
return isSensitiveHeader(normalized) || SENSITIVE_HEADER_NAME_RE.test(normalized);
|
|
84
|
+
}
|
|
85
|
+
function isSensitiveQueryName(name) {
|
|
86
|
+
const normalized = stripControlAndTrim(name);
|
|
87
|
+
if (!normalized)
|
|
88
|
+
return false;
|
|
89
|
+
return (isSensitiveQueryParam(normalized) ||
|
|
90
|
+
SENSITIVE_QUERY_NAME_RE.test(normalized) ||
|
|
91
|
+
isSensitiveHeaderName(normalized));
|
|
92
|
+
}
|
|
93
|
+
function isSecretFieldName(name) {
|
|
94
|
+
const normalized = stripControlAndTrim(name);
|
|
95
|
+
if (!normalized)
|
|
96
|
+
return false;
|
|
97
|
+
return (SECRET_FIELD_NAME_RE.test(normalized) ||
|
|
98
|
+
isSensitiveHeaderName(normalized) ||
|
|
99
|
+
isSensitiveQueryName(normalized));
|
|
100
|
+
}
|
|
101
|
+
function hasAuthSchemeValue(value) {
|
|
102
|
+
return AUTH_SCHEME_VALUE_RE.test(value);
|
|
103
|
+
}
|
|
104
|
+
function redactVaultPaths(text) {
|
|
105
|
+
return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT]");
|
|
106
|
+
}
|
|
107
|
+
function scrubInlineKvSecrets(text) {
|
|
108
|
+
return text.replace(INLINE_KV_SECRET_RE, (full, key, q, sep, dq, sq, bare) => {
|
|
109
|
+
const val = dq ?? sq ?? bare ?? "";
|
|
110
|
+
if (val === "[REDACTED]" || val === "[REDACTED_VAULT]")
|
|
111
|
+
return full;
|
|
112
|
+
return q ? `${key}${q}${sep}"[REDACTED]"` : `${key}${sep}[REDACTED]`;
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function sanitizeUrlInText(rawUrl) {
|
|
116
|
+
const withoutVault = redactVaultPaths(rawUrl);
|
|
117
|
+
const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
|
|
118
|
+
const filterParams = (entries) => {
|
|
119
|
+
const safeParams = new URLSearchParams();
|
|
120
|
+
for (const [k, v] of entries) {
|
|
121
|
+
const cleanK = stripControlAndTrim(k);
|
|
122
|
+
if (!cleanK || isForbiddenKey(cleanK) || isSensitiveQueryName(cleanK))
|
|
123
|
+
continue;
|
|
124
|
+
if (hasAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
|
|
125
|
+
continue;
|
|
126
|
+
const scrubbed = scrubInlineKvSecrets(redactVaultPaths(v));
|
|
127
|
+
if (/\[REDACTED/i.test(scrubbed))
|
|
128
|
+
continue;
|
|
129
|
+
safeParams.append(cleanK, scrubbed);
|
|
130
|
+
}
|
|
131
|
+
return safeParams.toString();
|
|
132
|
+
};
|
|
133
|
+
try {
|
|
134
|
+
const parsed = new URL(withoutAuth);
|
|
135
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
136
|
+
return "[REDACTED_URL]";
|
|
137
|
+
}
|
|
138
|
+
parsed.username = "";
|
|
139
|
+
parsed.password = "";
|
|
140
|
+
const serialized = filterParams(parsed.searchParams.entries());
|
|
141
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
142
|
+
parsed.hash = "";
|
|
143
|
+
return parsed.toString();
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
const cleanFallback = withoutAuth.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/?#@]*@+/, "$1");
|
|
147
|
+
const hashIdx = cleanFallback.indexOf("#");
|
|
148
|
+
const noHash = hashIdx >= 0 ? cleanFallback.slice(0, hashIdx) : cleanFallback;
|
|
149
|
+
const qIdx = noHash.indexOf("?");
|
|
150
|
+
if (qIdx < 0)
|
|
151
|
+
return noHash;
|
|
152
|
+
const basePart = noHash.slice(0, qIdx);
|
|
153
|
+
const serialized = filterParams(new URLSearchParams(noHash.slice(qIdx + 1)).entries());
|
|
154
|
+
return serialized ? `${basePart}?${serialized}` : basePart;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function sanitizeText(raw) {
|
|
158
|
+
const noDangerous = raw.replace(/[\0\u2028\u2029]/g, "");
|
|
159
|
+
const noVault = redactVaultPaths(noDangerous);
|
|
160
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
|
|
161
|
+
const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
|
|
162
|
+
const noBearer = noBasicAuth.replace(INLINE_BEARER_RE, "$1 [REDACTED]");
|
|
163
|
+
const noBasic = noBearer.replace(INLINE_BASIC_RE, "$1 [REDACTED]");
|
|
164
|
+
const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
|
|
165
|
+
const noDigest = noScheme.replace(INLINE_DIGEST_RE, "$1 [REDACTED]");
|
|
166
|
+
const noCookie = noDigest.replace(INLINE_COOKIE_RE, "$1: [REDACTED]");
|
|
167
|
+
const noSensHdr = noCookie.replace(INLINE_SENSITIVE_HEADER_RE, "$1: [REDACTED]");
|
|
168
|
+
return scrubInlineKvSecrets(noSensHdr);
|
|
169
|
+
}
|
|
170
|
+
function sanitizeSingleLine(raw) {
|
|
171
|
+
return sanitizeText(raw)
|
|
172
|
+
.replace(CONTROL_CHAR_STRIP_RE, " ")
|
|
173
|
+
.replace(/\s+/g, " ")
|
|
174
|
+
.trim();
|
|
175
|
+
}
|
|
176
|
+
function sanitizeCommentLine(raw) {
|
|
177
|
+
return sanitizeSingleLine(raw)
|
|
178
|
+
.replace(/\*\//g, "* /")
|
|
179
|
+
.replace(/\/\*/g, "/ *");
|
|
180
|
+
}
|
|
181
|
+
function safeJsLiteral(value) {
|
|
182
|
+
const json = JSON.stringify(value);
|
|
183
|
+
if (json === undefined)
|
|
184
|
+
return "null";
|
|
185
|
+
return json
|
|
186
|
+
.replace(/\u2028/g, "\\u2028")
|
|
187
|
+
.replace(/\u2029/g, "\\u2029")
|
|
188
|
+
.replace(/</g, "\\u003c")
|
|
189
|
+
.replace(/\*\//g, "*\\/");
|
|
190
|
+
}
|
|
191
|
+
function sanitizeBaseUrl(raw) {
|
|
192
|
+
if (HEADER_CONTROL_CHAR_RE.test(raw))
|
|
193
|
+
return null;
|
|
194
|
+
const trimmed = raw.trim();
|
|
195
|
+
if (!trimmed || /\.vibecode-vault/i.test(trimmed))
|
|
196
|
+
return null;
|
|
197
|
+
const withoutAuth = redactVaultPaths(trimmed).replace(URL_BASIC_AUTH_RE, "$1");
|
|
198
|
+
try {
|
|
199
|
+
const parsed = new URL(withoutAuth);
|
|
200
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
201
|
+
return null;
|
|
202
|
+
parsed.username = "";
|
|
203
|
+
parsed.password = "";
|
|
204
|
+
parsed.search = "";
|
|
205
|
+
parsed.hash = "";
|
|
206
|
+
const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
|
|
207
|
+
return `${parsed.origin}${cleanPath}`;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function resolveBaseUrl(contract, options, warnings) {
|
|
214
|
+
if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
|
|
215
|
+
const sanitized = sanitizeBaseUrl(options.baseUrl);
|
|
216
|
+
if (sanitized)
|
|
217
|
+
return sanitized;
|
|
218
|
+
warnings.push(`Rejected unsafe or invalid baseUrl option; falling back to ${DEFAULT_BASE_URL}.`);
|
|
219
|
+
return DEFAULT_BASE_URL;
|
|
220
|
+
}
|
|
221
|
+
if (isRecord(contract.target) &&
|
|
222
|
+
Array.isArray(contract.target.sources) &&
|
|
223
|
+
contract.target.sources.length > 0) {
|
|
224
|
+
const firstSource = contract.target.sources[0];
|
|
225
|
+
if (isRecord(firstSource)) {
|
|
226
|
+
if (typeof firstSource.ref === "string" && /^https?:\/\//i.test(firstSource.ref.trim())) {
|
|
227
|
+
const sanitized = sanitizeBaseUrl(firstSource.ref);
|
|
228
|
+
if (sanitized)
|
|
229
|
+
return sanitized;
|
|
230
|
+
}
|
|
231
|
+
if (isRecord(firstSource.meta) &&
|
|
232
|
+
typeof firstSource.meta.baseUrl === "string" &&
|
|
233
|
+
/^https?:\/\//i.test(firstSource.meta.baseUrl.trim())) {
|
|
234
|
+
const sanitized = sanitizeBaseUrl(firstSource.meta.baseUrl);
|
|
235
|
+
if (sanitized)
|
|
236
|
+
return sanitized;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return DEFAULT_BASE_URL;
|
|
241
|
+
}
|
|
242
|
+
function sanitizePathname(rawPathname) {
|
|
243
|
+
const noControl = sanitizeText(rawPathname)
|
|
244
|
+
.replace(CONTROL_CHAR_STRIP_RE, "")
|
|
245
|
+
.trim();
|
|
246
|
+
if (!noControl)
|
|
247
|
+
return "/";
|
|
248
|
+
const encodedSpaces = noControl.replace(/\s+/g, "%20");
|
|
249
|
+
const stack = [];
|
|
250
|
+
for (const seg of encodedSpaces.split("/")) {
|
|
251
|
+
if (!seg || seg === ".")
|
|
252
|
+
continue;
|
|
253
|
+
if (seg === "..") {
|
|
254
|
+
if (stack.length > 0)
|
|
255
|
+
stack.pop();
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
stack.push(seg);
|
|
259
|
+
}
|
|
260
|
+
return stack.length === 0 ? "/" : `/${stack.join("/")}`;
|
|
261
|
+
}
|
|
262
|
+
function splitRelativePathAndQuery(raw) {
|
|
263
|
+
const hashIdx = raw.indexOf("#");
|
|
264
|
+
const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
|
|
265
|
+
const qIdx = withoutHash.indexOf("?");
|
|
266
|
+
const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
|
|
267
|
+
const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
|
|
268
|
+
const inlineQuery = [];
|
|
269
|
+
if (rawQueryPart) {
|
|
270
|
+
const params = new URLSearchParams(rawQueryPart);
|
|
271
|
+
for (const [k, v] of params.entries()) {
|
|
272
|
+
inlineQuery.push([k, v]);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
pathname: sanitizePathname(rawPathPart),
|
|
277
|
+
inlineQuery
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function parsePathAndInlineQuery(rawPath, warnings, invId) {
|
|
281
|
+
if (typeof rawPath !== "string") {
|
|
282
|
+
return { pathname: "/", inlineQuery: [] };
|
|
283
|
+
}
|
|
284
|
+
const cleaned = rawPath.replace(CONTROL_CHAR_STRIP_RE, "").trim();
|
|
285
|
+
if (!cleaned) {
|
|
286
|
+
return { pathname: "/", inlineQuery: [] };
|
|
287
|
+
}
|
|
288
|
+
const schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleaned);
|
|
289
|
+
if (schemeMatch) {
|
|
290
|
+
const scheme = schemeMatch[1].toLowerCase();
|
|
291
|
+
if (scheme !== "http" && scheme !== "https") {
|
|
292
|
+
warnings.push(`Rejected non-HTTP URL scheme in invariant ${invId}; defaulted path to "/".`);
|
|
293
|
+
return { pathname: "/", inlineQuery: [] };
|
|
294
|
+
}
|
|
295
|
+
const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
|
|
296
|
+
try {
|
|
297
|
+
const parsed = new URL(withoutAuth);
|
|
298
|
+
const inlineQuery = [];
|
|
299
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
300
|
+
inlineQuery.push([k, v]);
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
pathname: sanitizePathname(parsed.pathname || "/"),
|
|
304
|
+
inlineQuery
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
|
|
309
|
+
return splitRelativePathAndQuery(stripped);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return splitRelativePathAndQuery(cleaned);
|
|
313
|
+
}
|
|
314
|
+
function sanitizeQueryEntries(inlineQuery, structuredQuery) {
|
|
315
|
+
const merged = new Map();
|
|
316
|
+
const consider = (rawKey, rawVal) => {
|
|
317
|
+
const cleanKey = stripControlAndTrim(rawKey);
|
|
318
|
+
if (!cleanKey || isForbiddenKey(cleanKey))
|
|
319
|
+
return;
|
|
320
|
+
if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
|
|
321
|
+
return;
|
|
322
|
+
if (HEADER_CONTROL_CHAR_RE.test(rawVal))
|
|
323
|
+
return;
|
|
324
|
+
const trimmedVal = rawVal.trim();
|
|
325
|
+
if (hasAuthSchemeValue(trimmedVal) || /\.vibecode-vault/i.test(trimmedVal))
|
|
326
|
+
return;
|
|
327
|
+
const cleanVal = sanitizeText(trimmedVal).replace(CONTROL_CHAR_STRIP_RE, "");
|
|
328
|
+
merged.set(cleanKey, cleanVal);
|
|
329
|
+
};
|
|
330
|
+
for (const [k, v] of inlineQuery) {
|
|
331
|
+
consider(k, v);
|
|
332
|
+
}
|
|
333
|
+
if (isRecord(structuredQuery)) {
|
|
334
|
+
for (const key of Object.keys(structuredQuery)) {
|
|
335
|
+
if (isForbiddenKey(key))
|
|
336
|
+
continue;
|
|
337
|
+
const val = structuredQuery[key];
|
|
338
|
+
if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
|
|
339
|
+
if (typeof val === "number" && !Number.isFinite(val))
|
|
340
|
+
continue;
|
|
341
|
+
consider(key, String(val));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return [...merged.entries()];
|
|
346
|
+
}
|
|
347
|
+
function sanitizeHeaders(rawHeaders, isRequest, warnings, invId) {
|
|
348
|
+
if (!isRecord(rawHeaders))
|
|
349
|
+
return [];
|
|
350
|
+
const byLower = new Map();
|
|
351
|
+
for (const rawKey of Object.keys(rawHeaders)) {
|
|
352
|
+
if (isForbiddenKey(rawKey))
|
|
353
|
+
continue;
|
|
354
|
+
const rawVal = rawHeaders[rawKey];
|
|
355
|
+
if (rawVal === undefined || rawVal === null)
|
|
356
|
+
continue;
|
|
357
|
+
const rawValStr = String(rawVal);
|
|
358
|
+
// Reject CRLF, NUL, line-separators, and control characters in header names or values.
|
|
359
|
+
if (HEADER_CONTROL_CHAR_RE.test(rawKey) || HEADER_CONTROL_CHAR_RE.test(rawValStr)) {
|
|
360
|
+
warnings.push(`Dropped unsafe header with control characters in invariant ${invId}.`);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const trimmedKey = rawKey.trim();
|
|
364
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || !HEADER_NAME_TOKEN_RE.test(trimmedKey)) {
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
// Post-trim forbidden header stripping.
|
|
368
|
+
if (isSensitiveHeaderName(trimmedKey))
|
|
369
|
+
continue;
|
|
370
|
+
const lowerKey = trimmedKey.toLowerCase();
|
|
371
|
+
if (isRequest && TRANSPORT_SKIP_HEADERS.has(lowerKey))
|
|
372
|
+
continue;
|
|
373
|
+
const trimmedVal = rawValStr.trim();
|
|
374
|
+
if (!trimmedVal)
|
|
375
|
+
continue;
|
|
376
|
+
if (hasAuthSchemeValue(trimmedVal) || /\.vibecode-vault/i.test(trimmedVal))
|
|
377
|
+
continue;
|
|
378
|
+
const cleanVal = sanitizeSingleLine(trimmedVal);
|
|
379
|
+
if (!cleanVal || cleanVal.includes("[REDACTED]"))
|
|
380
|
+
continue;
|
|
381
|
+
byLower.set(lowerKey, [trimmedKey, cleanVal]);
|
|
382
|
+
}
|
|
383
|
+
return [...byLower.values()];
|
|
384
|
+
}
|
|
385
|
+
function sanitizeJsonValue(value, depth, seen, diag) {
|
|
386
|
+
if (value === null || value === undefined)
|
|
387
|
+
return value;
|
|
388
|
+
if (typeof value === "boolean")
|
|
389
|
+
return value;
|
|
390
|
+
if (typeof value === "number")
|
|
391
|
+
return Number.isFinite(value) ? value : null;
|
|
392
|
+
if (typeof value === "string") {
|
|
393
|
+
const trimmed = value.trim();
|
|
394
|
+
if (depth < MAX_JSON_DEPTH &&
|
|
395
|
+
((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
396
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]")))) {
|
|
397
|
+
try {
|
|
398
|
+
const parsed = JSON.parse(trimmed);
|
|
399
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
400
|
+
return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen, diag));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
// Not JSON; fall through to text sanitization.
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return sanitizeText(value);
|
|
408
|
+
}
|
|
409
|
+
if (depth >= MAX_JSON_DEPTH) {
|
|
410
|
+
diag.hadDepthLimit = true;
|
|
411
|
+
return "[TRUNCATED]";
|
|
412
|
+
}
|
|
413
|
+
if (typeof value !== "object")
|
|
414
|
+
return undefined;
|
|
415
|
+
if (seen.has(value)) {
|
|
416
|
+
diag.hadCircular = true;
|
|
417
|
+
return "[CIRCULAR]";
|
|
418
|
+
}
|
|
419
|
+
seen.add(value);
|
|
420
|
+
try {
|
|
421
|
+
if (Array.isArray(value)) {
|
|
422
|
+
return value
|
|
423
|
+
.slice(0, MAX_ARRAY_ITEMS)
|
|
424
|
+
.map((item) => sanitizeJsonValue(item, depth + 1, seen, diag));
|
|
425
|
+
}
|
|
426
|
+
const out = {};
|
|
427
|
+
let keyCount = 0;
|
|
428
|
+
for (const key of Object.keys(value)) {
|
|
429
|
+
if (keyCount >= MAX_SCHEMA_KEYS)
|
|
430
|
+
break;
|
|
431
|
+
if (isForbiddenKey(key))
|
|
432
|
+
continue;
|
|
433
|
+
const cleanKey = sanitizeSingleLine(key);
|
|
434
|
+
if (!cleanKey || isForbiddenKey(cleanKey))
|
|
435
|
+
continue;
|
|
436
|
+
const rawVal = value[key];
|
|
437
|
+
if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
keyCount += 1;
|
|
441
|
+
if (isSecretFieldName(cleanKey)) {
|
|
442
|
+
out[cleanKey] = "[REDACTED]";
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
out[cleanKey] = sanitizeJsonValue(rawVal, depth + 1, seen, diag);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
finally {
|
|
451
|
+
seen.delete(value);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
function sanitizeRequestBody(rawBody, diag) {
|
|
455
|
+
if (rawBody === undefined || rawBody === null)
|
|
456
|
+
return undefined;
|
|
457
|
+
if (typeof rawBody === "string") {
|
|
458
|
+
if (rawBody.length === 0)
|
|
459
|
+
return undefined;
|
|
460
|
+
const trimmed = rawBody.trim();
|
|
461
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
462
|
+
try {
|
|
463
|
+
const parsed = JSON.parse(trimmed);
|
|
464
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
465
|
+
const sanitized = sanitizeJsonValue(parsed, 0, new Set(), diag);
|
|
466
|
+
return {
|
|
467
|
+
isJson: true,
|
|
468
|
+
text: JSON.stringify(sanitized),
|
|
469
|
+
parsedJson: sanitized
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
catch {
|
|
474
|
+
// Fall through to plain text sanitization.
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const cleanText = sanitizeText(rawBody);
|
|
478
|
+
if (!cleanText)
|
|
479
|
+
return undefined;
|
|
480
|
+
return {
|
|
481
|
+
isJson: false,
|
|
482
|
+
text: cleanText
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
if (typeof rawBody === "object") {
|
|
486
|
+
const sanitized = sanitizeJsonValue(rawBody, 0, new Set(), diag);
|
|
487
|
+
return {
|
|
488
|
+
isJson: true,
|
|
489
|
+
text: JSON.stringify(sanitized),
|
|
490
|
+
parsedJson: sanitized
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
if (typeof rawBody === "boolean" || typeof rawBody === "number") {
|
|
494
|
+
const val = typeof rawBody === "number" && !Number.isFinite(rawBody) ? null : rawBody;
|
|
495
|
+
return {
|
|
496
|
+
isJson: true,
|
|
497
|
+
text: JSON.stringify(val),
|
|
498
|
+
parsedJson: val
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
return undefined;
|
|
502
|
+
}
|
|
503
|
+
function sanitizeSchemaCheck(rawSchema, depth, seen, diag) {
|
|
504
|
+
if (!isRecord(rawSchema))
|
|
505
|
+
return undefined;
|
|
506
|
+
if (depth >= MAX_SCHEMA_DEPTH) {
|
|
507
|
+
diag.hadDepthLimit = true;
|
|
508
|
+
return undefined;
|
|
509
|
+
}
|
|
510
|
+
if (seen.has(rawSchema)) {
|
|
511
|
+
diag.hadCircular = true;
|
|
512
|
+
return undefined;
|
|
513
|
+
}
|
|
514
|
+
seen.add(rawSchema);
|
|
515
|
+
try {
|
|
516
|
+
const schema = rawSchema;
|
|
517
|
+
const out = {};
|
|
518
|
+
const validTypes = new Set(["object", "array", "string", "number", "integer", "boolean", "null"]);
|
|
519
|
+
if (typeof schema.type === "string" && validTypes.has(schema.type)) {
|
|
520
|
+
out.type = schema.type;
|
|
521
|
+
}
|
|
522
|
+
else if (Array.isArray(schema.type)) {
|
|
523
|
+
const filtered = schema.type.filter((t) => typeof t === "string" && validTypes.has(t));
|
|
524
|
+
if (filtered.length > 0)
|
|
525
|
+
out.type = filtered;
|
|
526
|
+
}
|
|
527
|
+
if (isRecord(schema.properties)) {
|
|
528
|
+
const props = {};
|
|
529
|
+
let count = 0;
|
|
530
|
+
for (const key of Object.keys(schema.properties)) {
|
|
531
|
+
if (count >= MAX_SCHEMA_KEYS)
|
|
532
|
+
break;
|
|
533
|
+
if (isForbiddenKey(key) || isSecretFieldName(key))
|
|
534
|
+
continue;
|
|
535
|
+
const cleanKey = sanitizeSingleLine(key);
|
|
536
|
+
if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
|
|
537
|
+
continue;
|
|
538
|
+
const sub = sanitizeSchemaCheck(schema.properties[key], depth + 1, seen, diag);
|
|
539
|
+
if (sub) {
|
|
540
|
+
props[cleanKey] = sub;
|
|
541
|
+
count += 1;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (Object.keys(props).length > 0)
|
|
545
|
+
out.properties = props;
|
|
546
|
+
}
|
|
547
|
+
if (Array.isArray(schema.required)) {
|
|
548
|
+
const reqKeys = [];
|
|
549
|
+
for (const item of schema.required) {
|
|
550
|
+
if (typeof item !== "string")
|
|
551
|
+
continue;
|
|
552
|
+
if (isForbiddenKey(item) || isSecretFieldName(item))
|
|
553
|
+
continue;
|
|
554
|
+
const clean = sanitizeSingleLine(item);
|
|
555
|
+
if (!clean || isForbiddenKey(clean) || isSecretFieldName(clean))
|
|
556
|
+
continue;
|
|
557
|
+
if (out.properties && !Object.prototype.hasOwnProperty.call(out.properties, clean))
|
|
558
|
+
continue;
|
|
559
|
+
if (!reqKeys.includes(clean))
|
|
560
|
+
reqKeys.push(clean);
|
|
561
|
+
}
|
|
562
|
+
if (reqKeys.length > 0)
|
|
563
|
+
out.required = reqKeys;
|
|
564
|
+
}
|
|
565
|
+
if (isRecord(schema.items)) {
|
|
566
|
+
const itemSchema = sanitizeSchemaCheck(schema.items, depth + 1, seen, diag);
|
|
567
|
+
if (itemSchema)
|
|
568
|
+
out.items = itemSchema;
|
|
569
|
+
}
|
|
570
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
571
|
+
out.enum = schema.enum
|
|
572
|
+
.slice(0, MAX_ARRAY_ITEMS)
|
|
573
|
+
.map((v) => sanitizeJsonValue(v, depth + 1, seen, diag));
|
|
574
|
+
}
|
|
575
|
+
if (schema.const !== undefined) {
|
|
576
|
+
out.const = sanitizeJsonValue(schema.const, depth + 1, seen, diag);
|
|
577
|
+
}
|
|
578
|
+
const numericKeys = [
|
|
579
|
+
"minLength",
|
|
580
|
+
"maxLength",
|
|
581
|
+
"minimum",
|
|
582
|
+
"maximum",
|
|
583
|
+
"minItems",
|
|
584
|
+
"maxItems"
|
|
585
|
+
];
|
|
586
|
+
for (const nk of numericKeys) {
|
|
587
|
+
const v = schema[nk];
|
|
588
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
589
|
+
out[nk] = v;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
seen.delete(rawSchema);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function isSafeJsonPathExpr(expr) {
|
|
599
|
+
if (!expr || HEADER_CONTROL_CHAR_RE.test(expr))
|
|
600
|
+
return false;
|
|
601
|
+
const segments = expr.replace(/^\$\.?/, "").split(/[.\[\]]+/);
|
|
602
|
+
for (const seg of segments) {
|
|
603
|
+
const cleaned = seg.replace(/^["']|["']$/g, "");
|
|
604
|
+
if (isForbiddenKey(cleaned))
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
function sanitizeJsonPaths(rawPaths, diag) {
|
|
610
|
+
if (!Array.isArray(rawPaths))
|
|
611
|
+
return [];
|
|
612
|
+
const out = [];
|
|
613
|
+
for (const item of rawPaths) {
|
|
614
|
+
if (!isRecord(item))
|
|
615
|
+
continue;
|
|
616
|
+
const jp = item;
|
|
617
|
+
if (typeof jp.path !== "string")
|
|
618
|
+
continue;
|
|
619
|
+
const cleanPath = sanitizeSingleLine(jp.path);
|
|
620
|
+
if (!cleanPath || !isSafeJsonPathExpr(cleanPath))
|
|
621
|
+
continue;
|
|
622
|
+
const entry = { path: cleanPath };
|
|
623
|
+
const segs = cleanPath
|
|
624
|
+
.replace(/^\$\.?/, "")
|
|
625
|
+
.split(/[.\[\]]+/)
|
|
626
|
+
.map((s) => s.replace(/^["']|["']$/g, ""))
|
|
627
|
+
.filter(Boolean);
|
|
628
|
+
const hasSecretSegment = segs.some((seg) => isSecretFieldName(seg));
|
|
629
|
+
if (jp.equals !== undefined) {
|
|
630
|
+
entry.equals = hasSecretSegment
|
|
631
|
+
? "[REDACTED]"
|
|
632
|
+
: sanitizeJsonValue(jp.equals, 0, new Set(), diag);
|
|
633
|
+
}
|
|
634
|
+
if (!hasSecretSegment &&
|
|
635
|
+
typeof jp.matches === "string" &&
|
|
636
|
+
jp.matches.length > 0 &&
|
|
637
|
+
jp.matches.length <= MAX_REGEX_LENGTH) {
|
|
638
|
+
const cleanMatch = sanitizeSingleLine(jp.matches);
|
|
639
|
+
if (cleanMatch)
|
|
640
|
+
entry.matches = cleanMatch;
|
|
641
|
+
}
|
|
642
|
+
out.push(entry);
|
|
643
|
+
}
|
|
644
|
+
return out;
|
|
645
|
+
}
|
|
646
|
+
function extractExpectedStatuses(rawStatus) {
|
|
647
|
+
const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 100 && n <= 599;
|
|
648
|
+
if (isValid(rawStatus))
|
|
649
|
+
return [rawStatus];
|
|
650
|
+
if (Array.isArray(rawStatus)) {
|
|
651
|
+
const out = [];
|
|
652
|
+
for (const item of rawStatus) {
|
|
653
|
+
if (isValid(item) && !out.includes(item))
|
|
654
|
+
out.push(item);
|
|
655
|
+
}
|
|
656
|
+
return out;
|
|
657
|
+
}
|
|
658
|
+
return [];
|
|
659
|
+
}
|
|
660
|
+
function buildQueryString(query) {
|
|
661
|
+
if (query.length === 0)
|
|
662
|
+
return "";
|
|
663
|
+
const params = new URLSearchParams();
|
|
664
|
+
for (const [k, v] of query) {
|
|
665
|
+
params.append(k, v);
|
|
666
|
+
}
|
|
667
|
+
return params.toString();
|
|
668
|
+
}
|
|
669
|
+
function extractBodyContains(expected, invType) {
|
|
670
|
+
const needles = [];
|
|
671
|
+
const pushClean = (raw) => {
|
|
672
|
+
if (typeof raw !== "string")
|
|
673
|
+
return;
|
|
674
|
+
const clean = sanitizeSingleLine(raw);
|
|
675
|
+
if (clean && !needles.includes(clean)) {
|
|
676
|
+
needles.push(clean);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
if (typeof expected.bodyContains === "string") {
|
|
680
|
+
pushClean(expected.bodyContains);
|
|
681
|
+
}
|
|
682
|
+
else if (Array.isArray(expected.bodyContains)) {
|
|
683
|
+
for (const item of expected.bodyContains) {
|
|
684
|
+
pushClean(item);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
if (invType === "web_route") {
|
|
688
|
+
if (typeof expected.titleContains === "string" && !/[&<>"']/.test(expected.titleContains)) {
|
|
689
|
+
pushClean(expected.titleContains);
|
|
690
|
+
}
|
|
691
|
+
if (Array.isArray(expected.visibleText)) {
|
|
692
|
+
for (const item of expected.visibleText) {
|
|
693
|
+
if (typeof item === "string" && !/[&<>"']/.test(item)) {
|
|
694
|
+
pushClean(item);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return needles;
|
|
700
|
+
}
|
|
701
|
+
function normalizeScenario(inv, invType, fallbackId, warnings) {
|
|
702
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
703
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
704
|
+
const id = sanitizeSingleLine(typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : fallbackId) || fallbackId;
|
|
705
|
+
let method = "GET";
|
|
706
|
+
if (invType === "http") {
|
|
707
|
+
const rawMethod = typeof input.method === "string" && stripControlAndTrim(input.method)
|
|
708
|
+
? stripControlAndTrim(input.method).toUpperCase()
|
|
709
|
+
: "GET";
|
|
710
|
+
if (!SUPPORTED_HTTP_METHODS.has(rawMethod)) {
|
|
711
|
+
return { skipReason: `unsupported HTTP method: ${sanitizeSingleLine(rawMethod)}` };
|
|
712
|
+
}
|
|
713
|
+
method = rawMethod;
|
|
714
|
+
}
|
|
715
|
+
const rawPath = invType === "web_route"
|
|
716
|
+
? (typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined) ??
|
|
717
|
+
(typeof input.path === "string" && input.path.trim() ? input.path : undefined)
|
|
718
|
+
: (typeof input.path === "string" && input.path.trim() ? input.path : undefined) ??
|
|
719
|
+
(typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined);
|
|
720
|
+
const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath, warnings, id);
|
|
721
|
+
const query = sanitizeQueryEntries(inlineQuery, input.query);
|
|
722
|
+
const qs = buildQueryString(query);
|
|
723
|
+
const requestPath = qs ? `${pathname}?${qs}` : pathname;
|
|
724
|
+
const headers = sanitizeHeaders(input.headers, true, warnings, id);
|
|
725
|
+
const expectedHeaders = sanitizeHeaders(expected.headers, false, warnings, id);
|
|
726
|
+
const diag = { hadCircular: false, hadDepthLimit: false };
|
|
727
|
+
let body;
|
|
728
|
+
if (invType === "http" && BODY_HTTP_METHODS.has(method)) {
|
|
729
|
+
body = sanitizeRequestBody(input.body, diag);
|
|
730
|
+
if (body?.isJson && !headers.some(([k]) => k.toLowerCase() === "content-type")) {
|
|
731
|
+
headers.push(["Content-Type", "application/json"]);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const expectedStatuses = extractExpectedStatuses(expected.status);
|
|
735
|
+
if (expectedStatuses.length === 0 && invType === "web_route") {
|
|
736
|
+
expectedStatuses.push(200);
|
|
737
|
+
}
|
|
738
|
+
let bodyExact;
|
|
739
|
+
if (typeof expected.bodyExact === "string" && expected.bodyExact.length > 0) {
|
|
740
|
+
const sanitizedExact = sanitizeRequestBody(expected.bodyExact, diag);
|
|
741
|
+
if (sanitizedExact) {
|
|
742
|
+
bodyExact = sanitizedExact.text;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
const bodyContains = extractBodyContains(expected, invType);
|
|
746
|
+
let jsonSubset;
|
|
747
|
+
if (expected.jsonSubset !== undefined) {
|
|
748
|
+
jsonSubset = sanitizeJsonValue(expected.jsonSubset, 0, new Set(), diag);
|
|
749
|
+
}
|
|
750
|
+
let jsonSchema;
|
|
751
|
+
if (isRecord(expected.jsonSchema)) {
|
|
752
|
+
jsonSchema = sanitizeSchemaCheck(expected.jsonSchema, 0, new Set(), diag);
|
|
753
|
+
}
|
|
754
|
+
const jsonPaths = sanitizeJsonPaths(expected.jsonPaths, diag);
|
|
755
|
+
let maxLatencyMs;
|
|
756
|
+
if (typeof expected.maxLatencyMs === "number" &&
|
|
757
|
+
Number.isFinite(expected.maxLatencyMs) &&
|
|
758
|
+
expected.maxLatencyMs > 0) {
|
|
759
|
+
maxLatencyMs = Math.round(expected.maxLatencyMs);
|
|
760
|
+
}
|
|
761
|
+
if (diag.hadCircular) {
|
|
762
|
+
warnings.push(`Sanitized circular reference in invariant ${id}.`);
|
|
763
|
+
}
|
|
764
|
+
if (diag.hadDepthLimit) {
|
|
765
|
+
warnings.push(`Truncated deeply nested payload or schema in invariant ${id}.`);
|
|
766
|
+
}
|
|
767
|
+
const rawDesc = typeof inv.description === "string" && inv.description.trim()
|
|
768
|
+
? sanitizeSingleLine(inv.description)
|
|
769
|
+
: "";
|
|
770
|
+
const label = rawDesc ? `${id}: ${rawDesc}` : `${id}: ${method} ${pathname}`;
|
|
771
|
+
return {
|
|
772
|
+
scenario: {
|
|
773
|
+
id,
|
|
774
|
+
label,
|
|
775
|
+
invariantType: invType,
|
|
776
|
+
method,
|
|
777
|
+
pathname,
|
|
778
|
+
requestPath,
|
|
779
|
+
query,
|
|
780
|
+
headers,
|
|
781
|
+
...(body ? { body } : {}),
|
|
782
|
+
expectedStatuses,
|
|
783
|
+
expectedHeaders,
|
|
784
|
+
...(bodyExact !== undefined ? { bodyExact } : {}),
|
|
785
|
+
bodyContains,
|
|
786
|
+
...(jsonSubset !== undefined ? { jsonSubset } : {}),
|
|
787
|
+
...(jsonSchema ? { jsonSchema } : {}),
|
|
788
|
+
jsonPaths,
|
|
789
|
+
...(maxLatencyMs !== undefined ? { maxLatencyMs } : {})
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
function validatePositiveInt(value, name, fallback, max) {
|
|
794
|
+
if (value === undefined)
|
|
795
|
+
return fallback;
|
|
796
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) {
|
|
797
|
+
throw new VibecodeError("CONTRACT_INVALID", `exportLoadSuite option "${name}" must be an integer between 1 and ${max}.`);
|
|
798
|
+
}
|
|
799
|
+
return value;
|
|
800
|
+
}
|
|
801
|
+
function resolveLatencyThresholds(scenarios, strict) {
|
|
802
|
+
let minContractBudget;
|
|
803
|
+
for (const s of scenarios) {
|
|
804
|
+
if (s.maxLatencyMs !== undefined) {
|
|
805
|
+
minContractBudget =
|
|
806
|
+
minContractBudget === undefined
|
|
807
|
+
? s.maxLatencyMs
|
|
808
|
+
: Math.min(minContractBudget, s.maxLatencyMs);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
if (strict) {
|
|
812
|
+
const p95 = minContractBudget !== undefined
|
|
813
|
+
? Math.min(STRICT_DEFAULT_P95_MS, minContractBudget)
|
|
814
|
+
: STRICT_DEFAULT_P95_MS;
|
|
815
|
+
const p99 = Math.max(p95, Math.min(STRICT_DEFAULT_P99_MS, p95 * 2));
|
|
816
|
+
return { p95ThresholdMs: p95, p99ThresholdMs: p99 };
|
|
817
|
+
}
|
|
818
|
+
const p95 = minContractBudget !== undefined
|
|
819
|
+
? Math.min(RELAXED_DEFAULT_P95_MS, minContractBudget)
|
|
820
|
+
: RELAXED_DEFAULT_P95_MS;
|
|
821
|
+
const p99 = Math.max(p95, Math.min(RELAXED_DEFAULT_P99_MS, p95 * 2));
|
|
822
|
+
return { p95ThresholdMs: p95, p99ThresholdMs: p99 };
|
|
823
|
+
}
|
|
824
|
+
function buildHeadersObject(headers) {
|
|
825
|
+
const out = {};
|
|
826
|
+
for (const [k, v] of headers) {
|
|
827
|
+
if (isForbiddenKey(k))
|
|
828
|
+
continue;
|
|
829
|
+
out[k] = v;
|
|
830
|
+
}
|
|
831
|
+
return out;
|
|
832
|
+
}
|
|
833
|
+
function emitK6Suite(scenarios, cfg, skippedInvariants, warnings) {
|
|
834
|
+
const lines = [];
|
|
835
|
+
lines.push(`// Generated by vibecode-anything load-export (k6)`);
|
|
836
|
+
lines.push(`// Suite: ${sanitizeCommentLine(cfg.title)}`);
|
|
837
|
+
lines.push(`// Target override: API_BASE_URL (default: ${sanitizeCommentLine(cfg.baseUrl)})`);
|
|
838
|
+
lines.push(`// Auth override: API_AUTH_HEADER (never hardcoded)`);
|
|
839
|
+
if (cfg.includeSkippedComments && skippedInvariants.length > 0) {
|
|
840
|
+
const summary = skippedInvariants
|
|
841
|
+
.map((s) => `${sanitizeCommentLine(s.id)} (${sanitizeCommentLine(s.reason)})`)
|
|
842
|
+
.join(", ");
|
|
843
|
+
lines.push(`// Skipped invariants (${skippedInvariants.length}): ${summary}`);
|
|
844
|
+
}
|
|
845
|
+
lines.push("");
|
|
846
|
+
lines.push(`import http from "k6/http";`);
|
|
847
|
+
lines.push(`import { check, group } from "k6";`);
|
|
848
|
+
lines.push("");
|
|
849
|
+
lines.push(`const DEFAULT_BASE_URL = ${safeJsLiteral(cfg.baseUrl)};`);
|
|
850
|
+
lines.push(`const BASE_URL = String(__ENV.API_BASE_URL || DEFAULT_BASE_URL).replace(/\\/+$/, "");`);
|
|
851
|
+
lines.push(`const AUTH_HEADER = String(__ENV.API_AUTH_HEADER || "");`);
|
|
852
|
+
lines.push("");
|
|
853
|
+
const k6Options = {
|
|
854
|
+
vus: cfg.vus
|
|
855
|
+
};
|
|
856
|
+
if (cfg.explicitIterations && !cfg.explicitDuration) {
|
|
857
|
+
k6Options.iterations = cfg.iterations;
|
|
858
|
+
}
|
|
859
|
+
else {
|
|
860
|
+
k6Options.duration = `${cfg.durationSec}s`;
|
|
861
|
+
if (cfg.explicitIterations && cfg.explicitDuration) {
|
|
862
|
+
warnings.push("k6 top-level options cannot combine duration and iterations; emitted duration.");
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
k6Options.thresholds = cfg.strict
|
|
866
|
+
? {
|
|
867
|
+
http_req_failed: ["rate==0"],
|
|
868
|
+
http_req_duration: [`p(95)<${cfg.p95ThresholdMs}`, `p(99)<${cfg.p99ThresholdMs}`],
|
|
869
|
+
checks: ["rate==1"]
|
|
870
|
+
}
|
|
871
|
+
: {
|
|
872
|
+
http_req_failed: ["rate<0.05"],
|
|
873
|
+
http_req_duration: [`p(95)<${cfg.p95ThresholdMs}`],
|
|
874
|
+
checks: ["rate>0.95"]
|
|
875
|
+
};
|
|
876
|
+
lines.push(`export const options = ${JSON.stringify(k6Options, null, 2)};`);
|
|
877
|
+
lines.push("");
|
|
878
|
+
lines.push(`const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);`);
|
|
879
|
+
lines.push("");
|
|
880
|
+
lines.push(`function buildHeaders(baseHeaders) {`);
|
|
881
|
+
lines.push(` const out = {};`);
|
|
882
|
+
lines.push(` if (baseHeaders && typeof baseHeaders === "object") {`);
|
|
883
|
+
lines.push(` for (const key of Object.keys(baseHeaders)) {`);
|
|
884
|
+
lines.push(` if (!FORBIDDEN_KEYS.has(key)) out[key] = baseHeaders[key];`);
|
|
885
|
+
lines.push(` }`);
|
|
886
|
+
lines.push(` }`);
|
|
887
|
+
lines.push(` if (AUTH_HEADER) {`);
|
|
888
|
+
lines.push(` out["Authorization"] = AUTH_HEADER;`);
|
|
889
|
+
lines.push(` }`);
|
|
890
|
+
lines.push(` return out;`);
|
|
891
|
+
lines.push(`}`);
|
|
892
|
+
lines.push("");
|
|
893
|
+
lines.push(`function tryParseJson(res) {`);
|
|
894
|
+
lines.push(` try {`);
|
|
895
|
+
lines.push(` return { ok: true, value: res.json() };`);
|
|
896
|
+
lines.push(` } catch {`);
|
|
897
|
+
lines.push(` return { ok: false, value: null };`);
|
|
898
|
+
lines.push(` }`);
|
|
899
|
+
lines.push(`}`);
|
|
900
|
+
lines.push("");
|
|
901
|
+
lines.push(`function hasOwn(obj, key) {`);
|
|
902
|
+
lines.push(` return obj !== null && typeof obj === "object" && !FORBIDDEN_KEYS.has(key) && Object.prototype.hasOwnProperty.call(obj, key);`);
|
|
903
|
+
lines.push(`}`);
|
|
904
|
+
lines.push("");
|
|
905
|
+
lines.push(`function matchesSubset(actual, expected) {`);
|
|
906
|
+
lines.push(` if (expected === null || typeof expected !== "object") {`);
|
|
907
|
+
lines.push(` return Object.is(actual, expected);`);
|
|
908
|
+
lines.push(` }`);
|
|
909
|
+
lines.push(` if (Array.isArray(expected)) {`);
|
|
910
|
+
lines.push(` if (!Array.isArray(actual) || actual.length < expected.length) return false;`);
|
|
911
|
+
lines.push(` for (let i = 0; i < expected.length; i++) {`);
|
|
912
|
+
lines.push(` if (!matchesSubset(actual[i], expected[i])) return false;`);
|
|
913
|
+
lines.push(` }`);
|
|
914
|
+
lines.push(` return true;`);
|
|
915
|
+
lines.push(` }`);
|
|
916
|
+
lines.push(` if (actual === null || typeof actual !== "object" || Array.isArray(actual)) return false;`);
|
|
917
|
+
lines.push(` for (const key of Object.keys(expected)) {`);
|
|
918
|
+
lines.push(` if (FORBIDDEN_KEYS.has(key)) continue;`);
|
|
919
|
+
lines.push(` if (!hasOwn(actual, key)) return false;`);
|
|
920
|
+
lines.push(` if (!matchesSubset(actual[key], expected[key])) return false;`);
|
|
921
|
+
lines.push(` }`);
|
|
922
|
+
lines.push(` return true;`);
|
|
923
|
+
lines.push(`}`);
|
|
924
|
+
lines.push("");
|
|
925
|
+
lines.push(`function matchesType(value, expectedType) {`);
|
|
926
|
+
lines.push(` const allowed = Array.isArray(expectedType) ? expectedType : [expectedType];`);
|
|
927
|
+
lines.push(` return allowed.some((t) => {`);
|
|
928
|
+
lines.push(` if (t === "null") return value === null;`);
|
|
929
|
+
lines.push(` if (t === "array") return Array.isArray(value);`);
|
|
930
|
+
lines.push(` if (t === "object") return value !== null && typeof value === "object" && !Array.isArray(value);`);
|
|
931
|
+
lines.push(` if (t === "integer") return typeof value === "number" && Number.isInteger(value);`);
|
|
932
|
+
lines.push(` return typeof value === t;`);
|
|
933
|
+
lines.push(` });`);
|
|
934
|
+
lines.push(`}`);
|
|
935
|
+
lines.push("");
|
|
936
|
+
lines.push(`function matchesSchema(value, schema) {`);
|
|
937
|
+
lines.push(` if (!schema || typeof schema !== "object") return true;`);
|
|
938
|
+
lines.push(` if (schema.type && !matchesType(value, schema.type)) return false;`);
|
|
939
|
+
lines.push(` if (Object.prototype.hasOwnProperty.call(schema, "const") && !matchesSubset(value, schema.const)) return false;`);
|
|
940
|
+
lines.push(` if (Array.isArray(schema.enum) && !schema.enum.some((e) => matchesSubset(value, e))) return false;`);
|
|
941
|
+
lines.push(` if (Array.isArray(schema.required)) {`);
|
|
942
|
+
lines.push(` if (value === null || typeof value !== "object" || Array.isArray(value)) return false;`);
|
|
943
|
+
lines.push(` for (const key of schema.required) {`);
|
|
944
|
+
lines.push(` if (!hasOwn(value, key)) return false;`);
|
|
945
|
+
lines.push(` }`);
|
|
946
|
+
lines.push(` }`);
|
|
947
|
+
lines.push(` if (schema.properties && value !== null && typeof value === "object" && !Array.isArray(value)) {`);
|
|
948
|
+
lines.push(` for (const key of Object.keys(schema.properties)) {`);
|
|
949
|
+
lines.push(` if (hasOwn(value, key) && !matchesSchema(value[key], schema.properties[key])) return false;`);
|
|
950
|
+
lines.push(` }`);
|
|
951
|
+
lines.push(` }`);
|
|
952
|
+
lines.push(` if (schema.items && Array.isArray(value)) {`);
|
|
953
|
+
lines.push(` for (const item of value) {`);
|
|
954
|
+
lines.push(` if (!matchesSchema(item, schema.items)) return false;`);
|
|
955
|
+
lines.push(` }`);
|
|
956
|
+
lines.push(` }`);
|
|
957
|
+
lines.push(` return true;`);
|
|
958
|
+
lines.push(`}`);
|
|
959
|
+
lines.push("");
|
|
960
|
+
lines.push(`function queryJsonPath(root, expr) {`);
|
|
961
|
+
lines.push(` const cleaned = String(expr || "").replace(/^\\$\\.?/, "");`);
|
|
962
|
+
lines.push(` if (!cleaned) return { found: true, value: root };`);
|
|
963
|
+
lines.push(` const tokens = [];`);
|
|
964
|
+
lines.push(` const re = /([^.\\[\\]]+)|\\[(\\d+|"[^"]*"|'[^']*')\\]/g;`);
|
|
965
|
+
lines.push(` let m;`);
|
|
966
|
+
lines.push(` while ((m = re.exec(cleaned)) !== null) {`);
|
|
967
|
+
lines.push(` const raw = m[1] !== undefined ? m[1] : m[2];`);
|
|
968
|
+
lines.push(` tokens.push(raw.replace(/^["']|["']$/g, ""));`);
|
|
969
|
+
lines.push(` }`);
|
|
970
|
+
lines.push(` let cur = root;`);
|
|
971
|
+
lines.push(` for (const token of tokens) {`);
|
|
972
|
+
lines.push(` if (FORBIDDEN_KEYS.has(token) || cur === null || typeof cur !== "object") {`);
|
|
973
|
+
lines.push(` return { found: false, value: undefined };`);
|
|
974
|
+
lines.push(` }`);
|
|
975
|
+
lines.push(` if (Array.isArray(cur)) {`);
|
|
976
|
+
lines.push(` const idx = Number.parseInt(token, 10);`);
|
|
977
|
+
lines.push(` if (!Number.isInteger(idx) || idx < 0 || idx >= cur.length) return { found: false, value: undefined };`);
|
|
978
|
+
lines.push(` cur = cur[idx];`);
|
|
979
|
+
lines.push(` } else {`);
|
|
980
|
+
lines.push(` if (!hasOwn(cur, token)) return { found: false, value: undefined };`);
|
|
981
|
+
lines.push(` cur = cur[token];`);
|
|
982
|
+
lines.push(` }`);
|
|
983
|
+
lines.push(` }`);
|
|
984
|
+
lines.push(` return { found: true, value: cur };`);
|
|
985
|
+
lines.push(`}`);
|
|
986
|
+
lines.push("");
|
|
987
|
+
lines.push(`function getHeaderCI(headers, name) {`);
|
|
988
|
+
lines.push(` if (!headers || typeof headers !== "object") return undefined;`);
|
|
989
|
+
lines.push(` const target = name.toLowerCase();`);
|
|
990
|
+
lines.push(` for (const key of Object.keys(headers)) {`);
|
|
991
|
+
lines.push(` if (key.toLowerCase() === target) return String(headers[key]);`);
|
|
992
|
+
lines.push(` }`);
|
|
993
|
+
lines.push(` return undefined;`);
|
|
994
|
+
lines.push(`}`);
|
|
995
|
+
lines.push("");
|
|
996
|
+
const serializedScenarios = scenarios.map((s) => ({
|
|
997
|
+
id: s.id,
|
|
998
|
+
label: s.label,
|
|
999
|
+
method: s.method,
|
|
1000
|
+
requestPath: s.requestPath,
|
|
1001
|
+
headers: buildHeadersObject(s.headers),
|
|
1002
|
+
body: s.body ? s.body.text : null,
|
|
1003
|
+
expectedStatuses: s.expectedStatuses,
|
|
1004
|
+
expectedHeaders: s.expectedHeaders,
|
|
1005
|
+
bodyExact: s.bodyExact ?? null,
|
|
1006
|
+
bodyContains: s.bodyContains,
|
|
1007
|
+
jsonSubset: s.jsonSubset !== undefined ? s.jsonSubset : null,
|
|
1008
|
+
hasJsonSubset: s.jsonSubset !== undefined,
|
|
1009
|
+
jsonSchema: s.jsonSchema ?? null,
|
|
1010
|
+
jsonPaths: s.jsonPaths,
|
|
1011
|
+
maxLatencyMs: s.maxLatencyMs ?? null
|
|
1012
|
+
}));
|
|
1013
|
+
lines.push(`const SCENARIOS = ${safeJsLiteral(serializedScenarios)};`);
|
|
1014
|
+
lines.push("");
|
|
1015
|
+
lines.push(`export default function () {`);
|
|
1016
|
+
lines.push(` for (const sc of SCENARIOS) {`);
|
|
1017
|
+
lines.push(` group(sc.label, () => {`);
|
|
1018
|
+
lines.push(` const url = BASE_URL + sc.requestPath;`);
|
|
1019
|
+
lines.push(` const res = http.request(sc.method, url, sc.body, {`);
|
|
1020
|
+
lines.push(` headers: buildHeaders(sc.headers),`);
|
|
1021
|
+
lines.push(` tags: { scenario: sc.id }`);
|
|
1022
|
+
lines.push(` });`);
|
|
1023
|
+
lines.push(` const checks = {};`);
|
|
1024
|
+
lines.push(` if (sc.expectedStatuses.length > 0) {`);
|
|
1025
|
+
lines.push(` checks["status matches contract"] = (r) => sc.expectedStatuses.includes(r.status);`);
|
|
1026
|
+
lines.push(` } else {`);
|
|
1027
|
+
lines.push(` checks["status is 2xx/3xx"] = (r) => r.status >= 200 && r.status < 400;`);
|
|
1028
|
+
lines.push(` }`);
|
|
1029
|
+
lines.push(` for (const [hName, hVal] of sc.expectedHeaders) {`);
|
|
1030
|
+
lines.push(` checks["header " + hName] = (r) => {`);
|
|
1031
|
+
lines.push(` const actual = getHeaderCI(r.headers, hName);`);
|
|
1032
|
+
lines.push(` return typeof actual === "string" && actual.toLowerCase().includes(hVal.toLowerCase());`);
|
|
1033
|
+
lines.push(` };`);
|
|
1034
|
+
lines.push(` }`);
|
|
1035
|
+
lines.push(` if (sc.bodyExact !== null) {`);
|
|
1036
|
+
lines.push(` checks["body matches exact"] = (r) => String(r.body ?? "") === sc.bodyExact;`);
|
|
1037
|
+
lines.push(` }`);
|
|
1038
|
+
lines.push(` for (const needle of sc.bodyContains) {`);
|
|
1039
|
+
lines.push(` checks["body contains " + needle] = (r) => String(r.body ?? "").includes(needle);`);
|
|
1040
|
+
lines.push(` }`);
|
|
1041
|
+
lines.push(` const needsJson = sc.hasJsonSubset || sc.jsonSchema !== null || sc.jsonPaths.length > 0;`);
|
|
1042
|
+
lines.push(` if (needsJson) {`);
|
|
1043
|
+
lines.push(` const parsed = tryParseJson(res);`);
|
|
1044
|
+
lines.push(` checks["valid JSON body"] = () => parsed.ok;`);
|
|
1045
|
+
lines.push(` if (sc.hasJsonSubset) {`);
|
|
1046
|
+
lines.push(` checks["matches jsonSubset"] = () => parsed.ok && matchesSubset(parsed.value, sc.jsonSubset);`);
|
|
1047
|
+
lines.push(` }`);
|
|
1048
|
+
lines.push(` if (sc.jsonSchema !== null) {`);
|
|
1049
|
+
lines.push(` checks["matches jsonSchema"] = () => parsed.ok && matchesSchema(parsed.value, sc.jsonSchema);`);
|
|
1050
|
+
lines.push(` }`);
|
|
1051
|
+
lines.push(` for (const jp of sc.jsonPaths) {`);
|
|
1052
|
+
lines.push(` checks["jsonPath " + jp.path] = () => {`);
|
|
1053
|
+
lines.push(` if (!parsed.ok) return false;`);
|
|
1054
|
+
lines.push(` const q = queryJsonPath(parsed.value, jp.path);`);
|
|
1055
|
+
lines.push(` if (!q.found) return false;`);
|
|
1056
|
+
lines.push(` if (Object.prototype.hasOwnProperty.call(jp, "equals") && !matchesSubset(q.value, jp.equals)) return false;`);
|
|
1057
|
+
lines.push(` if (typeof jp.matches === "string") {`);
|
|
1058
|
+
lines.push(` try { return new RegExp(jp.matches).test(String(q.value ?? "")); } catch { return false; }`);
|
|
1059
|
+
lines.push(` }`);
|
|
1060
|
+
lines.push(` return true;`);
|
|
1061
|
+
lines.push(` };`);
|
|
1062
|
+
lines.push(` }`);
|
|
1063
|
+
lines.push(` }`);
|
|
1064
|
+
lines.push(` if (typeof sc.maxLatencyMs === "number") {`);
|
|
1065
|
+
lines.push(` checks["latency <= " + sc.maxLatencyMs + "ms"] = (r) => Boolean(r.timings && r.timings.duration <= sc.maxLatencyMs);`);
|
|
1066
|
+
lines.push(` }`);
|
|
1067
|
+
lines.push(` check(res, checks);`);
|
|
1068
|
+
lines.push(` });`);
|
|
1069
|
+
lines.push(` }`);
|
|
1070
|
+
lines.push(`}`);
|
|
1071
|
+
lines.push("");
|
|
1072
|
+
return lines.join("\n");
|
|
1073
|
+
}
|
|
1074
|
+
function normalizeArtilleryJsonPath(rawPath) {
|
|
1075
|
+
const trimmed = rawPath.trim();
|
|
1076
|
+
if (trimmed.startsWith("$"))
|
|
1077
|
+
return trimmed;
|
|
1078
|
+
return trimmed.startsWith("[") ? `$${trimmed}` : `$.${trimmed}`;
|
|
1079
|
+
}
|
|
1080
|
+
function escapeRegexpLiteral(raw) {
|
|
1081
|
+
return raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1082
|
+
}
|
|
1083
|
+
function emitArtillerySuite(scenarios, cfg, skippedInvariants) {
|
|
1084
|
+
const phase = {
|
|
1085
|
+
duration: cfg.durationSec,
|
|
1086
|
+
name: "Contract load phase"
|
|
1087
|
+
};
|
|
1088
|
+
if (cfg.explicitIterations && !cfg.explicitDuration) {
|
|
1089
|
+
phase.arrivalCount = cfg.iterations;
|
|
1090
|
+
phase.maxVusers = cfg.vus;
|
|
1091
|
+
}
|
|
1092
|
+
else {
|
|
1093
|
+
phase.arrivalRate = cfg.vus;
|
|
1094
|
+
}
|
|
1095
|
+
const configObj = {
|
|
1096
|
+
target: "{{$processEnvironment.API_BASE_URL}}",
|
|
1097
|
+
phases: [phase],
|
|
1098
|
+
defaults: {
|
|
1099
|
+
headers: {
|
|
1100
|
+
Authorization: "{{$processEnvironment.API_AUTH_HEADER}}"
|
|
1101
|
+
}
|
|
1102
|
+
},
|
|
1103
|
+
plugins: {
|
|
1104
|
+
expect: {}
|
|
1105
|
+
}
|
|
1106
|
+
};
|
|
1107
|
+
if (cfg.strict) {
|
|
1108
|
+
configObj.ensure = {
|
|
1109
|
+
maxErrorRate: 0,
|
|
1110
|
+
p95: cfg.p95ThresholdMs,
|
|
1111
|
+
p99: cfg.p99ThresholdMs,
|
|
1112
|
+
thresholds: [
|
|
1113
|
+
{ "http.response_time.p95": cfg.p95ThresholdMs },
|
|
1114
|
+
{ "http.response_time.p99": cfg.p99ThresholdMs }
|
|
1115
|
+
]
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
const artilleryScenarios = scenarios.map((sc, scIdx) => {
|
|
1119
|
+
const stepConfig = {
|
|
1120
|
+
url: sc.requestPath
|
|
1121
|
+
};
|
|
1122
|
+
const reqHeaders = buildHeadersObject(sc.headers);
|
|
1123
|
+
if (Object.keys(reqHeaders).length > 0) {
|
|
1124
|
+
stepConfig.headers = reqHeaders;
|
|
1125
|
+
}
|
|
1126
|
+
if (sc.body) {
|
|
1127
|
+
if (sc.body.isJson && sc.body.parsedJson !== undefined) {
|
|
1128
|
+
stepConfig.json = sc.body.parsedJson;
|
|
1129
|
+
}
|
|
1130
|
+
else {
|
|
1131
|
+
stepConfig.body = sc.body.text;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
const captures = [];
|
|
1135
|
+
const expects = [];
|
|
1136
|
+
const seenProps = new Set();
|
|
1137
|
+
let captureIdx = 0;
|
|
1138
|
+
if (sc.expectedStatuses.length === 1) {
|
|
1139
|
+
expects.push({ statusCode: sc.expectedStatuses[0] });
|
|
1140
|
+
}
|
|
1141
|
+
else if (sc.expectedStatuses.length > 1) {
|
|
1142
|
+
expects.push({ statusCode: sc.expectedStatuses });
|
|
1143
|
+
}
|
|
1144
|
+
for (const [hName, hVal] of sc.expectedHeaders) {
|
|
1145
|
+
if (hName.toLowerCase() === "content-type") {
|
|
1146
|
+
expects.push({ contentType: hVal.split(";")[0]?.trim() || hVal });
|
|
1147
|
+
}
|
|
1148
|
+
else {
|
|
1149
|
+
expects.push({ headerEquals: [hName, hVal] });
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
if (isRecord(sc.jsonSubset)) {
|
|
1153
|
+
for (const [key, val] of Object.entries(sc.jsonSubset)) {
|
|
1154
|
+
if (isForbiddenKey(key))
|
|
1155
|
+
continue;
|
|
1156
|
+
if (!seenProps.has(key)) {
|
|
1157
|
+
expects.push({ hasProperty: key });
|
|
1158
|
+
seenProps.add(key);
|
|
1159
|
+
}
|
|
1160
|
+
if (typeof val === "string" ||
|
|
1161
|
+
typeof val === "number" ||
|
|
1162
|
+
typeof val === "boolean") {
|
|
1163
|
+
const varName = `s${scIdx}_field_${captureIdx++}`;
|
|
1164
|
+
const jsonPropExpr = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
1165
|
+
? `$.${key}`
|
|
1166
|
+
: `$[${JSON.stringify(key)}]`;
|
|
1167
|
+
captures.push({ json: jsonPropExpr, as: varName });
|
|
1168
|
+
expects.push({ equals: [`{{ ${varName} }}`, val] });
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
if (sc.jsonSchema?.required) {
|
|
1173
|
+
for (const reqKey of sc.jsonSchema.required) {
|
|
1174
|
+
if (isForbiddenKey(reqKey) || seenProps.has(reqKey))
|
|
1175
|
+
continue;
|
|
1176
|
+
expects.push({ hasProperty: reqKey });
|
|
1177
|
+
seenProps.add(reqKey);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
for (const jp of sc.jsonPaths) {
|
|
1181
|
+
const varName = `s${scIdx}_jp_${captureIdx++}`;
|
|
1182
|
+
const jsonExpr = normalizeArtilleryJsonPath(jp.path);
|
|
1183
|
+
captures.push({ json: jsonExpr, as: varName });
|
|
1184
|
+
if (jp.equals !== undefined) {
|
|
1185
|
+
if (typeof jp.equals === "string" ||
|
|
1186
|
+
typeof jp.equals === "number" ||
|
|
1187
|
+
typeof jp.equals === "boolean") {
|
|
1188
|
+
expects.push({ equals: [`{{ ${varName} }}`, jp.equals] });
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
else if (jp.matches) {
|
|
1192
|
+
expects.push({ matchesRegexp: jp.matches });
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
for (const needle of sc.bodyContains) {
|
|
1196
|
+
expects.push({ matchesRegexp: escapeRegexpLiteral(needle) });
|
|
1197
|
+
}
|
|
1198
|
+
if (captures.length > 0) {
|
|
1199
|
+
stepConfig.capture = captures;
|
|
1200
|
+
}
|
|
1201
|
+
if (expects.length > 0) {
|
|
1202
|
+
stepConfig.expect = expects;
|
|
1203
|
+
}
|
|
1204
|
+
const methodLower = sc.method.toLowerCase();
|
|
1205
|
+
const flowStep = {};
|
|
1206
|
+
flowStep[methodLower] = stepConfig;
|
|
1207
|
+
return {
|
|
1208
|
+
name: sc.label,
|
|
1209
|
+
flow: [flowStep]
|
|
1210
|
+
};
|
|
1211
|
+
});
|
|
1212
|
+
const doc = {
|
|
1213
|
+
config: configObj,
|
|
1214
|
+
scenarios: artilleryScenarios
|
|
1215
|
+
};
|
|
1216
|
+
const commentLines = [
|
|
1217
|
+
`# Generated by vibecode-anything load-export (artillery)`,
|
|
1218
|
+
`# Suite: ${sanitizeCommentLine(cfg.title)}`,
|
|
1219
|
+
`# Default target (set API_BASE_URL): ${sanitizeCommentLine(cfg.baseUrl)}`,
|
|
1220
|
+
`# Optional auth header: API_AUTH_HEADER`
|
|
1221
|
+
];
|
|
1222
|
+
if (cfg.includeSkippedComments && skippedInvariants.length > 0) {
|
|
1223
|
+
const summary = skippedInvariants
|
|
1224
|
+
.map((s) => `${sanitizeCommentLine(s.id)} (${sanitizeCommentLine(s.reason)})`)
|
|
1225
|
+
.join(", ");
|
|
1226
|
+
commentLines.push(`# Skipped invariants (${skippedInvariants.length}): ${summary}`);
|
|
1227
|
+
}
|
|
1228
|
+
return `${commentLines.join("\n")}\n${serializeYaml(doc)}`;
|
|
1229
|
+
}
|
|
1230
|
+
function emitNodeBenchSuite(scenarios, cfg, skippedInvariants) {
|
|
1231
|
+
const lines = [];
|
|
1232
|
+
lines.push(`// Generated by vibecode-anything load-export (node-bench)`);
|
|
1233
|
+
lines.push(`// Suite: ${sanitizeCommentLine(cfg.title)}`);
|
|
1234
|
+
lines.push(`// Runtime env: API_BASE_URL, API_AUTH_HEADER, LOAD_VUS, LOAD_ITERATIONS, LOAD_TIMEOUT_MS`);
|
|
1235
|
+
if (cfg.includeSkippedComments && skippedInvariants.length > 0) {
|
|
1236
|
+
const summary = skippedInvariants
|
|
1237
|
+
.map((s) => `${sanitizeCommentLine(s.id)} (${sanitizeCommentLine(s.reason)})`)
|
|
1238
|
+
.join(", ");
|
|
1239
|
+
lines.push(`// Skipped invariants (${skippedInvariants.length}): ${summary}`);
|
|
1240
|
+
}
|
|
1241
|
+
const serializedScenarios = scenarios.map((s) => ({
|
|
1242
|
+
id: s.id,
|
|
1243
|
+
label: s.label,
|
|
1244
|
+
method: s.method,
|
|
1245
|
+
requestPath: s.requestPath,
|
|
1246
|
+
headers: buildHeadersObject(s.headers),
|
|
1247
|
+
body: s.body ? s.body.text : null,
|
|
1248
|
+
expectedStatuses: s.expectedStatuses,
|
|
1249
|
+
expectedHeaders: s.expectedHeaders,
|
|
1250
|
+
bodyExact: s.bodyExact ?? null,
|
|
1251
|
+
bodyContains: s.bodyContains,
|
|
1252
|
+
jsonSubset: s.jsonSubset !== undefined ? s.jsonSubset : null,
|
|
1253
|
+
hasJsonSubset: s.jsonSubset !== undefined,
|
|
1254
|
+
jsonSchema: s.jsonSchema ?? null,
|
|
1255
|
+
jsonPaths: s.jsonPaths,
|
|
1256
|
+
maxLatencyMs: s.maxLatencyMs ?? null
|
|
1257
|
+
}));
|
|
1258
|
+
lines.push("");
|
|
1259
|
+
lines.push(`const SUITE_TITLE = ${safeJsLiteral(cfg.title)};`);
|
|
1260
|
+
lines.push(`const DEFAULT_BASE_URL = ${safeJsLiteral(cfg.baseUrl)};`);
|
|
1261
|
+
lines.push(`const STRICT = ${cfg.strict ? "true" : "false"};`);
|
|
1262
|
+
lines.push(`const DEFAULT_VUS = ${cfg.vus};`);
|
|
1263
|
+
lines.push(`const DEFAULT_ITERATIONS = ${cfg.iterations};`);
|
|
1264
|
+
lines.push(`const MAX_P95_MS = ${cfg.p95ThresholdMs};`);
|
|
1265
|
+
lines.push(`const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);`);
|
|
1266
|
+
lines.push(`const SCENARIOS = ${safeJsLiteral(serializedScenarios)};`);
|
|
1267
|
+
lines.push("");
|
|
1268
|
+
lines.push(`function parsePositiveInt(raw, fallback) {`);
|
|
1269
|
+
lines.push(` const parsed = Number.parseInt(String(raw || ""), 10);`);
|
|
1270
|
+
lines.push(` return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;`);
|
|
1271
|
+
lines.push(`}`);
|
|
1272
|
+
lines.push("");
|
|
1273
|
+
lines.push(`function hasOwn(obj, key) {`);
|
|
1274
|
+
lines.push(` return obj !== null && typeof obj === "object" && !FORBIDDEN_KEYS.has(key) && Object.prototype.hasOwnProperty.call(obj, key);`);
|
|
1275
|
+
lines.push(`}`);
|
|
1276
|
+
lines.push("");
|
|
1277
|
+
lines.push('const HEADER_NAME_RE = /^[!#$%&\'*+\\-.^_`|~0-9A-Za-z]+$/;');
|
|
1278
|
+
lines.push("");
|
|
1279
|
+
lines.push("function parseAuthHeader(rawAuth) {");
|
|
1280
|
+
lines.push(' if (typeof rawAuth !== "string" || !rawAuth.trim()) return null;');
|
|
1281
|
+
lines.push(" if (/[\\r\\n\\0]/.test(rawAuth)) {");
|
|
1282
|
+
lines.push(' throw new Error("Invalid API_AUTH_HEADER: control characters are not allowed.");');
|
|
1283
|
+
lines.push(" }");
|
|
1284
|
+
lines.push(" const trimmed = rawAuth.trim();");
|
|
1285
|
+
lines.push(' const colonIdx = trimmed.indexOf(":");');
|
|
1286
|
+
lines.push(" if (colonIdx >= 0) {");
|
|
1287
|
+
lines.push(" const name = trimmed.slice(0, colonIdx).trim();");
|
|
1288
|
+
lines.push(" const value = trimmed.slice(colonIdx + 1).trim();");
|
|
1289
|
+
lines.push(" if (!HEADER_NAME_RE.test(name) || FORBIDDEN_KEYS.has(name) || FORBIDDEN_KEYS.has(name.toLowerCase()) || !value) {");
|
|
1290
|
+
lines.push(' throw new Error("Invalid API_AUTH_HEADER: forbidden or malformed header name/value.");');
|
|
1291
|
+
lines.push(" }");
|
|
1292
|
+
lines.push(" return { name, value };");
|
|
1293
|
+
lines.push(" }");
|
|
1294
|
+
lines.push(' return { name: "Authorization", value: trimmed };');
|
|
1295
|
+
lines.push("}");
|
|
1296
|
+
lines.push("");
|
|
1297
|
+
lines.push("function parseTargetBaseUrl(rawUrl) {");
|
|
1298
|
+
lines.push(' const parsed = new URL(String(rawUrl || "").trim());');
|
|
1299
|
+
lines.push(' if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {');
|
|
1300
|
+
lines.push(' throw new Error("Invalid API_BASE_URL protocol: only http: and https: are allowed.");');
|
|
1301
|
+
lines.push(" }");
|
|
1302
|
+
lines.push(' parsed.username = "";');
|
|
1303
|
+
lines.push(' parsed.password = "";');
|
|
1304
|
+
lines.push(' parsed.search = "";');
|
|
1305
|
+
lines.push(' parsed.hash = "";');
|
|
1306
|
+
lines.push(' const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\\/+$/, "");');
|
|
1307
|
+
lines.push(" const safeBaseUrl = parsed.origin + cleanPath;");
|
|
1308
|
+
lines.push(' const basePrefix = cleanPath ? cleanPath + "/" : "/";');
|
|
1309
|
+
lines.push(' const baseExact = cleanPath || "/";');
|
|
1310
|
+
lines.push(" return { safeBaseUrl, baseOrigin: parsed.origin, basePrefix, baseExact };");
|
|
1311
|
+
lines.push("}");
|
|
1312
|
+
lines.push("");
|
|
1313
|
+
lines.push(`function buildHeaders(baseHeaders, parsedAuth) {`);
|
|
1314
|
+
lines.push(` const out = Object.create(null);`);
|
|
1315
|
+
lines.push(` if (baseHeaders && typeof baseHeaders === "object") {`);
|
|
1316
|
+
lines.push(` for (const key of Object.keys(baseHeaders)) {`);
|
|
1317
|
+
lines.push(` if (!FORBIDDEN_KEYS.has(key)) out[key] = baseHeaders[key];`);
|
|
1318
|
+
lines.push(` }`);
|
|
1319
|
+
lines.push(` }`);
|
|
1320
|
+
lines.push(` if (parsedAuth) {`);
|
|
1321
|
+
lines.push(` const lower = parsedAuth.name.toLowerCase();`);
|
|
1322
|
+
lines.push(` for (const existing of Object.keys(out)) {`);
|
|
1323
|
+
lines.push(` if (existing.toLowerCase() === lower) {`);
|
|
1324
|
+
lines.push(` delete out[existing];`);
|
|
1325
|
+
lines.push(` }`);
|
|
1326
|
+
lines.push(` }`);
|
|
1327
|
+
lines.push(` out[parsedAuth.name] = parsedAuth.value;`);
|
|
1328
|
+
lines.push(` }`);
|
|
1329
|
+
lines.push(` return out;`);
|
|
1330
|
+
lines.push(`}`);
|
|
1331
|
+
lines.push("");
|
|
1332
|
+
lines.push(`function matchesSubset(actual, expected) {`);
|
|
1333
|
+
lines.push(` if (expected === null || typeof expected !== "object") {`);
|
|
1334
|
+
lines.push(` return Object.is(actual, expected);`);
|
|
1335
|
+
lines.push(` }`);
|
|
1336
|
+
lines.push(` if (Array.isArray(expected)) {`);
|
|
1337
|
+
lines.push(` if (!Array.isArray(actual) || actual.length < expected.length) return false;`);
|
|
1338
|
+
lines.push(` for (let i = 0; i < expected.length; i++) {`);
|
|
1339
|
+
lines.push(` if (!matchesSubset(actual[i], expected[i])) return false;`);
|
|
1340
|
+
lines.push(` }`);
|
|
1341
|
+
lines.push(` return true;`);
|
|
1342
|
+
lines.push(` }`);
|
|
1343
|
+
lines.push(` if (actual === null || typeof actual !== "object" || Array.isArray(actual)) return false;`);
|
|
1344
|
+
lines.push(` for (const key of Object.keys(expected)) {`);
|
|
1345
|
+
lines.push(` if (FORBIDDEN_KEYS.has(key)) continue;`);
|
|
1346
|
+
lines.push(` if (!hasOwn(actual, key)) return false;`);
|
|
1347
|
+
lines.push(` if (!matchesSubset(actual[key], expected[key])) return false;`);
|
|
1348
|
+
lines.push(` }`);
|
|
1349
|
+
lines.push(` return true;`);
|
|
1350
|
+
lines.push(`}`);
|
|
1351
|
+
lines.push("");
|
|
1352
|
+
lines.push(`function matchesType(value, expectedType) {`);
|
|
1353
|
+
lines.push(` const allowed = Array.isArray(expectedType) ? expectedType : [expectedType];`);
|
|
1354
|
+
lines.push(` return allowed.some((t) => {`);
|
|
1355
|
+
lines.push(` if (t === "null") return value === null;`);
|
|
1356
|
+
lines.push(` if (t === "array") return Array.isArray(value);`);
|
|
1357
|
+
lines.push(` if (t === "object") return value !== null && typeof value === "object" && !Array.isArray(value);`);
|
|
1358
|
+
lines.push(` if (t === "integer") return typeof value === "number" && Number.isInteger(value);`);
|
|
1359
|
+
lines.push(` return typeof value === t;`);
|
|
1360
|
+
lines.push(` });`);
|
|
1361
|
+
lines.push(`}`);
|
|
1362
|
+
lines.push("");
|
|
1363
|
+
lines.push(`function matchesSchema(value, schema) {`);
|
|
1364
|
+
lines.push(` if (!schema || typeof schema !== "object") return true;`);
|
|
1365
|
+
lines.push(` if (schema.type && !matchesType(value, schema.type)) return false;`);
|
|
1366
|
+
lines.push(` if (hasOwn(schema, "const") && !matchesSubset(value, schema.const)) return false;`);
|
|
1367
|
+
lines.push(` if (Array.isArray(schema.enum) && !schema.enum.some((e) => matchesSubset(value, e))) return false;`);
|
|
1368
|
+
lines.push(` if (typeof value === "string") {`);
|
|
1369
|
+
lines.push(` if (typeof schema.minLength === "number" && value.length < schema.minLength) return false;`);
|
|
1370
|
+
lines.push(` if (typeof schema.maxLength === "number" && value.length > schema.maxLength) return false;`);
|
|
1371
|
+
lines.push(` }`);
|
|
1372
|
+
lines.push(` if (typeof value === "number") {`);
|
|
1373
|
+
lines.push(` if (typeof schema.minimum === "number" && value < schema.minimum) return false;`);
|
|
1374
|
+
lines.push(` if (typeof schema.maximum === "number" && value > schema.maximum) return false;`);
|
|
1375
|
+
lines.push(` }`);
|
|
1376
|
+
lines.push(` if (Array.isArray(value)) {`);
|
|
1377
|
+
lines.push(` if (typeof schema.minItems === "number" && value.length < schema.minItems) return false;`);
|
|
1378
|
+
lines.push(` if (typeof schema.maxItems === "number" && value.length > schema.maxItems) return false;`);
|
|
1379
|
+
lines.push(` if (schema.items) {`);
|
|
1380
|
+
lines.push(` for (const item of value) {`);
|
|
1381
|
+
lines.push(` if (!matchesSchema(item, schema.items)) return false;`);
|
|
1382
|
+
lines.push(` }`);
|
|
1383
|
+
lines.push(` }`);
|
|
1384
|
+
lines.push(` }`);
|
|
1385
|
+
lines.push(` if (Array.isArray(schema.required)) {`);
|
|
1386
|
+
lines.push(` if (value === null || typeof value !== "object" || Array.isArray(value)) return false;`);
|
|
1387
|
+
lines.push(` for (const key of schema.required) {`);
|
|
1388
|
+
lines.push(` if (!hasOwn(value, key)) return false;`);
|
|
1389
|
+
lines.push(` }`);
|
|
1390
|
+
lines.push(` }`);
|
|
1391
|
+
lines.push(` if (schema.properties && value !== null && typeof value === "object" && !Array.isArray(value)) {`);
|
|
1392
|
+
lines.push(` for (const key of Object.keys(schema.properties)) {`);
|
|
1393
|
+
lines.push(` if (hasOwn(value, key) && !matchesSchema(value[key], schema.properties[key])) return false;`);
|
|
1394
|
+
lines.push(` }`);
|
|
1395
|
+
lines.push(` }`);
|
|
1396
|
+
lines.push(` return true;`);
|
|
1397
|
+
lines.push(`}`);
|
|
1398
|
+
lines.push("");
|
|
1399
|
+
lines.push(`function queryJsonPath(root, expr) {`);
|
|
1400
|
+
lines.push(` const cleaned = String(expr || "").replace(/^\\$\\.?/, "");`);
|
|
1401
|
+
lines.push(` if (!cleaned) return { found: true, value: root };`);
|
|
1402
|
+
lines.push(` const tokens = [];`);
|
|
1403
|
+
lines.push(` const re = /([^.\\[\\]]+)|\\[(\\d+|"[^"]*"|'[^']*')\\]/g;`);
|
|
1404
|
+
lines.push(` let m;`);
|
|
1405
|
+
lines.push(` while ((m = re.exec(cleaned)) !== null) {`);
|
|
1406
|
+
lines.push(` const raw = m[1] !== undefined ? m[1] : m[2];`);
|
|
1407
|
+
lines.push(` tokens.push(raw.replace(/^["']|["']$/g, ""));`);
|
|
1408
|
+
lines.push(` }`);
|
|
1409
|
+
lines.push(` let cur = root;`);
|
|
1410
|
+
lines.push(` for (const token of tokens) {`);
|
|
1411
|
+
lines.push(` if (FORBIDDEN_KEYS.has(token) || cur === null || typeof cur !== "object") {`);
|
|
1412
|
+
lines.push(` return { found: false, value: undefined };`);
|
|
1413
|
+
lines.push(` }`);
|
|
1414
|
+
lines.push(` if (Array.isArray(cur)) {`);
|
|
1415
|
+
lines.push(` const idx = Number.parseInt(token, 10);`);
|
|
1416
|
+
lines.push(` if (!Number.isInteger(idx) || idx < 0 || idx >= cur.length) return { found: false, value: undefined };`);
|
|
1417
|
+
lines.push(` cur = cur[idx];`);
|
|
1418
|
+
lines.push(` } else {`);
|
|
1419
|
+
lines.push(` if (!hasOwn(cur, token)) return { found: false, value: undefined };`);
|
|
1420
|
+
lines.push(` cur = cur[token];`);
|
|
1421
|
+
lines.push(` }`);
|
|
1422
|
+
lines.push(` }`);
|
|
1423
|
+
lines.push(` return { found: true, value: cur };`);
|
|
1424
|
+
lines.push(`}`);
|
|
1425
|
+
lines.push("");
|
|
1426
|
+
lines.push(`function percentile(sorted, p) {`);
|
|
1427
|
+
lines.push(` if (sorted.length === 0) return 0;`);
|
|
1428
|
+
lines.push(` const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));`);
|
|
1429
|
+
lines.push(` return Number(sorted[idx].toFixed(3));`);
|
|
1430
|
+
lines.push(`}`);
|
|
1431
|
+
lines.push("");
|
|
1432
|
+
lines.push(`async function executeScenario(sc, baseInfo, parsedAuth, timeoutMs) {`);
|
|
1433
|
+
lines.push(` const targetUrl = new URL(baseInfo.safeBaseUrl + sc.requestPath);`);
|
|
1434
|
+
lines.push(' if (targetUrl.origin !== baseInfo.baseOrigin || (baseInfo.basePrefix !== "/" && targetUrl.pathname !== baseInfo.baseExact && !targetUrl.pathname.startsWith(baseInfo.basePrefix))) {');
|
|
1435
|
+
lines.push(' throw new Error("Resolved request URL escapes configured API_BASE_URL base path.");');
|
|
1436
|
+
lines.push(" }");
|
|
1437
|
+
lines.push(` const init = {`);
|
|
1438
|
+
lines.push(` method: sc.method,`);
|
|
1439
|
+
lines.push(` headers: buildHeaders(sc.headers, parsedAuth),`);
|
|
1440
|
+
lines.push(` signal: AbortSignal.timeout(timeoutMs)`);
|
|
1441
|
+
lines.push(` };`);
|
|
1442
|
+
lines.push(` if (sc.body !== null && sc.method !== "GET" && sc.method !== "HEAD") {`);
|
|
1443
|
+
lines.push(` init.body = sc.body;`);
|
|
1444
|
+
lines.push(` }`);
|
|
1445
|
+
lines.push(` const t0 = performance.now();`);
|
|
1446
|
+
lines.push(` let res;`);
|
|
1447
|
+
lines.push(` let rawText = "";`);
|
|
1448
|
+
lines.push(` try {`);
|
|
1449
|
+
lines.push(` res = await fetch(targetUrl.toString(), init);`);
|
|
1450
|
+
lines.push(` rawText = await res.text();`);
|
|
1451
|
+
lines.push(` } catch (err) {`);
|
|
1452
|
+
lines.push(` const durationMs = performance.now() - t0;`);
|
|
1453
|
+
lines.push(` return { ok: false, durationMs, error: sc.id + ": request error: " + (err && err.message ? err.message : String(err)) };`);
|
|
1454
|
+
lines.push(` }`);
|
|
1455
|
+
lines.push(` const durationMs = performance.now() - t0;`);
|
|
1456
|
+
lines.push(` const errors = [];`);
|
|
1457
|
+
lines.push(` if (sc.expectedStatuses.length > 0) {`);
|
|
1458
|
+
lines.push(` if (!sc.expectedStatuses.includes(res.status)) {`);
|
|
1459
|
+
lines.push(` errors.push("expected status " + sc.expectedStatuses.join("|") + ", got " + res.status);`);
|
|
1460
|
+
lines.push(` }`);
|
|
1461
|
+
lines.push(` } else if (res.status < 200 || res.status >= 400) {`);
|
|
1462
|
+
lines.push(` errors.push("unexpected status " + res.status);`);
|
|
1463
|
+
lines.push(` }`);
|
|
1464
|
+
lines.push(` for (const [hName, hVal] of sc.expectedHeaders) {`);
|
|
1465
|
+
lines.push(` const actual = res.headers.get(hName);`);
|
|
1466
|
+
lines.push(` if (typeof actual !== "string" || !actual.toLowerCase().includes(hVal.toLowerCase())) {`);
|
|
1467
|
+
lines.push(` errors.push("header " + hName + " mismatch");`);
|
|
1468
|
+
lines.push(` }`);
|
|
1469
|
+
lines.push(` }`);
|
|
1470
|
+
lines.push(` if (sc.bodyExact !== null && rawText !== sc.bodyExact) {`);
|
|
1471
|
+
lines.push(` errors.push("bodyExact mismatch");`);
|
|
1472
|
+
lines.push(` }`);
|
|
1473
|
+
lines.push(` for (const needle of sc.bodyContains) {`);
|
|
1474
|
+
lines.push(` if (!rawText.includes(needle)) {`);
|
|
1475
|
+
lines.push(` errors.push("body missing substring: " + needle);`);
|
|
1476
|
+
lines.push(` }`);
|
|
1477
|
+
lines.push(` }`);
|
|
1478
|
+
lines.push(` const needsJson = sc.hasJsonSubset || sc.jsonSchema !== null || sc.jsonPaths.length > 0;`);
|
|
1479
|
+
lines.push(` if (needsJson) {`);
|
|
1480
|
+
lines.push(` let parsed;`);
|
|
1481
|
+
lines.push(` let jsonOk = true;`);
|
|
1482
|
+
lines.push(` try {`);
|
|
1483
|
+
lines.push(` parsed = JSON.parse(rawText);`);
|
|
1484
|
+
lines.push(` } catch {`);
|
|
1485
|
+
lines.push(` jsonOk = false;`);
|
|
1486
|
+
lines.push(` errors.push("invalid JSON response body");`);
|
|
1487
|
+
lines.push(` }`);
|
|
1488
|
+
lines.push(` if (jsonOk) {`);
|
|
1489
|
+
lines.push(` if (sc.hasJsonSubset && !matchesSubset(parsed, sc.jsonSubset)) {`);
|
|
1490
|
+
lines.push(` errors.push("jsonSubset mismatch");`);
|
|
1491
|
+
lines.push(` }`);
|
|
1492
|
+
lines.push(` if (sc.jsonSchema !== null && !matchesSchema(parsed, sc.jsonSchema)) {`);
|
|
1493
|
+
lines.push(` errors.push("jsonSchema mismatch");`);
|
|
1494
|
+
lines.push(` }`);
|
|
1495
|
+
lines.push(` for (const jp of sc.jsonPaths) {`);
|
|
1496
|
+
lines.push(` const q = queryJsonPath(parsed, jp.path);`);
|
|
1497
|
+
lines.push(` if (!q.found) {`);
|
|
1498
|
+
lines.push(` errors.push("jsonPath missing: " + jp.path);`);
|
|
1499
|
+
lines.push(` continue;`);
|
|
1500
|
+
lines.push(` }`);
|
|
1501
|
+
lines.push(` if (hasOwn(jp, "equals") && !matchesSubset(q.value, jp.equals)) {`);
|
|
1502
|
+
lines.push(` errors.push("jsonPath equals mismatch: " + jp.path);`);
|
|
1503
|
+
lines.push(` }`);
|
|
1504
|
+
lines.push(` if (typeof jp.matches === "string") {`);
|
|
1505
|
+
lines.push(` try {`);
|
|
1506
|
+
lines.push(` if (!new RegExp(jp.matches).test(String(q.value ?? ""))) {`);
|
|
1507
|
+
lines.push(` errors.push("jsonPath regex mismatch: " + jp.path);`);
|
|
1508
|
+
lines.push(` }`);
|
|
1509
|
+
lines.push(` } catch {`);
|
|
1510
|
+
lines.push(` errors.push("invalid jsonPath regex: " + jp.path);`);
|
|
1511
|
+
lines.push(` }`);
|
|
1512
|
+
lines.push(` }`);
|
|
1513
|
+
lines.push(` }`);
|
|
1514
|
+
lines.push(` }`);
|
|
1515
|
+
lines.push(` }`);
|
|
1516
|
+
lines.push(` if (typeof sc.maxLatencyMs === "number" && durationMs > sc.maxLatencyMs) {`);
|
|
1517
|
+
lines.push(` errors.push("latency " + durationMs.toFixed(1) + "ms exceeded " + sc.maxLatencyMs + "ms");`);
|
|
1518
|
+
lines.push(` }`);
|
|
1519
|
+
lines.push(` return { ok: errors.length === 0, durationMs, error: errors.length > 0 ? sc.id + ": " + errors.join("; ") : null };`);
|
|
1520
|
+
lines.push(`}`);
|
|
1521
|
+
lines.push("");
|
|
1522
|
+
lines.push(`async function main() {`);
|
|
1523
|
+
lines.push(` const rawBaseUrl = String(process.env.API_BASE_URL || DEFAULT_BASE_URL);`);
|
|
1524
|
+
lines.push(` const rawAuthHeader = process.env.API_AUTH_HEADER;`);
|
|
1525
|
+
lines.push(` let baseInfo;`);
|
|
1526
|
+
lines.push(` let parsedAuth;`);
|
|
1527
|
+
lines.push(` try {`);
|
|
1528
|
+
lines.push(` baseInfo = parseTargetBaseUrl(rawBaseUrl);`);
|
|
1529
|
+
lines.push(` parsedAuth = parseAuthHeader(rawAuthHeader);`);
|
|
1530
|
+
lines.push(` } catch (err) {`);
|
|
1531
|
+
lines.push(` const msg = err && err.message ? err.message : String(err);`);
|
|
1532
|
+
lines.push(` console.error(msg);`);
|
|
1533
|
+
lines.push(` process.exitCode = 1;`);
|
|
1534
|
+
lines.push(` return;`);
|
|
1535
|
+
lines.push(` }`);
|
|
1536
|
+
lines.push(` const baseUrl = baseInfo.safeBaseUrl;`);
|
|
1537
|
+
lines.push(` const vus = parsePositiveInt(process.env.LOAD_VUS, DEFAULT_VUS);`);
|
|
1538
|
+
lines.push(` const iterations = parsePositiveInt(process.env.LOAD_ITERATIONS, DEFAULT_ITERATIONS);`);
|
|
1539
|
+
lines.push(` const timeoutMs = parsePositiveInt(process.env.LOAD_TIMEOUT_MS, 15000);`);
|
|
1540
|
+
lines.push(` const latencies = [];`);
|
|
1541
|
+
lines.push(` const failures = [];`);
|
|
1542
|
+
lines.push(` let passedRequests = 0;`);
|
|
1543
|
+
lines.push(` let failedRequests = 0;`);
|
|
1544
|
+
lines.push(` let nextIteration = 0;`);
|
|
1545
|
+
lines.push(` const wallStart = performance.now();`);
|
|
1546
|
+
lines.push(` const workerCount = SCENARIOS.length === 0 ? 0 : Math.min(vus, iterations);`);
|
|
1547
|
+
lines.push(` async function worker() {`);
|
|
1548
|
+
lines.push(` while (true) {`);
|
|
1549
|
+
lines.push(` const iter = nextIteration++;`);
|
|
1550
|
+
lines.push(` if (iter >= iterations) break;`);
|
|
1551
|
+
lines.push(` for (const sc of SCENARIOS) {`);
|
|
1552
|
+
lines.push(` const outcome = await executeScenario(sc, baseInfo, parsedAuth, timeoutMs);`);
|
|
1553
|
+
lines.push(` latencies.push(outcome.durationMs);`);
|
|
1554
|
+
lines.push(` if (outcome.ok) {`);
|
|
1555
|
+
lines.push(` passedRequests += 1;`);
|
|
1556
|
+
lines.push(` } else {`);
|
|
1557
|
+
lines.push(` failedRequests += 1;`);
|
|
1558
|
+
lines.push(` if (failures.length < 20 && outcome.error) failures.push(outcome.error);`);
|
|
1559
|
+
lines.push(` }`);
|
|
1560
|
+
lines.push(` }`);
|
|
1561
|
+
lines.push(` }`);
|
|
1562
|
+
lines.push(` }`);
|
|
1563
|
+
lines.push(` await Promise.all(Array.from({ length: workerCount }, () => worker()));`);
|
|
1564
|
+
lines.push(` const wallDurationMs = Math.max(0.001, performance.now() - wallStart);`);
|
|
1565
|
+
lines.push(` latencies.sort((a, b) => a - b);`);
|
|
1566
|
+
lines.push(` const totalRequests = passedRequests + failedRequests;`);
|
|
1567
|
+
lines.push(` const avgMs = latencies.length > 0 ? latencies.reduce((acc, v) => acc + v, 0) / latencies.length : 0;`);
|
|
1568
|
+
lines.push(` const latencyMs = {`);
|
|
1569
|
+
lines.push(` min: latencies.length > 0 ? Number(latencies[0].toFixed(3)) : 0,`);
|
|
1570
|
+
lines.push(` p50: percentile(latencies, 50),`);
|
|
1571
|
+
lines.push(` p95: percentile(latencies, 95),`);
|
|
1572
|
+
lines.push(` p99: percentile(latencies, 99),`);
|
|
1573
|
+
lines.push(` max: latencies.length > 0 ? Number(latencies[latencies.length - 1].toFixed(3)) : 0,`);
|
|
1574
|
+
lines.push(` avg: Number(avgMs.toFixed(3))`);
|
|
1575
|
+
lines.push(` };`);
|
|
1576
|
+
lines.push(` const errorRate = totalRequests > 0 ? Number((failedRequests / totalRequests).toFixed(6)) : 0;`);
|
|
1577
|
+
lines.push(` const rps = Number((totalRequests / (wallDurationMs / 1000)).toFixed(2));`);
|
|
1578
|
+
lines.push(` const thresholdPassed = failedRequests === 0 && (!STRICT || latencyMs.p95 <= MAX_P95_MS);`);
|
|
1579
|
+
lines.push(` const summary = {`);
|
|
1580
|
+
lines.push(` title: SUITE_TITLE,`);
|
|
1581
|
+
lines.push(` format: "node-bench",`);
|
|
1582
|
+
lines.push(` baseUrl,`);
|
|
1583
|
+
lines.push(` strict: STRICT,`);
|
|
1584
|
+
lines.push(` vus,`);
|
|
1585
|
+
lines.push(` iterations,`);
|
|
1586
|
+
lines.push(` scenarios: SCENARIOS.length,`);
|
|
1587
|
+
lines.push(` totalRequests,`);
|
|
1588
|
+
lines.push(` passedRequests,`);
|
|
1589
|
+
lines.push(` failedRequests,`);
|
|
1590
|
+
lines.push(` errorRate,`);
|
|
1591
|
+
lines.push(` durationMs: Number(wallDurationMs.toFixed(2)),`);
|
|
1592
|
+
lines.push(` rps,`);
|
|
1593
|
+
lines.push(` latencyMs,`);
|
|
1594
|
+
lines.push(` thresholds: {`);
|
|
1595
|
+
lines.push(` maxErrorRate: 0,`);
|
|
1596
|
+
lines.push(` maxP95Ms: MAX_P95_MS,`);
|
|
1597
|
+
lines.push(` passed: thresholdPassed`);
|
|
1598
|
+
lines.push(` },`);
|
|
1599
|
+
lines.push(` failures`);
|
|
1600
|
+
lines.push(` };`);
|
|
1601
|
+
lines.push(` console.log(JSON.stringify(summary, null, 2));`);
|
|
1602
|
+
lines.push(` if (!thresholdPassed) {`);
|
|
1603
|
+
lines.push(` process.exitCode = 1;`);
|
|
1604
|
+
lines.push(` }`);
|
|
1605
|
+
lines.push(`}`);
|
|
1606
|
+
lines.push("");
|
|
1607
|
+
lines.push(`main().catch((err) => {`);
|
|
1608
|
+
lines.push(` console.error(err && err.message ? err.message : String(err));`);
|
|
1609
|
+
lines.push(` process.exitCode = 1;`);
|
|
1610
|
+
lines.push(`});`);
|
|
1611
|
+
lines.push("");
|
|
1612
|
+
return lines.join("\n");
|
|
1613
|
+
}
|
|
1614
|
+
function fileExtensionFor(format) {
|
|
1615
|
+
if (format === "k6")
|
|
1616
|
+
return ".js";
|
|
1617
|
+
if (format === "artillery")
|
|
1618
|
+
return ".yml";
|
|
1619
|
+
return ".mjs";
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Compile visible HTTP (and optional web_route) invariants into a load/performance suite
|
|
1623
|
+
* for Grafana k6, Artillery v2, or a self-contained zero-dependency Node benchmark runner.
|
|
1624
|
+
*/
|
|
1625
|
+
export function exportLoadSuite(contract, options = {}) {
|
|
1626
|
+
if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
|
|
1627
|
+
throw new VibecodeError("CONTRACT_INVALID", "exportLoadSuite requires a valid contract object with an invariants array.");
|
|
1628
|
+
}
|
|
1629
|
+
const formatRaw = options.format ?? "k6";
|
|
1630
|
+
if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
|
|
1631
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported load export format "${String(formatRaw)}". Supported formats: k6, artillery, node-bench.`);
|
|
1632
|
+
}
|
|
1633
|
+
const format = formatRaw;
|
|
1634
|
+
const strict = options.strict === true;
|
|
1635
|
+
const includeWebRoutes = options.includeWebRoutes !== false;
|
|
1636
|
+
const includeSkippedComments = options.includeSkippedComments !== false;
|
|
1637
|
+
const vus = validatePositiveInt(options.vus, "vus", DEFAULT_VUS, MAX_VUS);
|
|
1638
|
+
const durationSec = validatePositiveInt(options.durationSec, "durationSec", DEFAULT_DURATION_SEC, MAX_DURATION_SEC);
|
|
1639
|
+
const defaultIterations = Math.max(vus, DEFAULT_NODE_BENCH_ITERATIONS);
|
|
1640
|
+
const iterations = validatePositiveInt(options.iterations, "iterations", defaultIterations, MAX_ITERATIONS);
|
|
1641
|
+
const warnings = [];
|
|
1642
|
+
const baseUrl = resolveBaseUrl(contract, options, warnings);
|
|
1643
|
+
const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
|
|
1644
|
+
(isRecord(contract.target) &&
|
|
1645
|
+
typeof contract.target.name === "string" &&
|
|
1646
|
+
contract.target.name.trim()) ||
|
|
1647
|
+
DEFAULT_TITLE;
|
|
1648
|
+
const title = sanitizeSingleLine(rawTitle) || DEFAULT_TITLE;
|
|
1649
|
+
const scenarios = [];
|
|
1650
|
+
const skippedInvariants = [];
|
|
1651
|
+
for (let i = 0; i < contract.invariants.length; i++) {
|
|
1652
|
+
const inv = contract.invariants[i];
|
|
1653
|
+
if (!isRecord(inv))
|
|
1654
|
+
continue;
|
|
1655
|
+
// 100% Holdout Invisibility: holdouts never appear in scenarios, skippedInvariants, warnings, or comments.
|
|
1656
|
+
if (inv.holdout === true) {
|
|
1657
|
+
continue;
|
|
1658
|
+
}
|
|
1659
|
+
const fallbackId = `inv-${i + 1}`;
|
|
1660
|
+
const invId = sanitizeSingleLine(typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : fallbackId) ||
|
|
1661
|
+
fallbackId;
|
|
1662
|
+
const invType = typeof inv.type === "string" ? inv.type : "unknown";
|
|
1663
|
+
if (invType === "http") {
|
|
1664
|
+
const normalized = normalizeScenario(inv, "http", fallbackId, warnings);
|
|
1665
|
+
if (normalized.scenario) {
|
|
1666
|
+
scenarios.push(normalized.scenario);
|
|
1667
|
+
}
|
|
1668
|
+
else {
|
|
1669
|
+
skippedInvariants.push({
|
|
1670
|
+
id: invId,
|
|
1671
|
+
reason: normalized.skipReason || "invalid HTTP invariant"
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
continue;
|
|
1675
|
+
}
|
|
1676
|
+
if (invType === "web_route") {
|
|
1677
|
+
if (!includeWebRoutes) {
|
|
1678
|
+
skippedInvariants.push({
|
|
1679
|
+
id: invId,
|
|
1680
|
+
reason: "web_route excluded (includeWebRoutes=false)"
|
|
1681
|
+
});
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
const normalized = normalizeScenario(inv, "web_route", fallbackId, warnings);
|
|
1685
|
+
if (normalized.scenario) {
|
|
1686
|
+
scenarios.push(normalized.scenario);
|
|
1687
|
+
}
|
|
1688
|
+
else {
|
|
1689
|
+
skippedInvariants.push({
|
|
1690
|
+
id: invId,
|
|
1691
|
+
reason: normalized.skipReason || "invalid web_route invariant"
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
continue;
|
|
1695
|
+
}
|
|
1696
|
+
skippedInvariants.push({
|
|
1697
|
+
id: invId,
|
|
1698
|
+
reason: `unsupported invariant type: ${sanitizeSingleLine(invType) || "unknown"}`
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
if (scenarios.length === 0) {
|
|
1702
|
+
warnings.push("No exportable HTTP or web_route invariants found in contract.");
|
|
1703
|
+
}
|
|
1704
|
+
const { p95ThresholdMs, p99ThresholdMs } = resolveLatencyThresholds(scenarios, strict);
|
|
1705
|
+
const runConfig = {
|
|
1706
|
+
title,
|
|
1707
|
+
baseUrl,
|
|
1708
|
+
strict,
|
|
1709
|
+
vus,
|
|
1710
|
+
durationSec,
|
|
1711
|
+
iterations,
|
|
1712
|
+
explicitDuration: options.durationSec !== undefined,
|
|
1713
|
+
explicitIterations: options.iterations !== undefined,
|
|
1714
|
+
includeSkippedComments,
|
|
1715
|
+
p95ThresholdMs,
|
|
1716
|
+
p99ThresholdMs
|
|
1717
|
+
};
|
|
1718
|
+
let content;
|
|
1719
|
+
if (format === "k6") {
|
|
1720
|
+
content = emitK6Suite(scenarios, runConfig, skippedInvariants, warnings);
|
|
1721
|
+
}
|
|
1722
|
+
else if (format === "artillery") {
|
|
1723
|
+
content = emitArtillerySuite(scenarios, runConfig, skippedInvariants);
|
|
1724
|
+
}
|
|
1725
|
+
else {
|
|
1726
|
+
content = emitNodeBenchSuite(scenarios, runConfig, skippedInvariants);
|
|
1727
|
+
}
|
|
1728
|
+
return {
|
|
1729
|
+
format,
|
|
1730
|
+
content,
|
|
1731
|
+
fileExtension: fileExtensionFor(format),
|
|
1732
|
+
scenarioCount: scenarios.length,
|
|
1733
|
+
skippedInvariants,
|
|
1734
|
+
warnings
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Export and atomically write a load-testing suite to disk (temp file + rename in target directory).
|
|
1739
|
+
*/
|
|
1740
|
+
export function writeLoadSuite(contract, outPath, options = {}) {
|
|
1741
|
+
if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
|
|
1742
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeLoadSuite requires a valid non-empty outPath without NUL bytes.");
|
|
1743
|
+
}
|
|
1744
|
+
const resolvedOut = path.resolve(outPath.trim());
|
|
1745
|
+
if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
|
|
1746
|
+
throw new VibecodeError("CONTRACT_INVALID", `Cannot write load suite: "${resolvedOut}" is a directory.`, { fallbackHint: "Pass a file path rather than a directory." });
|
|
1747
|
+
}
|
|
1748
|
+
const result = exportLoadSuite(contract, options);
|
|
1749
|
+
const parentDir = path.dirname(resolvedOut);
|
|
1750
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
1751
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
1752
|
+
try {
|
|
1753
|
+
fs.writeFileSync(tmpPath, result.content, "utf8");
|
|
1754
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
1755
|
+
}
|
|
1756
|
+
catch (err) {
|
|
1757
|
+
try {
|
|
1758
|
+
if (fs.existsSync(tmpPath)) {
|
|
1759
|
+
fs.rmSync(tmpPath, { force: true });
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
catch {
|
|
1763
|
+
// ignore cleanup error
|
|
1764
|
+
}
|
|
1765
|
+
throw err;
|
|
1766
|
+
}
|
|
1767
|
+
return result;
|
|
1768
|
+
}
|
|
1769
|
+
function style(text, codes, useColor) {
|
|
1770
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* Format a concise, sanitized terminal summary for a load-suite export result.
|
|
1774
|
+
*/
|
|
1775
|
+
export function formatPrettyLoadExport(result, outPath, color) {
|
|
1776
|
+
const useColor = color === true;
|
|
1777
|
+
const lines = [];
|
|
1778
|
+
const banner = style("[LOAD EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
1779
|
+
const fmtLabel = style(`${result.format} (${result.fileExtension})`, ANSI.bold, useColor);
|
|
1780
|
+
lines.push(`${banner} ${fmtLabel}`);
|
|
1781
|
+
if (typeof outPath === "string" && outPath.trim().length > 0) {
|
|
1782
|
+
lines.push(`Output: ${sanitizeSingleLine(outPath)}`);
|
|
1783
|
+
}
|
|
1784
|
+
const totalBytes = Buffer.byteLength(result.content || "", "utf8");
|
|
1785
|
+
const scenarioLabel = result.scenarioCount === 1 ? "scenario" : "scenarios";
|
|
1786
|
+
const summaryParts = [`${result.scenarioCount} ${scenarioLabel}`];
|
|
1787
|
+
if (result.skippedInvariants.length > 0) {
|
|
1788
|
+
summaryParts.push(`${result.skippedInvariants.length} skipped`);
|
|
1789
|
+
}
|
|
1790
|
+
summaryParts.push(`${totalBytes} bytes`);
|
|
1791
|
+
lines.push(`Summary: ${summaryParts.join(", ")}`);
|
|
1792
|
+
if (result.skippedInvariants.length > 0) {
|
|
1793
|
+
lines.push("Skipped:");
|
|
1794
|
+
for (const item of result.skippedInvariants.slice(0, MAX_PRETTY_SKIPPED)) {
|
|
1795
|
+
const safeId = sanitizeSingleLine(item.id) || "unknown";
|
|
1796
|
+
const safeReason = sanitizeSingleLine(item.reason) || "skipped";
|
|
1797
|
+
lines.push(` - ${safeId}: ${style(safeReason, ANSI.dim, useColor)}`);
|
|
1798
|
+
}
|
|
1799
|
+
if (result.skippedInvariants.length > MAX_PRETTY_SKIPPED) {
|
|
1800
|
+
lines.push(` ${style(`... and ${result.skippedInvariants.length - MAX_PRETTY_SKIPPED} more`, ANSI.dim, useColor)}`);
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
if (Array.isArray(result.warnings) && result.warnings.length > 0) {
|
|
1804
|
+
lines.push("Warnings:");
|
|
1805
|
+
for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
|
|
1806
|
+
lines.push(` - ${style(sanitizeSingleLine(warning), ANSI.yellow, useColor)}`);
|
|
1807
|
+
}
|
|
1808
|
+
if (result.warnings.length > MAX_PRETTY_WARNINGS) {
|
|
1809
|
+
lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
return lines.join("\n");
|
|
1813
|
+
}
|