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,923 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { VibecodeError, errorMessage } from "../core/errors.js";
4
+ import { validateContract } from "../core/schema.js";
5
+ import { isSensitiveHeader, isSensitiveQueryParam, mergeHeaders, redactHeaders } from "./trace.js";
6
+ const HTTP_FILE_MAX_BYTES = 5 * 1024 * 1024;
7
+ const HTTP_FILE_MAX_INVARIANTS = 50;
8
+ const MAX_JSON_SCHEMA_DEPTH = 16;
9
+ const MAX_JSON_SCHEMA_KEYS = 200;
10
+ const DEFAULT_PROBE_TIMEOUT_MS = 10000;
11
+ const MAX_BODY_CONTAINS_SNIPPET = 120;
12
+ const DETERMINISTIC_GUID = "00000000-0000-4000-8000-000000000000";
13
+ const DETERMINISTIC_TIMESTAMP = "1700000000";
14
+ const DETERMINISTIC_ISO_TIMESTAMP = "2023-11-14T22:13:20.000Z";
15
+ const SECRET_SENTINEL = "__VIBECODE_SECRET_SENTINEL__";
16
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
17
+ const EXTRA_SENSITIVE_HEADERS = new Set([
18
+ "x-csrf-token",
19
+ "x-xsrf-token",
20
+ "csrf-token"
21
+ ]);
22
+ const SECRET_VAR_NAME_RE = /secret|token|password|passwd|api[-_]?key|auth|jwt|cookie/i;
23
+ const SEPARATOR_RE = /^#{3,}(?:\s*(.*))?$/;
24
+ const NAME_DIRECTIVE_RE = /^(?:#|\/\/)\s*@name\s+(.+?)\s*$/i;
25
+ const VAR_DEF_RE = /^@([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/;
26
+ const RAW_REQUEST_LINE_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)(?:\s+HTTP\/[\d.]+)?\s*$/;
27
+ const RESOLVED_REQUEST_LINE_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(?:https?:\/\/\S+|\/\S*)(?:\s+HTTP\/[\d.]+)?\s*$/;
28
+ const TEMPLATE_REQUEST_LINE_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\{\{\s*[A-Za-z_][A-Za-z0-9_.-]*\s*\}\}\/\S*(?:\s+HTTP\/[\d.]+)?\s*$/;
29
+ const HEADER_LINE_RE = /^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)\s*:\s*(.*)$/;
30
+ const TEMPLATE_EXPR_RE = /\{\{\s*([^{}]+?)\s*\}\}/g;
31
+ const RANDOM_INT_RE = /^\$randomInt(?:\s+(-?\d+)\s+(-?\d+))?$/;
32
+ function isObject(v) {
33
+ return v !== null && typeof v === "object" && !Array.isArray(v);
34
+ }
35
+ function isHttpSensitiveHeader(name) {
36
+ const lower = name.trim().toLowerCase();
37
+ return isSensitiveHeader(lower) || EXTRA_SENSITIVE_HEADERS.has(lower);
38
+ }
39
+ function stripSensitiveHeaders(headers) {
40
+ if (!isObject(headers))
41
+ return { safe: {}, redacted: false };
42
+ const candidate = {};
43
+ let redacted = false;
44
+ for (const [rawKey, rawVal] of Object.entries(headers)) {
45
+ const key = rawKey.trim();
46
+ if (!key || rawVal === undefined || rawVal === null)
47
+ continue;
48
+ if (isHttpSensitiveHeader(key)) {
49
+ redacted = true;
50
+ continue;
51
+ }
52
+ candidate[key] = String(rawVal);
53
+ }
54
+ const safe = redactHeaders(candidate, "strip");
55
+ if (Object.keys(safe).length < Object.keys(candidate).length) {
56
+ redacted = true;
57
+ }
58
+ return { safe, redacted };
59
+ }
60
+ function setHeaderCaseInsensitive(headers, name, value) {
61
+ const lower = name.toLowerCase();
62
+ for (const existingKey of Object.keys(headers)) {
63
+ if (existingKey.toLowerCase() === lower && existingKey !== name) {
64
+ delete headers[existingKey];
65
+ }
66
+ }
67
+ headers[name] = value;
68
+ }
69
+ function deleteHeaderCaseInsensitive(headers, name) {
70
+ const lower = name.toLowerCase();
71
+ for (const existingKey of Object.keys(headers)) {
72
+ if (existingKey.toLowerCase() === lower) {
73
+ delete headers[existingKey];
74
+ }
75
+ }
76
+ }
77
+ function getHeaderCaseInsensitive(headers, name) {
78
+ const lower = name.toLowerCase();
79
+ for (const [k, v] of Object.entries(headers)) {
80
+ if (k.toLowerCase() === lower)
81
+ return v;
82
+ }
83
+ return undefined;
84
+ }
85
+ function hasHeaderCaseInsensitive(headers, name) {
86
+ return getHeaderCaseInsensitive(headers, name) !== undefined;
87
+ }
88
+ function stripBom(rawText) {
89
+ return rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
90
+ }
91
+ function resolveBuiltinVariable(expr) {
92
+ if (expr === "$guid" || expr === "$uuid")
93
+ return DETERMINISTIC_GUID;
94
+ if (expr === "$timestamp")
95
+ return DETERMINISTIC_TIMESTAMP;
96
+ if (expr === "$isoTimestamp")
97
+ return DETERMINISTIC_ISO_TIMESTAMP;
98
+ const randMatch = RANDOM_INT_RE.exec(expr);
99
+ if (randMatch) {
100
+ return randMatch[1] ?? "1";
101
+ }
102
+ return undefined;
103
+ }
104
+ function interpolateTemplate(template, rawVars, secretVars, mode, secretPlaceholder) {
105
+ let usedSecret = false;
106
+ const value = template.replace(TEMPLATE_EXPR_RE, (full, rawExpr) => {
107
+ const expr = rawExpr.trim();
108
+ const builtin = resolveBuiltinVariable(expr);
109
+ if (builtin !== undefined)
110
+ return builtin;
111
+ if (rawVars.has(expr)) {
112
+ if (secretVars.has(expr)) {
113
+ usedSecret = true;
114
+ return mode === "raw" ? (rawVars.get(expr) ?? "") : secretPlaceholder;
115
+ }
116
+ return rawVars.get(expr) ?? "";
117
+ }
118
+ return full;
119
+ });
120
+ return { value, usedSecret };
121
+ }
122
+ function resolveOriginFromHost(rawHost) {
123
+ const host = rawHost.trim().replace(/\/+$/, "");
124
+ if (!host)
125
+ return "";
126
+ if (/^https?:\/\//i.test(host))
127
+ return host;
128
+ const hostWithoutPort = host.startsWith("[")
129
+ ? host.slice(0, host.indexOf("]") + 1).toLowerCase()
130
+ : host.split(":")[0].toLowerCase();
131
+ const isLocal = hostWithoutPort === "localhost" ||
132
+ hostWithoutPort === "127.0.0.1" ||
133
+ hostWithoutPort === "[::1]" ||
134
+ hostWithoutPort === "::1";
135
+ const formattedHost = hostWithoutPort === "::1" && !host.startsWith("[") ? `[${host}]` : host;
136
+ return `${isLocal ? "http" : "https"}://${formattedHost}`;
137
+ }
138
+ function resolveRelativeWithBase(baseStr, relTarget) {
139
+ try {
140
+ const normalizedBase = /^https?:\/\//i.test(baseStr.trim()) ? baseStr.trim() : `http://${baseStr.trim()}`;
141
+ const baseObj = new URL(normalizedBase);
142
+ if (baseObj.protocol !== "http:" && baseObj.protocol !== "https:")
143
+ return null;
144
+ const relObj = new URL(relTarget, "http://placeholder.invalid");
145
+ const basePath = baseObj.pathname.replace(/\/+$/, "");
146
+ const relPath = relObj.pathname.startsWith("/") ? relObj.pathname : `/${relObj.pathname}`;
147
+ const out = new URL(baseObj.origin);
148
+ out.username = baseObj.username;
149
+ out.password = baseObj.password;
150
+ out.pathname = `${basePath}${relPath}` || "/";
151
+ out.search = relObj.search;
152
+ return out;
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
158
+ function parseTargetUrl(target, hostHeader, baseUrlOption) {
159
+ const trimmed = target.trim();
160
+ if (/^https?:\/\//i.test(trimmed)) {
161
+ try {
162
+ const parsed = new URL(trimmed);
163
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
164
+ return null;
165
+ return { url: parsed, resolvedFromBaseUrl: false };
166
+ }
167
+ catch {
168
+ return null;
169
+ }
170
+ }
171
+ if (trimmed.startsWith("/")) {
172
+ if (hostHeader && hostHeader.trim()) {
173
+ const origin = resolveOriginFromHost(hostHeader);
174
+ const parsed = origin ? resolveRelativeWithBase(origin, trimmed) : null;
175
+ if (parsed)
176
+ return { url: parsed, resolvedFromBaseUrl: false };
177
+ }
178
+ if (baseUrlOption && baseUrlOption.trim()) {
179
+ const parsed = resolveRelativeWithBase(baseUrlOption, trimmed);
180
+ if (parsed)
181
+ return { url: parsed, resolvedFromBaseUrl: true };
182
+ }
183
+ const parsed = resolveRelativeWithBase("http://localhost", trimmed);
184
+ if (parsed)
185
+ return { url: parsed, resolvedFromBaseUrl: false };
186
+ }
187
+ return null;
188
+ }
189
+ function isCommentLine(trimmed) {
190
+ return trimmed.startsWith("#") || trimmed.startsWith("//");
191
+ }
192
+ function parseBodyValue(bodyText, contentType) {
193
+ const trimmed = bodyText.trim();
194
+ if (!trimmed)
195
+ return undefined;
196
+ const looksJson = (typeof contentType === "string" && contentType.toLowerCase().includes("json")) ||
197
+ trimmed.startsWith("{") ||
198
+ trimmed.startsWith("[");
199
+ if (looksJson) {
200
+ try {
201
+ return JSON.parse(trimmed);
202
+ }
203
+ catch {
204
+ return bodyText;
205
+ }
206
+ }
207
+ return bodyText;
208
+ }
209
+ function extractBlocks(rawText) {
210
+ const text = stripBom(rawText);
211
+ const lines = text.split(/\r?\n/);
212
+ const rawVars = new Map();
213
+ const secretVars = new Set();
214
+ const secretValues = new Set();
215
+ let fileHasSecretVars = false;
216
+ const blocks = [];
217
+ let state = "preamble";
218
+ let pendingName;
219
+ let current = null;
220
+ const flushCurrent = () => {
221
+ if (current) {
222
+ blocks.push(current);
223
+ current = null;
224
+ }
225
+ state = "preamble";
226
+ pendingName = undefined;
227
+ };
228
+ for (const line of lines) {
229
+ const trimmed = line.trim();
230
+ // `### [optional name]` always delimits request blocks
231
+ const sepMatch = SEPARATOR_RE.exec(trimmed);
232
+ if (sepMatch) {
233
+ flushCurrent();
234
+ const title = (sepMatch[1] || "").trim();
235
+ pendingName = title || undefined;
236
+ continue;
237
+ }
238
+ if (state === "preamble") {
239
+ if (!trimmed)
240
+ continue;
241
+ const nameMatch = NAME_DIRECTIVE_RE.exec(trimmed);
242
+ if (nameMatch) {
243
+ const candidateName = nameMatch[1].trim();
244
+ if (candidateName)
245
+ pendingName = candidateName;
246
+ continue;
247
+ }
248
+ if (isCommentLine(trimmed))
249
+ continue;
250
+ const varMatch = VAR_DEF_RE.exec(trimmed);
251
+ if (varMatch) {
252
+ const varName = varMatch[1];
253
+ const rawRhs = varMatch[2].trim();
254
+ const expanded = interpolateTemplate(rawRhs, rawVars, secretVars, "raw", "");
255
+ const isSecret = SECRET_VAR_NAME_RE.test(varName) || expanded.usedSecret;
256
+ rawVars.set(varName, expanded.value);
257
+ if (isSecret) {
258
+ secretVars.add(varName);
259
+ fileHasSecretVars = true;
260
+ recordSecretValue(secretValues, expanded.value);
261
+ }
262
+ continue;
263
+ }
264
+ const reqMatch = RAW_REQUEST_LINE_RE.exec(trimmed);
265
+ if (reqMatch) {
266
+ current = {
267
+ ...(pendingName ? { name: pendingName } : {}),
268
+ method: reqMatch[1].toUpperCase(),
269
+ target: reqMatch[2],
270
+ headers: [],
271
+ bodyLines: [],
272
+ rawVarsSnapshot: new Map(rawVars),
273
+ secretVarsSnapshot: new Set(secretVars)
274
+ };
275
+ pendingName = undefined;
276
+ state = "headers";
277
+ }
278
+ continue;
279
+ }
280
+ if (state === "headers" && current) {
281
+ if (!trimmed) {
282
+ state = "body";
283
+ continue;
284
+ }
285
+ if (isCommentLine(trimmed))
286
+ continue;
287
+ // Multi-line query continuations (`?k=v` or `&k=v`) before any headers
288
+ if (current.headers.length === 0 && (trimmed.startsWith("?") || trimmed.startsWith("&"))) {
289
+ current.target += trimmed;
290
+ continue;
291
+ }
292
+ const headerMatch = HEADER_LINE_RE.exec(line);
293
+ if (headerMatch) {
294
+ current.headers.push({
295
+ name: headerMatch[1].trim(),
296
+ value: headerMatch[2].trim()
297
+ });
298
+ }
299
+ continue;
300
+ }
301
+ if (state === "body" && current) {
302
+ // Allow consecutive simple requests separated by blank lines without `###`
303
+ if (current.bodyLines.every((l) => !l.trim())) {
304
+ const nextReqMatch = RAW_REQUEST_LINE_RE.exec(trimmed);
305
+ if (nextReqMatch) {
306
+ const expandedNext = interpolateTemplate(trimmed, rawVars, secretVars, "raw", "").value;
307
+ if (RESOLVED_REQUEST_LINE_RE.test(expandedNext) || TEMPLATE_REQUEST_LINE_RE.test(trimmed)) {
308
+ flushCurrent();
309
+ current = {
310
+ method: nextReqMatch[1].toUpperCase(),
311
+ target: nextReqMatch[2],
312
+ headers: [],
313
+ bodyLines: [],
314
+ rawVarsSnapshot: new Map(rawVars),
315
+ secretVarsSnapshot: new Set(secretVars)
316
+ };
317
+ state = "headers";
318
+ continue;
319
+ }
320
+ }
321
+ }
322
+ current.bodyLines.push(line);
323
+ }
324
+ }
325
+ flushCurrent();
326
+ return { blocks, fileHasSecretVars, secretValues };
327
+ }
328
+ function buildParsedRequest(block, baseUrlOption, secretValues) {
329
+ let redactedSecrets = false;
330
+ const rawHeaders = {};
331
+ const safeHeaders = {};
332
+ let rawHostHeader;
333
+ let safeHostHeader;
334
+ for (const h of block.headers) {
335
+ const rawInterp = interpolateTemplate(h.value, block.rawVarsSnapshot, block.secretVarsSnapshot, "raw", "");
336
+ const safeInterp = interpolateTemplate(h.value, block.rawVarsSnapshot, block.secretVarsSnapshot, "safe", SECRET_SENTINEL);
337
+ if (rawInterp.usedSecret || safeInterp.usedSecret) {
338
+ redactedSecrets = true;
339
+ }
340
+ if (rawInterp.value !== "") {
341
+ setHeaderCaseInsensitive(rawHeaders, h.name, rawInterp.value);
342
+ }
343
+ const isSensitive = isHttpSensitiveHeader(h.name);
344
+ if (isSensitive) {
345
+ redactedSecrets = true;
346
+ recordSecretValue(secretValues, rawInterp.value);
347
+ continue;
348
+ }
349
+ if (h.name.toLowerCase() === "host") {
350
+ rawHostHeader = rawInterp.value;
351
+ safeHostHeader = safeInterp.usedSecret ? "redacted.invalid" : safeInterp.value;
352
+ }
353
+ if (safeInterp.usedSecret || safeInterp.value.includes(SECRET_SENTINEL)) {
354
+ redactedSecrets = true;
355
+ continue;
356
+ }
357
+ if (safeInterp.value !== "") {
358
+ setHeaderCaseInsensitive(safeHeaders, h.name, safeInterp.value);
359
+ }
360
+ }
361
+ const rawTargetInterp = interpolateTemplate(block.target, block.rawVarsSnapshot, block.secretVarsSnapshot, "raw", "");
362
+ const safeTargetInterp = interpolateTemplate(block.target, block.rawVarsSnapshot, block.secretVarsSnapshot, "safe", SECRET_SENTINEL);
363
+ if (rawTargetInterp.usedSecret || safeTargetInterp.usedSecret) {
364
+ redactedSecrets = true;
365
+ }
366
+ const rawParsed = parseTargetUrl(rawTargetInterp.value, rawHostHeader, baseUrlOption);
367
+ if (!rawParsed)
368
+ return null;
369
+ const rawUrlObj = rawParsed.url;
370
+ let safeParsed = parseTargetUrl(safeTargetInterp.value, safeHostHeader, baseUrlOption);
371
+ if (!safeParsed) {
372
+ // Fallback if a secret variable was placed in the host/scheme portion
373
+ const sanitizedFallbackTarget = safeTargetInterp.value.replaceAll(SECRET_SENTINEL, "redacted.invalid");
374
+ safeParsed =
375
+ parseTargetUrl(sanitizedFallbackTarget, safeHostHeader, baseUrlOption) ??
376
+ parseTargetUrl(rawUrlObj.pathname + rawUrlObj.search, "redacted.invalid", undefined);
377
+ redactedSecrets = true;
378
+ }
379
+ if (!safeParsed)
380
+ return null;
381
+ const safeUrlObj = safeParsed.url;
382
+ // Strip URL userinfo (`https://user:pass@host`) and convert to ephemeral Basic auth for live probing ONLY
383
+ let urlUserinfoAuth = null;
384
+ if (rawUrlObj.username || rawUrlObj.password) {
385
+ redactedSecrets = true;
386
+ try {
387
+ const decUser = decodeURIComponent(rawUrlObj.username);
388
+ const decPass = decodeURIComponent(rawUrlObj.password);
389
+ urlUserinfoAuth = `${decUser}:${decPass}`;
390
+ if (decUser)
391
+ secretValues.add(decUser);
392
+ if (decPass)
393
+ secretValues.add(decPass);
394
+ }
395
+ catch {
396
+ urlUserinfoAuth = `${rawUrlObj.username}:${rawUrlObj.password}`;
397
+ }
398
+ rawUrlObj.username = "";
399
+ rawUrlObj.password = "";
400
+ }
401
+ if (safeUrlObj.username || safeUrlObj.password) {
402
+ redactedSecrets = true;
403
+ safeUrlObj.username = "";
404
+ safeUrlObj.password = "";
405
+ }
406
+ // Build ephemeral probe headers
407
+ const probeHeaders = { ...rawHeaders };
408
+ if (urlUserinfoAuth !== null && !hasHeaderCaseInsensitive(probeHeaders, "authorization")) {
409
+ const encoded = Buffer.from(urlUserinfoAuth, "utf8").toString("base64");
410
+ setHeaderCaseInsensitive(probeHeaders, "Authorization", `Basic ${encoded}`);
411
+ }
412
+ // Final pass through stripSensitiveHeaders for persisted headers
413
+ const { safe: finalSafeHeaders, redacted: extraRedacted } = stripSensitiveHeaders(safeHeaders);
414
+ if (extraRedacted)
415
+ redactedSecrets = true;
416
+ // Sanitize path (replace any secret sentinel with REDACTED)
417
+ const rawPathname = rawUrlObj.pathname || "/";
418
+ let safePathname = safeUrlObj.pathname || "/";
419
+ if (safePathname.includes(SECRET_SENTINEL)) {
420
+ safePathname = safePathname.replaceAll(SECRET_SENTINEL, "REDACTED");
421
+ redactedSecrets = true;
422
+ }
423
+ // Collect raw query params (ephemeral probe) and sanitized query params (persisted)
424
+ const probeQuery = [];
425
+ for (const [k, v] of rawUrlObj.searchParams.entries()) {
426
+ probeQuery.push([k, v]);
427
+ if (isSensitiveQueryParam(k) && v.length > 0) {
428
+ secretValues.add(v);
429
+ }
430
+ }
431
+ const safeSearchParams = new URLSearchParams();
432
+ const safeQuery = {};
433
+ for (const [k, v] of safeUrlObj.searchParams.entries()) {
434
+ const trimmedKey = k.trim();
435
+ if (!trimmedKey)
436
+ continue;
437
+ if (isSensitiveQueryParam(trimmedKey) || k.includes(SECRET_SENTINEL) || v.includes(SECRET_SENTINEL)) {
438
+ redactedSecrets = true;
439
+ continue;
440
+ }
441
+ safeSearchParams.append(k, v);
442
+ safeQuery[k] = v;
443
+ }
444
+ // Trim trailing blank lines from body; ignore bodies containing only comments/whitespace
445
+ const trimmedBodyLines = block.bodyLines.slice();
446
+ while (trimmedBodyLines.length > 0 && trimmedBodyLines[0].trim() === "") {
447
+ trimmedBodyLines.shift();
448
+ }
449
+ while (trimmedBodyLines.length > 0 && trimmedBodyLines[trimmedBodyLines.length - 1].trim() === "") {
450
+ trimmedBodyLines.pop();
451
+ }
452
+ const hasRealBodyContent = trimmedBodyLines.some((l) => {
453
+ const t = l.trim();
454
+ return t.length > 0 && !isCommentLine(t);
455
+ });
456
+ let safeBody = undefined;
457
+ let probeBody = undefined;
458
+ if (hasRealBodyContent) {
459
+ const joinedBody = trimmedBodyLines.join("\n");
460
+ const contentType = getHeaderCaseInsensitive(rawHeaders, "content-type");
461
+ const rawBodyInterp = interpolateTemplate(joinedBody, block.rawVarsSnapshot, block.secretVarsSnapshot, "raw", "");
462
+ const safeBodyInterp = interpolateTemplate(joinedBody, block.rawVarsSnapshot, block.secretVarsSnapshot, "safe", "[REDACTED]");
463
+ if (rawBodyInterp.usedSecret || safeBodyInterp.usedSecret) {
464
+ redactedSecrets = true;
465
+ }
466
+ probeBody = parseBodyValue(rawBodyInterp.value, contentType);
467
+ safeBody = parseBodyValue(safeBodyInterp.value, contentType);
468
+ }
469
+ const safeOrigin = safeUrlObj.origin;
470
+ const safeSearchStr = safeSearchParams.toString();
471
+ const sanitizedUrl = `${safeOrigin}${safePathname}${safeSearchStr ? `?${safeSearchStr}` : ""}`;
472
+ const rawSearchStr = rawUrlObj.searchParams.toString();
473
+ const probeUrl = `${rawUrlObj.origin}${rawPathname}${rawSearchStr ? `?${rawSearchStr}` : ""}`;
474
+ const request = {
475
+ ...(block.name ? { name: block.name } : {}),
476
+ method: block.method,
477
+ url: sanitizedUrl,
478
+ origin: safeOrigin,
479
+ path: safePathname,
480
+ query: safeQuery,
481
+ headers: finalSafeHeaders,
482
+ ...(safeBody !== undefined ? { body: safeBody } : {}),
483
+ redactedSecrets
484
+ };
485
+ return {
486
+ request,
487
+ probeUrl,
488
+ probePath: rawPathname,
489
+ probeQuery,
490
+ probeHeaders,
491
+ probeBody,
492
+ resolvedFromBaseUrl: rawParsed.resolvedFromBaseUrl
493
+ };
494
+ }
495
+ function parseHttpFileInternal(text, options) {
496
+ if (typeof text !== "string" || !text.trim()) {
497
+ return { entries: [], redactedSecrets: false, secretValues: new Set() };
498
+ }
499
+ const baseUrlOption = typeof options?.baseUrl === "string" && options.baseUrl.trim() ? options.baseUrl.trim() : undefined;
500
+ const { blocks, fileHasSecretVars, secretValues } = extractBlocks(text);
501
+ const entries = [];
502
+ let redactedSecrets = fileHasSecretVars;
503
+ for (const block of blocks) {
504
+ const parsed = buildParsedRequest(block, baseUrlOption, secretValues);
505
+ if (!parsed)
506
+ continue;
507
+ if (parsed.request.redactedSecrets)
508
+ redactedSecrets = true;
509
+ entries.push(parsed);
510
+ }
511
+ return { entries, redactedSecrets, secretValues };
512
+ }
513
+ export function isHttpFileText(text) {
514
+ if (typeof text !== "string" || !text.trim())
515
+ return false;
516
+ const normalized = stripBom(text);
517
+ const lines = normalized.split(/\r?\n/);
518
+ // Reject shell scripts with shebang
519
+ if (lines[0]?.trimStart().startsWith("#!"))
520
+ return false;
521
+ const vars = new Map();
522
+ const emptySecrets = new Set();
523
+ for (const line of lines) {
524
+ const trimmed = line.trim();
525
+ if (!trimmed)
526
+ continue;
527
+ if (SEPARATOR_RE.test(trimmed))
528
+ continue;
529
+ if (isCommentLine(trimmed))
530
+ continue;
531
+ const varMatch = VAR_DEF_RE.exec(trimmed);
532
+ if (varMatch) {
533
+ const expanded = interpolateTemplate(varMatch[2].trim(), vars, emptySecrets, "raw", "").value;
534
+ vars.set(varMatch[1], expanded);
535
+ continue;
536
+ }
537
+ // First non-preamble line must be an HTTP request line
538
+ const expanded = interpolateTemplate(trimmed, vars, emptySecrets, "raw", "").value;
539
+ if (RESOLVED_REQUEST_LINE_RE.test(expanded))
540
+ return true;
541
+ if (TEMPLATE_REQUEST_LINE_RE.test(trimmed))
542
+ return true;
543
+ return false;
544
+ }
545
+ return false;
546
+ }
547
+ export function parseHttpFile(text, options) {
548
+ const internal = parseHttpFileInternal(text, options);
549
+ return {
550
+ requests: internal.entries.map((e) => e.request),
551
+ redactedSecrets: internal.redactedSecrets
552
+ };
553
+ }
554
+ function synthesizeSchema(value, depth = 0) {
555
+ if (depth >= MAX_JSON_SCHEMA_DEPTH)
556
+ return {};
557
+ if (value === null)
558
+ return { type: "null" };
559
+ if (Array.isArray(value)) {
560
+ return { type: "array", items: value.length ? synthesizeSchema(value[0], depth + 1) : {} };
561
+ }
562
+ if (isObject(value)) {
563
+ const entries = Object.entries(value).slice(0, MAX_JSON_SCHEMA_KEYS);
564
+ const properties = {};
565
+ const required = [];
566
+ for (const [k, v] of entries) {
567
+ properties[k] = synthesizeSchema(v, depth + 1);
568
+ required.push(k);
569
+ }
570
+ return { type: "object", required, properties };
571
+ }
572
+ if (Number.isInteger(value))
573
+ return { type: "integer" };
574
+ return { type: typeof value };
575
+ }
576
+ async function fetchJson(url, { method = "GET", headers = {}, body, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS } = {}) {
577
+ const ctrl = new AbortController();
578
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
579
+ const upperMethod = method.toUpperCase();
580
+ const canHaveBody = upperMethod !== "GET" && upperMethod !== "HEAD";
581
+ const serializedBody = !canHaveBody || body === undefined || body === null
582
+ ? undefined
583
+ : typeof body === "string"
584
+ ? body
585
+ : JSON.stringify(body);
586
+ try {
587
+ const res = await fetch(url, {
588
+ method: upperMethod,
589
+ headers,
590
+ body: serializedBody,
591
+ signal: ctrl.signal
592
+ });
593
+ const text = await res.text();
594
+ let json = null;
595
+ try {
596
+ json = text ? JSON.parse(text) : null;
597
+ }
598
+ catch {
599
+ // ignore non-JSON body
600
+ }
601
+ const headersObj = {};
602
+ for (const [k, v] of res.headers.entries())
603
+ headersObj[k.toLowerCase()] = v;
604
+ return { status: res.status, headers: headersObj, text, json };
605
+ }
606
+ finally {
607
+ clearTimeout(t);
608
+ }
609
+ }
610
+ function buildProbeUrl(baseUrl, pathname, queryEntries) {
611
+ const normalizedBase = /^https?:\/\//i.test(baseUrl) ? baseUrl : `http://${baseUrl}`;
612
+ const baseObj = new URL(normalizedBase);
613
+ baseObj.username = "";
614
+ baseObj.password = "";
615
+ const basePath = baseObj.pathname.replace(/\/+$/, "");
616
+ const cleanPath = pathname.startsWith("/") ? pathname : `/${pathname}`;
617
+ const url = new URL(baseObj.origin);
618
+ url.pathname = `${basePath}${cleanPath}` || "/";
619
+ for (const [k, v] of queryEntries) {
620
+ url.searchParams.append(k, v);
621
+ }
622
+ return url.toString();
623
+ }
624
+ function sanitizeBaseUrl(rawBase) {
625
+ try {
626
+ const normalized = /^https?:\/\//i.test(rawBase) ? rawBase : `http://${rawBase}`;
627
+ const u = new URL(normalized);
628
+ if (u.protocol !== "http:" && u.protocol !== "https:")
629
+ return "";
630
+ const basePath = u.pathname.replace(/\/+$/, "");
631
+ return `${u.origin}${basePath}`;
632
+ }
633
+ catch {
634
+ return "";
635
+ }
636
+ }
637
+ function slugify(text, fallback = "root") {
638
+ const s = String(text || "")
639
+ .toLowerCase()
640
+ .replace(/[^a-z0-9]+/g, "-")
641
+ .replace(/^-+|-+$/g, "")
642
+ .slice(0, 64);
643
+ return s || fallback;
644
+ }
645
+ function uniqueId(base, used) {
646
+ let id = slugify(base, "inv");
647
+ if (!id.startsWith("inv-"))
648
+ id = `inv-${id}`;
649
+ if (!used.has(id)) {
650
+ used.add(id);
651
+ return id;
652
+ }
653
+ let n = 2;
654
+ while (used.has(`${id}-${n}`))
655
+ n += 1;
656
+ const out = `${id}-${n}`;
657
+ used.add(out);
658
+ return out;
659
+ }
660
+ function recordSecretValue(secretValues, raw) {
661
+ const trimmed = raw.trim();
662
+ if (!trimmed)
663
+ return;
664
+ secretValues.add(trimmed);
665
+ const schemeMatch = /^(?:Bearer|Basic|Token|Digest)\s+(.+)$/i.exec(trimmed);
666
+ if (schemeMatch && schemeMatch[1].trim().length > 0) {
667
+ secretValues.add(schemeMatch[1].trim());
668
+ }
669
+ if (trimmed.includes("=")) {
670
+ for (const part of trimmed.split(";")) {
671
+ const eqIdx = part.indexOf("=");
672
+ if (eqIdx > 0) {
673
+ const val = part.slice(eqIdx + 1).trim();
674
+ if (val.length > 0)
675
+ secretValues.add(val);
676
+ }
677
+ }
678
+ }
679
+ }
680
+ function redactKnownSecrets(text, secretValues) {
681
+ let out = text;
682
+ const sorted = [...secretValues].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
683
+ for (const secret of sorted) {
684
+ if (out.includes(secret)) {
685
+ out = out.replaceAll(secret, "[REDACTED]");
686
+ }
687
+ }
688
+ return out;
689
+ }
690
+ function extractSafeBodySnippet(text, secretValues) {
691
+ for (const line of text.split(/\r?\n/)) {
692
+ const trimmed = line.trim();
693
+ if (!trimmed)
694
+ continue;
695
+ const snippet = trimmed.slice(0, MAX_BODY_CONTAINS_SNIPPET);
696
+ for (const secret of secretValues) {
697
+ if (secret.length > 0 && snippet.includes(secret)) {
698
+ return null;
699
+ }
700
+ }
701
+ return snippet;
702
+ }
703
+ return null;
704
+ }
705
+ function validateInvariantsOrThrow(invariants) {
706
+ const contract = {
707
+ schemaVersion: "0.2.0",
708
+ target: {
709
+ name: "http-file",
710
+ domains: ["api"],
711
+ sources: [{ id: "src-1", kind: "http-file", ref: "inline", meta: {} }]
712
+ },
713
+ artifacts: { root: ".vibecode/artifacts", files: {} },
714
+ thresholds: { hardBehavioralParity: 1, softPerceptualParity: 0.85, softGateMode: "warn", defaults: {} },
715
+ invariants
716
+ };
717
+ const res = validateContract(contract);
718
+ if (!res.ok) {
719
+ const err = res.errors[0];
720
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `http-file ingestor produced invalid invariant: ${err.path} ${err.message}`, { details: res.errors });
721
+ }
722
+ }
723
+ export async function ingestHttpFile(options = {}, deps = {}) {
724
+ if (typeof options.source !== "string" || !options.source.trim()) {
725
+ throw new VibecodeError("TARGET_MISSING", "HTTP file ingestor requires --source <file.http|.rest-or-http-text>");
726
+ }
727
+ const cwd = options.cwd || process.cwd();
728
+ const rawSource = options.source;
729
+ const trimmedSource = rawSource.trim();
730
+ let rawText = "";
731
+ let isFileSource = false;
732
+ if (!/[\r\n]/.test(trimmedSource)) {
733
+ const candidatePath = path.resolve(cwd, trimmedSource);
734
+ const ext = path.extname(candidatePath).toLowerCase();
735
+ const looksLikeHttpFilePath = ext === ".http" || ext === ".rest";
736
+ let stat = null;
737
+ try {
738
+ if (fs.existsSync(candidatePath)) {
739
+ stat = fs.statSync(candidatePath);
740
+ }
741
+ }
742
+ catch {
743
+ stat = null;
744
+ }
745
+ if (stat) {
746
+ if (!stat.isFile()) {
747
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `HTTP file source is not a regular file: ${trimmedSource}`);
748
+ }
749
+ if (stat.size > HTTP_FILE_MAX_BYTES) {
750
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `HTTP file exceeds maximum size of ${HTTP_FILE_MAX_BYTES} bytes: ${trimmedSource}`);
751
+ }
752
+ isFileSource = true;
753
+ try {
754
+ rawText = fs.readFileSync(candidatePath, "utf8");
755
+ }
756
+ catch (err) {
757
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Failed to read HTTP file ${trimmedSource}: ${errorMessage(err)}`);
758
+ }
759
+ }
760
+ else if (looksLikeHttpFilePath && !isHttpFileText(rawSource)) {
761
+ throw new VibecodeError("TARGET_MISSING", `HTTP file not found: ${trimmedSource}`);
762
+ }
763
+ }
764
+ if (!isFileSource) {
765
+ if (Buffer.byteLength(rawSource, "utf8") > HTTP_FILE_MAX_BYTES) {
766
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Inline HTTP source exceeds maximum size of ${HTTP_FILE_MAX_BYTES} bytes`);
767
+ }
768
+ if (!isHttpFileText(rawSource)) {
769
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Source is neither an existing .http/.rest file nor valid HTTP request text");
770
+ }
771
+ rawText = rawSource;
772
+ }
773
+ const baseUrlOverride = typeof options.baseUrl === "string" && options.baseUrl.trim() ? options.baseUrl.trim() : "";
774
+ const parsed = parseHttpFileInternal(rawText, { baseUrl: baseUrlOverride || undefined });
775
+ if (parsed.entries.length === 0) {
776
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "No valid HTTP requests found in .http/.rest input");
777
+ }
778
+ const includeMutating = options.includeMutating === true;
779
+ const offline = options.offline === true;
780
+ const globalHeaders = isObject(options.headers) ? options.headers : undefined;
781
+ const timeoutMs = typeof deps.timeoutMs === "number" && deps.timeoutMs > 0 ? deps.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
782
+ const doFetch = deps.fetchJson || fetchJson;
783
+ // Record sensitive runtime option header values so they can never leak in diagnostics or snippets
784
+ if (globalHeaders) {
785
+ for (const [k, v] of Object.entries(globalHeaders)) {
786
+ if (isHttpSensitiveHeader(k) && typeof v === "string") {
787
+ recordSecretValue(parsed.secretValues, v);
788
+ }
789
+ }
790
+ }
791
+ const warnings = [];
792
+ const filtered = [];
793
+ let skippedMutatingCount = 0;
794
+ for (const entry of parsed.entries) {
795
+ if (!SAFE_METHODS.has(entry.request.method) && !includeMutating) {
796
+ skippedMutatingCount += 1;
797
+ continue;
798
+ }
799
+ filtered.push(entry);
800
+ }
801
+ if (skippedMutatingCount > 0) {
802
+ warnings.push({
803
+ code: "BRIDGE_FORMAT_WARNING",
804
+ message: `Skipped ${skippedMutatingCount} mutating HTTP file request(s) (POST/PUT/PATCH/DELETE); pass includeMutating: true to include them.`,
805
+ details: { skippedMutatingCount }
806
+ });
807
+ }
808
+ let selected = filtered;
809
+ if (filtered.length > HTTP_FILE_MAX_INVARIANTS) {
810
+ selected = filtered.slice(0, HTTP_FILE_MAX_INVARIANTS);
811
+ warnings.push({
812
+ code: "BRIDGE_FORMAT_WARNING",
813
+ message: `HTTP file exceeded maximum of ${HTTP_FILE_MAX_INVARIANTS} emitted invariants; remaining requests were skipped.`
814
+ });
815
+ }
816
+ const usedIds = new Set();
817
+ const invariants = [];
818
+ const firstOrigin = parsed.entries[0]?.request.origin || "";
819
+ let anyRedactedSecrets = parsed.redactedSecrets;
820
+ for (const entry of selected) {
821
+ const req = entry.request;
822
+ const probeHeaders = mergeHeaders(entry.probeHeaders, globalHeaders);
823
+ if (baseUrlOverride) {
824
+ deleteHeaderCaseInsensitive(probeHeaders, "host");
825
+ }
826
+ const { safe: persistedHeaders, redacted: mergedHeadersRedacted } = stripSensitiveHeaders(mergeHeaders(req.headers, globalHeaders));
827
+ deleteHeaderCaseInsensitive(persistedHeaders, "host");
828
+ if (mergedHeadersRedacted)
829
+ anyRedactedSecrets = true;
830
+ const probeUrl = baseUrlOverride && !entry.resolvedFromBaseUrl
831
+ ? buildProbeUrl(baseUrlOverride, entry.probePath, entry.probeQuery)
832
+ : entry.probeUrl;
833
+ let observed = null;
834
+ let probeFailed = null;
835
+ if (!offline) {
836
+ try {
837
+ observed = await doFetch(probeUrl, {
838
+ method: req.method,
839
+ headers: probeHeaders,
840
+ body: entry.probeBody,
841
+ timeoutMs
842
+ });
843
+ }
844
+ catch (err) {
845
+ probeFailed = err;
846
+ }
847
+ }
848
+ const expected = {};
849
+ if (observed) {
850
+ expected.status = observed.status;
851
+ if (observed.json !== null && (isObject(observed.json) || Array.isArray(observed.json))) {
852
+ expected.jsonSchema = synthesizeSchema(observed.json);
853
+ if (isObject(observed.json)) {
854
+ expected.jsonSubset = observed.json;
855
+ }
856
+ }
857
+ else if (observed.text.trim().length > 0) {
858
+ const snippet = extractSafeBodySnippet(observed.text, parsed.secretValues);
859
+ if (snippet) {
860
+ expected.bodyContains = [snippet];
861
+ }
862
+ }
863
+ }
864
+ else {
865
+ expected.status = 200;
866
+ if (offline) {
867
+ warnings.push({
868
+ code: "ADAPTER_DEGRADED",
869
+ message: `Offline spec-only mode: emitted ${req.method} ${req.path} without live HTTP probe.`
870
+ });
871
+ }
872
+ else {
873
+ const safeErr = redactKnownSecrets(probeFailed ? errorMessage(probeFailed) : "unknown error", parsed.secretValues);
874
+ warnings.push({
875
+ code: "ADAPTER_DEGRADED",
876
+ message: `Live probe failed for ${req.method} ${req.path}; fell back to spec-only status 200: ${safeErr}`
877
+ });
878
+ }
879
+ }
880
+ const input = {
881
+ method: req.method,
882
+ path: req.path,
883
+ ...(Object.keys(req.query).length > 0 ? { query: { ...req.query } } : {}),
884
+ ...(Object.keys(persistedHeaders).length > 0 ? { headers: persistedHeaders } : {}),
885
+ ...(req.body !== undefined ? { body: req.body } : {})
886
+ };
887
+ const methodLower = req.method.toLowerCase();
888
+ const idSeed = req.name ? `${methodLower}-${slugify(req.name)}` : `${methodLower}-${slugify(req.path)}`;
889
+ const label = req.name ? `${req.name} (${req.method} ${req.path})` : `${req.method} ${req.path}`;
890
+ invariants.push({
891
+ id: uniqueId(`inv-http-${idSeed}`, usedIds),
892
+ domain: "api",
893
+ type: "http",
894
+ severity: "hard",
895
+ description: `HTTP ${label} matches ${observed ? "observed" : "spec-only"} HTTP contract`,
896
+ tags: ["api", "http-file", methodLower],
897
+ sourceId: "src-1",
898
+ input,
899
+ expected,
900
+ tolerance: {}
901
+ });
902
+ }
903
+ validateInvariantsOrThrow(invariants);
904
+ const safeBaseUrl = (baseUrlOverride ? sanitizeBaseUrl(baseUrlOverride) : "") || firstOrigin || undefined;
905
+ return {
906
+ domain: "api",
907
+ sources: [
908
+ {
909
+ id: "src-1",
910
+ kind: "http-file",
911
+ ref: isFileSource ? trimmedSource : (safeBaseUrl || "inline"),
912
+ meta: {
913
+ ...(safeBaseUrl ? { baseUrl: safeBaseUrl } : {}),
914
+ requestCount: parsed.entries.length,
915
+ ...(anyRedactedSecrets ? { redactedSecrets: true } : {})
916
+ }
917
+ }
918
+ ],
919
+ artifacts: { root: ".vibecode/artifacts", files: {} },
920
+ invariants,
921
+ warnings
922
+ };
923
+ }