vibecode-anything 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,726 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { VibecodeError } from "./errors.js";
5
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
6
+ const DEFAULT_BASE_URL = "http://127.0.0.1:8080";
7
+ const MAX_BODY_DEPTH = 32;
8
+ const VALID_FORMATS = new Set(["http-file", "curl", "postman"]);
9
+ const SUPPORTED_HTTP_METHODS = new Set([
10
+ "GET",
11
+ "POST",
12
+ "PUT",
13
+ "PATCH",
14
+ "DELETE",
15
+ "HEAD",
16
+ "OPTIONS"
17
+ ]);
18
+ const MUTATING_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
19
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
20
+ const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
21
+ const EXTRA_SENSITIVE_HEADER_RE = /^(?:api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|x[_-]csrf[_-]token|x[_-]xsrf[_-]token|csrf[_-]token|xsrf[_-]token|authorization|proxy[_-]authorization|cookie|set[_-]cookie)$/i;
22
+ const EXTRA_SENSITIVE_QUERY_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|secret|client[_-]?secret|password|passwd|passphrase|auth|jwt|session[_-]?id|sig|signature|private[_-]?key|authorization|cookie|credential|credentials)$/i;
23
+ const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer)/i;
24
+ const AUTH_SCHEME_VALUE_RE = /^\s*(?:bearer|basic|token|digest|apikey)\s+\S+/i;
25
+ const VAULT_PATH_RE = /(?:[A-Za-z]:)?[^\s"'`<>]*\.vibecode-vault[^\s"'`<>]*/gi;
26
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
27
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s@"'`<>]+)@/g;
28
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
29
+ const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi;
30
+ const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+[A-Za-z0-9._~+/=:-]{6,}/gi;
31
+ const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9._~+/=:-]{6,}|[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*)/gi;
32
+ const HTTP_STATUS_TEXT = {
33
+ 200: "OK",
34
+ 201: "Created",
35
+ 202: "Accepted",
36
+ 204: "No Content",
37
+ 206: "Partial Content",
38
+ 301: "Moved Permanently",
39
+ 302: "Found",
40
+ 304: "Not Modified",
41
+ 307: "Temporary Redirect",
42
+ 308: "Permanent Redirect",
43
+ 400: "Bad Request",
44
+ 401: "Unauthorized",
45
+ 403: "Forbidden",
46
+ 404: "Not Found",
47
+ 405: "Method Not Allowed",
48
+ 409: "Conflict",
49
+ 410: "Gone",
50
+ 415: "Unsupported Media Type",
51
+ 422: "Unprocessable Entity",
52
+ 429: "Too Many Requests",
53
+ 500: "Internal Server Error",
54
+ 502: "Bad Gateway",
55
+ 503: "Service Unavailable",
56
+ 504: "Gateway Timeout"
57
+ };
58
+ function isRecord(value) {
59
+ return value !== null && typeof value === "object" && !Array.isArray(value);
60
+ }
61
+ function isForbiddenKey(key) {
62
+ return FORBIDDEN_KEYS.has(key);
63
+ }
64
+ function isSensitiveHeaderName(name) {
65
+ const trimmed = String(name).trim();
66
+ return isSensitiveHeader(trimmed) || EXTRA_SENSITIVE_HEADER_RE.test(trimmed);
67
+ }
68
+ function isSensitiveQueryName(name) {
69
+ const trimmed = String(name).trim();
70
+ return (isSensitiveQueryParam(trimmed) ||
71
+ EXTRA_SENSITIVE_QUERY_RE.test(trimmed) ||
72
+ isSensitiveHeaderName(trimmed));
73
+ }
74
+ function isSecretFieldName(name) {
75
+ const trimmed = String(name).trim();
76
+ return (SECRET_FIELD_NAME_RE.test(trimmed) ||
77
+ isSensitiveHeaderName(trimmed) ||
78
+ isSensitiveQueryName(trimmed));
79
+ }
80
+ function isAuthSchemeValue(value) {
81
+ return AUTH_SCHEME_VALUE_RE.test(value);
82
+ }
83
+ function redactVaultPaths(text) {
84
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
85
+ }
86
+ function sanitizeUrlInText(rawUrl) {
87
+ const withoutVault = redactVaultPaths(rawUrl);
88
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
89
+ try {
90
+ const parsed = new URL(withoutAuth);
91
+ parsed.username = "";
92
+ parsed.password = "";
93
+ const safeParams = new URLSearchParams();
94
+ for (const [k, v] of parsed.searchParams.entries()) {
95
+ const trimmedKey = k.trim();
96
+ if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
97
+ continue;
98
+ if (isAuthSchemeValue(v))
99
+ continue;
100
+ safeParams.append(k, redactVaultPaths(v));
101
+ }
102
+ const serialized = safeParams.toString();
103
+ parsed.search = serialized ? `?${serialized}` : "";
104
+ parsed.hash = "";
105
+ return parsed.toString();
106
+ }
107
+ catch {
108
+ return withoutAuth.replace(/#.*$/, "");
109
+ }
110
+ }
111
+ function sanitizeText(raw) {
112
+ const noNul = raw.replace(/\0/g, "");
113
+ const noVault = redactVaultPaths(noNul);
114
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
115
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
116
+ const noBearer = noBasicAuth.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
117
+ const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
118
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
119
+ return noScheme.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
120
+ }
121
+ function sanitizeSingleLineText(raw) {
122
+ return sanitizeText(raw)
123
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
124
+ .replace(/\s+/g, " ")
125
+ .trim();
126
+ }
127
+ function sanitizeBaseUrl(raw) {
128
+ const cleaned = raw.replace(/[\r\n\0]+/g, "").trim();
129
+ if (!cleaned || /\.vibecode-vault/i.test(cleaned))
130
+ return null;
131
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
132
+ try {
133
+ const parsed = new URL(withoutAuth);
134
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
135
+ return null;
136
+ parsed.username = "";
137
+ parsed.password = "";
138
+ parsed.search = "";
139
+ parsed.hash = "";
140
+ const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
141
+ return `${parsed.origin}${cleanPath}`;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ function resolveBaseUrl(contract, options) {
148
+ if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
149
+ const sanitized = sanitizeBaseUrl(options.baseUrl);
150
+ if (sanitized)
151
+ return sanitized;
152
+ }
153
+ if (isRecord(contract.target) && Array.isArray(contract.target.sources) && contract.target.sources.length > 0) {
154
+ const firstSource = contract.target.sources[0];
155
+ if (isRecord(firstSource)) {
156
+ if (typeof firstSource.ref === "string" && /^https?:\/\//i.test(firstSource.ref.trim())) {
157
+ const sanitized = sanitizeBaseUrl(firstSource.ref);
158
+ if (sanitized)
159
+ return sanitized;
160
+ }
161
+ if (isRecord(firstSource.meta) &&
162
+ typeof firstSource.meta.baseUrl === "string" &&
163
+ /^https?:\/\//i.test(firstSource.meta.baseUrl.trim())) {
164
+ const sanitized = sanitizeBaseUrl(firstSource.meta.baseUrl);
165
+ if (sanitized)
166
+ return sanitized;
167
+ }
168
+ }
169
+ }
170
+ return DEFAULT_BASE_URL;
171
+ }
172
+ function sanitizeJsonValue(value, depth = 0, seen = new Set()) {
173
+ if (value === null || value === undefined)
174
+ return value;
175
+ if (typeof value === "boolean")
176
+ return value;
177
+ if (typeof value === "number")
178
+ return Number.isFinite(value) ? value : null;
179
+ if (typeof value === "string") {
180
+ const trimmed = value.trim();
181
+ if (depth < MAX_BODY_DEPTH &&
182
+ ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
183
+ (trimmed.startsWith("[") && trimmed.endsWith("]")))) {
184
+ try {
185
+ const parsed = JSON.parse(trimmed);
186
+ if (parsed !== null && typeof parsed === "object") {
187
+ return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen));
188
+ }
189
+ }
190
+ catch {
191
+ // Not valid JSON; sanitize as plain text below.
192
+ }
193
+ }
194
+ return sanitizeText(value);
195
+ }
196
+ if (depth >= MAX_BODY_DEPTH)
197
+ return "[TRUNCATED]";
198
+ if (typeof value !== "object")
199
+ return undefined;
200
+ if (seen.has(value))
201
+ return "[CIRCULAR]";
202
+ seen.add(value);
203
+ try {
204
+ if (Array.isArray(value)) {
205
+ return value.map((item) => sanitizeJsonValue(item, depth + 1, seen));
206
+ }
207
+ const out = {};
208
+ for (const key of Object.keys(value)) {
209
+ if (isForbiddenKey(key))
210
+ continue;
211
+ const rawVal = value[key];
212
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
213
+ continue;
214
+ }
215
+ if (isSecretFieldName(key)) {
216
+ out[key] = "[REDACTED]";
217
+ }
218
+ else {
219
+ out[key] = sanitizeJsonValue(rawVal, depth + 1, seen);
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ finally {
225
+ seen.delete(value);
226
+ }
227
+ }
228
+ function sanitizeRequestBody(rawBody) {
229
+ if (rawBody === undefined || rawBody === null)
230
+ return undefined;
231
+ if (typeof rawBody === "string") {
232
+ if (rawBody.length === 0)
233
+ return undefined;
234
+ const trimmed = rawBody.trim();
235
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
236
+ try {
237
+ const parsed = JSON.parse(trimmed);
238
+ if (parsed !== null && typeof parsed === "object") {
239
+ const sanitized = sanitizeJsonValue(parsed);
240
+ return {
241
+ isJson: true,
242
+ compactText: JSON.stringify(sanitized),
243
+ prettyText: JSON.stringify(sanitized, null, 2)
244
+ };
245
+ }
246
+ }
247
+ catch {
248
+ // Fall through to plain text sanitization.
249
+ }
250
+ }
251
+ const cleanText = sanitizeText(rawBody);
252
+ if (cleanText.length === 0)
253
+ return undefined;
254
+ return {
255
+ isJson: false,
256
+ compactText: cleanText,
257
+ prettyText: cleanText
258
+ };
259
+ }
260
+ if (typeof rawBody === "object") {
261
+ const sanitized = sanitizeJsonValue(rawBody);
262
+ return {
263
+ isJson: true,
264
+ compactText: JSON.stringify(sanitized),
265
+ prettyText: JSON.stringify(sanitized, null, 2)
266
+ };
267
+ }
268
+ if (typeof rawBody === "boolean" || typeof rawBody === "number") {
269
+ const val = typeof rawBody === "number" && !Number.isFinite(rawBody) ? null : rawBody;
270
+ const text = JSON.stringify(val);
271
+ return {
272
+ isJson: true,
273
+ compactText: text,
274
+ prettyText: text
275
+ };
276
+ }
277
+ return undefined;
278
+ }
279
+ function sanitizePathname(rawPathname) {
280
+ const noControl = sanitizeText(rawPathname)
281
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "")
282
+ .trim();
283
+ if (!noControl)
284
+ return "/";
285
+ const encodedSpaces = noControl.replace(/\s+/g, "%20");
286
+ return encodedSpaces.startsWith("/") ? encodedSpaces : `/${encodedSpaces}`;
287
+ }
288
+ function parsePathAndInlineQuery(rawPath) {
289
+ if (typeof rawPath !== "string") {
290
+ return { pathname: "/", inlineQuery: [] };
291
+ }
292
+ const cleaned = rawPath.replace(/[\r\n\0]+/g, "").trim();
293
+ if (!cleaned) {
294
+ return { pathname: "/", inlineQuery: [] };
295
+ }
296
+ if (/^https?:\/\//i.test(cleaned)) {
297
+ const withoutAuth = cleaned.replace(URL_BASIC_AUTH_RE, "$1");
298
+ try {
299
+ const parsed = new URL(withoutAuth);
300
+ const inlineQuery = [];
301
+ for (const [k, v] of parsed.searchParams.entries()) {
302
+ inlineQuery.push([k, v]);
303
+ }
304
+ return {
305
+ pathname: sanitizePathname(parsed.pathname || "/"),
306
+ inlineQuery
307
+ };
308
+ }
309
+ catch {
310
+ const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
311
+ return splitRelativePathAndQuery(stripped);
312
+ }
313
+ }
314
+ return splitRelativePathAndQuery(cleaned);
315
+ }
316
+ function splitRelativePathAndQuery(raw) {
317
+ const hashIdx = raw.indexOf("#");
318
+ const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
319
+ const qIdx = withoutHash.indexOf("?");
320
+ const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
321
+ const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
322
+ const inlineQuery = [];
323
+ if (rawQueryPart) {
324
+ const params = new URLSearchParams(rawQueryPart);
325
+ for (const [k, v] of params.entries()) {
326
+ inlineQuery.push([k, v]);
327
+ }
328
+ }
329
+ return {
330
+ pathname: sanitizePathname(rawPathPart),
331
+ inlineQuery
332
+ };
333
+ }
334
+ function sanitizeQueryEntries(inlineQuery, structuredQuery) {
335
+ const merged = new Map();
336
+ const consider = (rawKey, rawVal) => {
337
+ const cleanKey = rawKey.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
338
+ if (!cleanKey || isForbiddenKey(cleanKey))
339
+ return;
340
+ if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
341
+ return;
342
+ const cleanVal = sanitizeText(rawVal).replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "");
343
+ if (isAuthSchemeValue(cleanVal))
344
+ return;
345
+ merged.set(cleanKey, cleanVal);
346
+ };
347
+ for (const [k, v] of inlineQuery) {
348
+ consider(k, v);
349
+ }
350
+ if (isRecord(structuredQuery)) {
351
+ for (const key of Object.keys(structuredQuery)) {
352
+ if (isForbiddenKey(key))
353
+ continue;
354
+ const val = structuredQuery[key];
355
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
356
+ if (typeof val === "number" && !Number.isFinite(val))
357
+ continue;
358
+ consider(key, String(val));
359
+ }
360
+ }
361
+ }
362
+ return [...merged.entries()];
363
+ }
364
+ function sanitizeHeaders(rawHeaders) {
365
+ if (!isRecord(rawHeaders))
366
+ return [];
367
+ const byLower = new Map();
368
+ for (const rawKey of Object.keys(rawHeaders)) {
369
+ if (isForbiddenKey(rawKey))
370
+ continue;
371
+ const cleanKey = rawKey.replace(/[\r\n\u2028\u2029\0]+/g, "").trim();
372
+ if (!cleanKey || !HEADER_NAME_TOKEN_RE.test(cleanKey))
373
+ continue;
374
+ if (isSensitiveHeaderName(cleanKey))
375
+ continue;
376
+ const rawVal = rawHeaders[rawKey];
377
+ if (rawVal === undefined || rawVal === null)
378
+ continue;
379
+ const singleLineVal = String(rawVal)
380
+ .replace(/\0/g, "")
381
+ .replace(/[\r\n\u2028\u2029]+/g, " ")
382
+ .replace(/[\x00-\x1f\x7f]+/g, " ")
383
+ .trim();
384
+ if (!singleLineVal)
385
+ continue;
386
+ if (isAuthSchemeValue(singleLineVal))
387
+ continue;
388
+ const cleanVal = sanitizeText(singleLineVal)
389
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
390
+ .trim();
391
+ if (!cleanVal)
392
+ continue;
393
+ byLower.set(cleanKey.toLowerCase(), [cleanKey, cleanVal]);
394
+ }
395
+ return [...byLower.values()];
396
+ }
397
+ function extractPrimaryStatus(rawStatus) {
398
+ const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 100 && n <= 599;
399
+ if (isValid(rawStatus))
400
+ return rawStatus;
401
+ if (Array.isArray(rawStatus)) {
402
+ for (const item of rawStatus) {
403
+ if (isValid(item))
404
+ return item;
405
+ }
406
+ }
407
+ return undefined;
408
+ }
409
+ function extractMediaType(rawContentType) {
410
+ if (typeof rawContentType !== "string")
411
+ return undefined;
412
+ const base = rawContentType
413
+ .replace(/[\r\n\0]+/g, "")
414
+ .split(";")[0]
415
+ ?.trim()
416
+ .toLowerCase();
417
+ if (!base || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(base)) {
418
+ return undefined;
419
+ }
420
+ return base;
421
+ }
422
+ function normalizeHttpInvariant(inv) {
423
+ const input = isRecord(inv.input) ? inv.input : {};
424
+ const expected = isRecord(inv.expected) ? inv.expected : {};
425
+ const methodRaw = typeof input.method === "string" && input.method.replace(/[\r\n\0]+/g, "").trim()
426
+ ? input.method.replace(/[\r\n\0]+/g, "").trim().toUpperCase()
427
+ : "GET";
428
+ if (!SUPPORTED_HTTP_METHODS.has(methodRaw)) {
429
+ return null;
430
+ }
431
+ const rawPath = typeof input.path === "string"
432
+ ? input.path
433
+ : typeof input.urlPath === "string"
434
+ ? input.urlPath
435
+ : undefined;
436
+ const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
437
+ const query = sanitizeQueryEntries(inlineQuery, input.query);
438
+ const headers = sanitizeHeaders(input.headers);
439
+ let body;
440
+ if (MUTATING_HTTP_METHODS.has(methodRaw)) {
441
+ body = sanitizeRequestBody(input.body);
442
+ if (body?.isJson) {
443
+ const hasContentType = headers.some(([k]) => k.toLowerCase() === "content-type");
444
+ if (!hasContentType) {
445
+ headers.push(["Content-Type", "application/json"]);
446
+ }
447
+ }
448
+ }
449
+ const expectedStatus = extractPrimaryStatus(expected.status);
450
+ let expectedBody;
451
+ if (expected.jsonSubset !== undefined) {
452
+ const sanitizedSubset = sanitizeJsonValue(expected.jsonSubset);
453
+ expectedBody = { isJson: true, text: JSON.stringify(sanitizedSubset) };
454
+ }
455
+ else if (typeof expected.bodyExact === "string" && expected.bodyExact.length > 0) {
456
+ const sanitizedExact = sanitizeRequestBody(expected.bodyExact);
457
+ if (sanitizedExact) {
458
+ expectedBody = { isJson: sanitizedExact.isJson, text: sanitizedExact.compactText };
459
+ }
460
+ }
461
+ let expectedContentType;
462
+ if (isRecord(expected.headers)) {
463
+ for (const [k, v] of Object.entries(expected.headers)) {
464
+ if (isForbiddenKey(k))
465
+ continue;
466
+ if (k.trim().toLowerCase() === "content-type" && typeof v === "string") {
467
+ expectedContentType = extractMediaType(v);
468
+ break;
469
+ }
470
+ }
471
+ }
472
+ if (!expectedContentType && expectedBody?.isJson) {
473
+ expectedContentType = "application/json";
474
+ }
475
+ const id = typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : "unknown";
476
+ const rawSummary = typeof inv.description === "string" && inv.description.trim()
477
+ ? sanitizeSingleLineText(inv.description)
478
+ : "";
479
+ const summary = rawSummary || `${methodRaw} ${pathname}`;
480
+ return {
481
+ id,
482
+ summary,
483
+ method: methodRaw,
484
+ pathname,
485
+ query,
486
+ headers,
487
+ ...(body ? { body } : {}),
488
+ ...(expectedStatus !== undefined ? { expectedStatus } : {}),
489
+ ...(expectedBody ? { expectedBody } : {}),
490
+ ...(expectedContentType ? { expectedContentType } : {})
491
+ };
492
+ }
493
+ function buildQueryString(query) {
494
+ if (query.length === 0)
495
+ return "";
496
+ const params = new URLSearchParams();
497
+ for (const [k, v] of query) {
498
+ params.append(k, v);
499
+ }
500
+ return params.toString();
501
+ }
502
+ function posixSingleQuote(value) {
503
+ const safe = value.replace(/\0/g, "");
504
+ return `'${safe.replace(/'/g, "'\\''")}'`;
505
+ }
506
+ function statusReasonPhrase(code) {
507
+ return HTTP_STATUS_TEXT[code] ?? `HTTP ${code}`;
508
+ }
509
+ function emitHttpFile(requests, baseUrl, title, skippedIds, includeSkippedComments) {
510
+ const lines = [];
511
+ if (includeSkippedComments) {
512
+ lines.push(`# ${title}`);
513
+ if (skippedIds.length > 0) {
514
+ const safeSkipped = skippedIds.map((id) => sanitizeSingleLineText(id) || "unknown").join(", ");
515
+ lines.push(`# Skipped non-HTTP invariants (${skippedIds.length}): ${safeSkipped}`);
516
+ }
517
+ }
518
+ lines.push(`@baseUrl = ${baseUrl}`);
519
+ for (const req of requests) {
520
+ lines.push("");
521
+ lines.push(`### ${req.summary}`);
522
+ const qs = buildQueryString(req.query);
523
+ lines.push(`${req.method} {{baseUrl}}${req.pathname}${qs ? `?${qs}` : ""}`);
524
+ for (const [key, value] of req.headers) {
525
+ lines.push(`${key}: ${value}`);
526
+ }
527
+ if (req.body) {
528
+ lines.push("");
529
+ const safeBodyText = req.body.isJson
530
+ ? req.body.prettyText
531
+ : req.body.prettyText.replace(/^([ \t]*)(#{3,})/gm, "$1\\$2");
532
+ lines.push(safeBodyText);
533
+ }
534
+ }
535
+ return `${lines.join("\n")}\n`;
536
+ }
537
+ function emitCurlCommands(requests, baseUrl, title, skippedIds, includeSkippedComments) {
538
+ const lines = [];
539
+ if (includeSkippedComments) {
540
+ lines.push(`# ${title}`);
541
+ if (skippedIds.length > 0) {
542
+ const safeSkipped = skippedIds.map((id) => sanitizeSingleLineText(id) || "unknown").join(", ");
543
+ lines.push(`# Skipped non-HTTP invariants (${skippedIds.length}): ${safeSkipped}`);
544
+ }
545
+ }
546
+ for (const req of requests) {
547
+ if (lines.length > 0) {
548
+ lines.push("");
549
+ }
550
+ if (includeSkippedComments) {
551
+ lines.push(`# ${req.summary}`);
552
+ }
553
+ const qs = buildQueryString(req.query);
554
+ const fullUrl = `${baseUrl}${req.pathname}${qs ? `?${qs}` : ""}`;
555
+ const parts = ["curl", "-X", req.method, posixSingleQuote(fullUrl)];
556
+ for (const [key, value] of req.headers) {
557
+ parts.push("-H", posixSingleQuote(`${key}: ${value}`));
558
+ }
559
+ if (req.body) {
560
+ parts.push("--data-raw", posixSingleQuote(req.body.compactText));
561
+ }
562
+ lines.push(parts.join(" "));
563
+ }
564
+ return `${lines.join("\n")}\n`;
565
+ }
566
+ function emitPostmanCollection(requests, baseUrl, title, skippedIds, includeSkippedComments) {
567
+ const info = {
568
+ name: title,
569
+ schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
570
+ };
571
+ if (includeSkippedComments && skippedIds.length > 0) {
572
+ const safeSkipped = skippedIds.map((id) => sanitizeSingleLineText(id) || "unknown").join(", ");
573
+ info.description = `Exported by vibecode-anything. Skipped non-HTTP invariants (${skippedIds.length}): ${safeSkipped}`;
574
+ }
575
+ const items = requests.map((req) => {
576
+ const qs = buildQueryString(req.query);
577
+ const rawUrl = `{{baseUrl}}${req.pathname}${qs ? `?${qs}` : ""}`;
578
+ const pathSegments = req.pathname.split("/").filter((seg) => seg.length > 0);
579
+ const requestObj = {
580
+ method: req.method,
581
+ header: req.headers.map(([key, value]) => ({ key, value })),
582
+ url: {
583
+ raw: rawUrl,
584
+ host: ["{{baseUrl}}"],
585
+ path: pathSegments,
586
+ query: req.query.map(([key, value]) => ({ key, value }))
587
+ }
588
+ };
589
+ if (req.body) {
590
+ requestObj.body = {
591
+ mode: "raw",
592
+ raw: req.body.compactText,
593
+ ...(req.body.isJson ? { options: { raw: { language: "json" } } } : {})
594
+ };
595
+ }
596
+ const responses = [];
597
+ if (req.expectedStatus !== undefined || req.expectedBody !== undefined) {
598
+ const code = req.expectedStatus ?? 200;
599
+ const respEntry = {
600
+ name: `Expected ${code}`,
601
+ code,
602
+ status: statusReasonPhrase(code)
603
+ };
604
+ if (req.expectedContentType) {
605
+ respEntry.header = [{ key: "Content-Type", value: req.expectedContentType }];
606
+ }
607
+ if (req.expectedBody) {
608
+ respEntry.body = req.expectedBody.text;
609
+ }
610
+ responses.push(respEntry);
611
+ }
612
+ return {
613
+ name: req.summary,
614
+ request: requestObj,
615
+ response: responses
616
+ };
617
+ });
618
+ const collection = {
619
+ info,
620
+ variable: [{ key: "baseUrl", value: baseUrl }],
621
+ item: items
622
+ };
623
+ return `${JSON.stringify(collection, null, 2)}\n`;
624
+ }
625
+ function suggestedFilenameFor(format) {
626
+ if (format === "http-file")
627
+ return "vibecode-requests.http";
628
+ if (format === "curl")
629
+ return "vibecode-requests.curl";
630
+ return "vibecode-postman.collection.json";
631
+ }
632
+ /**
633
+ * Export visible HTTP invariants from a ContractV02 into `.http`, cURL, or Postman Collection v2.1.0 format.
634
+ */
635
+ export function exportHttpCollection(contract, options = {}) {
636
+ if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
637
+ throw new VibecodeError("CONTRACT_INVALID", "exportHttpCollection requires a valid contract object with an invariants array.");
638
+ }
639
+ const formatRaw = options.format ?? "http-file";
640
+ if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
641
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported HTTP export format "${String(formatRaw)}". Supported formats: http-file, curl, postman.`);
642
+ }
643
+ const format = formatRaw;
644
+ const includeSkippedComments = options.includeSkippedComments !== false;
645
+ const requests = [];
646
+ const skippedIds = [];
647
+ let excludedHoldoutCount = 0;
648
+ for (const inv of contract.invariants) {
649
+ if (!isRecord(inv))
650
+ continue;
651
+ if (inv.holdout === true) {
652
+ excludedHoldoutCount += 1;
653
+ continue;
654
+ }
655
+ const invId = typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : "unknown";
656
+ if (inv.type !== "http") {
657
+ skippedIds.push(invId);
658
+ continue;
659
+ }
660
+ const normalized = normalizeHttpInvariant(inv);
661
+ if (!normalized) {
662
+ skippedIds.push(invId);
663
+ continue;
664
+ }
665
+ requests.push(normalized);
666
+ }
667
+ const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
668
+ (isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
669
+ "vibecode-http-collection";
670
+ const title = sanitizeSingleLineText(rawTitle) || "vibecode-http-collection";
671
+ const baseUrl = resolveBaseUrl(contract, options);
672
+ let content;
673
+ if (format === "http-file") {
674
+ content = emitHttpFile(requests, baseUrl, title, skippedIds, includeSkippedComments);
675
+ }
676
+ else if (format === "curl") {
677
+ content = emitCurlCommands(requests, baseUrl, title, skippedIds, includeSkippedComments);
678
+ }
679
+ else {
680
+ content = emitPostmanCollection(requests, baseUrl, title, skippedIds, includeSkippedComments);
681
+ }
682
+ return {
683
+ format,
684
+ suggestedFilename: suggestedFilenameFor(format),
685
+ content,
686
+ exportedCount: requests.length,
687
+ skippedCount: skippedIds.length,
688
+ skippedIds,
689
+ excludedHoldoutCount
690
+ };
691
+ }
692
+ /**
693
+ * Export and atomically write an HTTP collection (`.http`, `.curl`, or Postman v2.1.0 JSON) to disk.
694
+ */
695
+ export function writeHttpCollection(contract, options) {
696
+ if (!isRecord(options) ||
697
+ typeof options.outPath !== "string" ||
698
+ !options.outPath.trim() ||
699
+ options.outPath.includes("\0")) {
700
+ throw new VibecodeError("CONTRACT_INVALID", "writeHttpCollection requires a valid non-empty outPath.");
701
+ }
702
+ const result = exportHttpCollection(contract, options);
703
+ const resolvedOut = path.resolve(options.outPath.trim());
704
+ const parentDir = path.dirname(resolvedOut);
705
+ fs.mkdirSync(parentDir, { recursive: true });
706
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
707
+ try {
708
+ fs.writeFileSync(tmpPath, result.content, "utf8");
709
+ fs.renameSync(tmpPath, resolvedOut);
710
+ }
711
+ catch (err) {
712
+ try {
713
+ if (fs.existsSync(tmpPath)) {
714
+ fs.rmSync(tmpPath, { force: true });
715
+ }
716
+ }
717
+ catch {
718
+ // ignore cleanup error
719
+ }
720
+ throw err;
721
+ }
722
+ return {
723
+ ...result,
724
+ outPath: resolvedOut
725
+ };
726
+ }