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,2706 @@
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 { splitCommand } from "./exec.js";
6
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
7
+ const VALID_FORMATS = new Set(["markdown", "html", "llms-txt"]);
8
+ const SUPPORTED_HTTP_METHODS = new Set([
9
+ "GET",
10
+ "POST",
11
+ "PUT",
12
+ "PATCH",
13
+ "DELETE",
14
+ "HEAD",
15
+ "OPTIONS"
16
+ ]);
17
+ const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
18
+ const WEB_INVARIANT_TYPES = new Set(["web_route", "web_flow", "web_network"]);
19
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
20
+ const MAX_SCHEMA_DEPTH = 12;
21
+ const MAX_BODY_DEPTH = 12;
22
+ const MAX_SCHEMA_PROPERTIES = 128;
23
+ const MAX_SCHEMA_FIELDS_TABLE = 128;
24
+ const MAX_ENUM_VALUES = 64;
25
+ const MAX_TUPLE_ITEMS = 32;
26
+ const MAX_CLI_ARGS = 64;
27
+ const MAX_WEB_STEPS = 64;
28
+ const MAX_PRETTY_WARNINGS = 10;
29
+ const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
30
+ const SAFE_PATH_PARAM_RE = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
31
+ const SENSITIVE_HEADER_RE = /(?:authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|api[_-]?key|apikey|auth[_-]?token|access[_-]?token|session[_-]?token|csrf|xsrf|secret|token|passwd|password|passphrase|credential|bearer|hmac|signature|signing[_-]?key|private[_-]?key)/i;
32
+ const SENSITIVE_QUERY_RE = /(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|secret|client[_-]?secret|password|passwd|passphrase|jwt|session[_-]?id|session|private[_-]?key|authorization|cookie|csrf|xsrf|credential|credentials|bearer|hmac|webhook[-_]?secret|(?:^|[_-])(?:auth|sig|signature)(?:$|[_-]))/i;
33
+ // Matches common secret fields and env/config secret keys without false-positiving on words like `author`.
34
+ const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|access[_-]?key|signing[_-]?key|encryption[_-]?key|master[_-]?key|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf|hmac|signature|auth(?:orization|entication|[_-]?(?:token|header|key|secret|code|pass))|(?:^|[_-])auth(?:$|[_-]))/i;
35
+ const SENSITIVE_CLI_FLAG_RE = /^--?(?:u|U|user|proxy[-_]?user|token|api[_-]?key|apikey|password|passwd|passphrase|secret|client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|session[_-]?id|csrf[_-]?token|xsrf[_-]?token|csrf|xsrf|cookie|authorization|bearer|private[_-]?key|access[_-]?key|credential|credentials|hmac|signature)(?:=.*)?$/i;
36
+ const AUTH_SCHEME_VALUE_RE = /\b(?:bearer|basic|token|digest|apikey)\s+\S+/i;
37
+ const VALID_JSON_SCHEMA_TYPES = new Set([
38
+ "string",
39
+ "number",
40
+ "integer",
41
+ "boolean",
42
+ "object",
43
+ "array",
44
+ "null"
45
+ ]);
46
+ const INLINE_JSON_SECRET_KV_RE = /(["'])([A-Za-z_][A-Za-z0-9_.-]*)\1\s*:\s*(?:(")(?:\\.|[^"\\\r\n])*"|(')(?:\\.|[^'\\\r\n])*')/g;
47
+ const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
48
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>()[\]{}]+/g;
49
+ // Greedy userinfo capture before the final `@` so multi-`@` passwords are fully stripped.
50
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
51
+ // Scheme-before-header inline redaction patterns.
52
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
53
+ const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+(?![A-Z]?[a-z]+\b)[A-Za-z0-9._~+/=-]{4,}/gi;
54
+ const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+(?![A-Z]?[a-z]+\b)[A-Za-z0-9._~+/=:-]{4,}/gi;
55
+ // RFC 7616 Digest: match multi-pair `key=value` branch BEFORE single-token fallback.
56
+ const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|(?!auth\b|mode\b|header\b)[A-Za-z0-9._~+/:-]{6,})/gi;
57
+ // Multi-pair Cookie / Set-Cookie and sensitive HTTP headers.
58
+ const INLINE_SENSITIVE_HEADER_RE = /\b(?:(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;]+(?:\s*;\s*[A-Za-z0-9_.-]+(?:=[^\s,\r\n;]+)?)*|(Authorization|Proxy-Authorization)\s*[:=]\s*(?:[A-Za-z][A-Za-z0-9_-]*\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+)|(X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token|X-Hub-Signature(?:-256)?|X-HMAC(?:-SHA256|-Signature)?|X-Webhook-(?:Signature|Secret))\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest|HMAC)\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+))/gi;
59
+ const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#]+)=([^&\s#]+)/g;
60
+ const INLINE_SENSITIVE_ENV_RE = /\b([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;`"']+)/g;
61
+ const ANSI = {
62
+ reset: "\x1b[0m",
63
+ bold: "\x1b[1m",
64
+ dim: "\x1b[2m",
65
+ green: "\x1b[32m",
66
+ yellow: "\x1b[33m",
67
+ cyan: "\x1b[36m"
68
+ };
69
+ // ============================================================================
70
+ // Core Guards & Day-1 Hardened Secret / Injection Sanitization
71
+ // ============================================================================
72
+ function isRecord(value) {
73
+ return value !== null && typeof value === "object" && !Array.isArray(value);
74
+ }
75
+ function hasOwn(obj, key) {
76
+ return Object.prototype.hasOwnProperty.call(obj, key);
77
+ }
78
+ function isForbiddenKey(key) {
79
+ return FORBIDDEN_KEYS.has(key);
80
+ }
81
+ function isSensitiveHeaderName(name) {
82
+ const trimmed = String(name).trim();
83
+ if (!trimmed)
84
+ return false;
85
+ return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
86
+ }
87
+ function isSensitiveQueryName(name) {
88
+ const trimmed = String(name).trim();
89
+ if (!trimmed)
90
+ return false;
91
+ return (isSensitiveQueryParam(trimmed) ||
92
+ SENSITIVE_QUERY_RE.test(trimmed) ||
93
+ isSensitiveHeaderName(trimmed));
94
+ }
95
+ function isSecretFieldName(name) {
96
+ const trimmed = String(name).trim();
97
+ if (!trimmed)
98
+ return false;
99
+ const segments = trimmed.split(/[.\[\]'"]+/).filter(Boolean);
100
+ for (const seg of segments.length > 0 ? segments : [trimmed]) {
101
+ if (SECRET_FIELD_NAME_RE.test(seg) ||
102
+ isSensitiveHeaderName(seg) ||
103
+ isSensitiveQueryName(seg)) {
104
+ return true;
105
+ }
106
+ }
107
+ return false;
108
+ }
109
+ function isAuthSchemeValue(value) {
110
+ return AUTH_SCHEME_VALUE_RE.test(value);
111
+ }
112
+ function redactVaultPaths(text) {
113
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
114
+ }
115
+ function stripControlChars(raw) {
116
+ return raw
117
+ .replace(/\0/g, "")
118
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
119
+ .replace(/[\u2028\u2029\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
120
+ }
121
+ function sanitizeUrlInText(rawUrl) {
122
+ const withoutVault = redactVaultPaths(rawUrl);
123
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
124
+ try {
125
+ const parsed = new URL(withoutAuth);
126
+ parsed.username = "";
127
+ parsed.password = "";
128
+ parsed.hash = "";
129
+ const safeParams = new URLSearchParams();
130
+ for (const [k, v] of parsed.searchParams.entries()) {
131
+ const trimmedKey = k.trim();
132
+ if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
133
+ continue;
134
+ if (isAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
135
+ continue;
136
+ const scrubbedVal = scrubInlineSecrets(redactVaultPaths(v));
137
+ if (scrubbedVal.includes("[REDACTED"))
138
+ continue;
139
+ safeParams.append(k, scrubbedVal);
140
+ }
141
+ const serialized = safeParams.toString();
142
+ parsed.search = serialized ? `?${serialized}` : "";
143
+ return parsed.toString();
144
+ }
145
+ catch {
146
+ const hashIdx = withoutAuth.indexOf("#");
147
+ const noHash = hashIdx >= 0 ? withoutAuth.slice(0, hashIdx) : withoutAuth;
148
+ return noHash
149
+ .replace(URL_BASIC_AUTH_RE, "$1")
150
+ .replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
151
+ }
152
+ }
153
+ function scrubInlineSecrets(text) {
154
+ // Scheme-before-header redaction ensures Digest/Bearer/Basic/Token/ApiKey payloads are scrubbed first.
155
+ const noDigest = text.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
156
+ const noBearer = noDigest.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
157
+ const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
158
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
159
+ const noSensHeader = noScheme.replace(INLINE_SENSITIVE_HEADER_RE, (_m, cookieHdr, authHdr, otherHdr) => `${cookieHdr || authHdr || otherHdr}: [REDACTED]`);
160
+ const noJsonSecret = noSensHeader.replace(INLINE_JSON_SECRET_KV_RE, (match, q1, key, dq, sq) => {
161
+ const q2 = dq ?? sq ?? '"';
162
+ return isSecretFieldName(key) ? `${q1}${key}${q1}: ${q2}[REDACTED]${q2}` : match;
163
+ });
164
+ return noJsonSecret.replace(INLINE_SENSITIVE_ENV_RE, (match, key) => isSecretFieldName(key) ? `${key}=[REDACTED]` : match);
165
+ }
166
+ function sanitizeText(raw) {
167
+ const cleaned = stripControlChars(raw);
168
+ const noVault = redactVaultPaths(cleaned);
169
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
170
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
171
+ const noSensQuery = noBasicAuth.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
172
+ return scrubInlineSecrets(noSensQuery);
173
+ }
174
+ function sanitizeSingleLineText(raw, maxLen = 240) {
175
+ const cleaned = sanitizeText(raw)
176
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
177
+ .replace(/\s+/g, " ")
178
+ .trim();
179
+ if (cleaned.length <= maxLen)
180
+ return cleaned;
181
+ return `${cleaned.slice(0, Math.max(1, maxLen - 3))}...`;
182
+ }
183
+ function sanitizeBaseUrl(raw) {
184
+ const cleaned = stripControlChars(raw).replace(/[\r\n]+/g, "").trim();
185
+ if (!cleaned || /\.vibecode-vault/i.test(cleaned))
186
+ return undefined;
187
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
188
+ try {
189
+ const parsed = new URL(withoutAuth);
190
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
191
+ return undefined;
192
+ parsed.username = "";
193
+ parsed.password = "";
194
+ parsed.search = "";
195
+ parsed.hash = "";
196
+ const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
197
+ return `${parsed.origin}${cleanPath}`;
198
+ }
199
+ catch {
200
+ return undefined;
201
+ }
202
+ }
203
+ function resolveBaseUrl(contract, options) {
204
+ if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
205
+ const sanitized = sanitizeBaseUrl(options.baseUrl);
206
+ if (sanitized)
207
+ return sanitized;
208
+ }
209
+ if (isRecord(contract.target) && Array.isArray(contract.target.sources)) {
210
+ for (const src of contract.target.sources) {
211
+ if (!isRecord(src))
212
+ continue;
213
+ if (typeof src.ref === "string" && /^https?:\/\//i.test(src.ref.trim())) {
214
+ const sanitized = sanitizeBaseUrl(src.ref);
215
+ if (sanitized)
216
+ return sanitized;
217
+ }
218
+ if (isRecord(src.meta) &&
219
+ typeof src.meta.baseUrl === "string" &&
220
+ /^https?:\/\//i.test(src.meta.baseUrl.trim())) {
221
+ const sanitized = sanitizeBaseUrl(src.meta.baseUrl);
222
+ if (sanitized)
223
+ return sanitized;
224
+ }
225
+ }
226
+ }
227
+ return undefined;
228
+ }
229
+ function escapeHtml(raw) {
230
+ return stripControlChars(String(raw))
231
+ .replace(/&/g, "&amp;")
232
+ .replace(/</g, "&lt;")
233
+ .replace(/>/g, "&gt;")
234
+ .replace(/"/g, "&quot;")
235
+ .replace(/'/g, "&#39;")
236
+ .replace(/`/g, "&#96;");
237
+ }
238
+ function escapeMarkdownCell(raw) {
239
+ return sanitizeSingleLineText(raw, 240)
240
+ .replace(/\\/g, "\\\\")
241
+ .replace(/\|/g, "\\|")
242
+ .replace(/</g, "&lt;")
243
+ .replace(/>/g, "&gt;")
244
+ .replace(/`/g, "\\`")
245
+ .replace(/!/g, "\\!")
246
+ .replace(/\[/g, "\\[")
247
+ .replace(/\]/g, "\\]");
248
+ }
249
+ function escapeMarkdownInline(raw, maxLen = 280) {
250
+ return sanitizeSingleLineText(raw, maxLen)
251
+ .replace(/</g, "&lt;")
252
+ .replace(/>/g, "&gt;")
253
+ .replace(/!/g, "\\!")
254
+ .replace(/\[/g, "\\[")
255
+ .replace(/\]/g, "\\]")
256
+ .replace(/^(#{1,6}|>+)(?=\s|$)/, (prefix) => prefix.replace(/./g, (c) => `\\${c}`));
257
+ }
258
+ function markdownCodeSpan(raw) {
259
+ const text = sanitizeSingleLineText(raw, 240);
260
+ const matches = text.match(/`+/g);
261
+ const maxRun = matches ? Math.max(...matches.map((m) => m.length)) : 0;
262
+ const delim = "`".repeat(maxRun + 1);
263
+ const needsPad = text.startsWith("`") || text.endsWith("`") || text.startsWith(" ") || text.endsWith(" ");
264
+ return needsPad ? `${delim} ${text} ${delim}` : `${delim}${text}${delim}`;
265
+ }
266
+ function markdownCodeBlock(content, lang) {
267
+ const safeContent = sanitizeText(content).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
268
+ const matches = safeContent.match(/`{3,}/g);
269
+ const maxRun = matches ? Math.max(...matches.map((m) => m.length)) : 2;
270
+ const fence = "`".repeat(Math.max(3, maxRun + 1));
271
+ const safeLang = lang.replace(/[^a-z0-9_-]/gi, "");
272
+ return `${fence}${safeLang}\n${safeContent}\n${fence}`;
273
+ }
274
+ function sanitizePathname(rawPathname) {
275
+ const noHash = rawPathname.split("#")[0] ?? "";
276
+ const noControl = sanitizeText(noHash)
277
+ .replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "")
278
+ .trim();
279
+ if (!noControl)
280
+ return "/";
281
+ const encodedSpaces = noControl.replace(/\s+/g, "%20");
282
+ const rawSegments = encodedSpaces.split("/");
283
+ const stack = [];
284
+ for (const seg of rawSegments) {
285
+ if (!seg || seg === ".")
286
+ continue;
287
+ if (seg === "..") {
288
+ if (stack.length > 0)
289
+ stack.pop();
290
+ continue;
291
+ }
292
+ stack.push(seg);
293
+ }
294
+ return stack.length === 0 ? "/" : `/${stack.join("/")}`;
295
+ }
296
+ function splitRelativePathAndQuery(raw) {
297
+ const hashIdx = raw.indexOf("#");
298
+ const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
299
+ const qIdx = withoutHash.indexOf("?");
300
+ const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
301
+ const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
302
+ const inlineQuery = [];
303
+ if (rawQueryPart) {
304
+ const params = new URLSearchParams(rawQueryPart);
305
+ for (const [k, v] of params.entries()) {
306
+ inlineQuery.push([k, v]);
307
+ }
308
+ }
309
+ return {
310
+ pathname: sanitizePathname(rawPathPart),
311
+ inlineQuery
312
+ };
313
+ }
314
+ function parsePathAndInlineQuery(rawPath) {
315
+ if (typeof rawPath !== "string") {
316
+ return { pathname: "/", inlineQuery: [] };
317
+ }
318
+ const cleaned = stripControlChars(rawPath).replace(/[\r\n]+/g, "").trim();
319
+ if (!cleaned) {
320
+ return { pathname: "/", inlineQuery: [] };
321
+ }
322
+ // Reject javascript:/data:/vbscript: schemes in paths.
323
+ if (/^(?:javascript|vbscript|data):/i.test(cleaned)) {
324
+ return { pathname: "/", inlineQuery: [] };
325
+ }
326
+ if (/^https?:\/\//i.test(cleaned)) {
327
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
328
+ try {
329
+ const parsed = new URL(withoutAuth);
330
+ const inlineQuery = [];
331
+ for (const [k, v] of parsed.searchParams.entries()) {
332
+ inlineQuery.push([k, v]);
333
+ }
334
+ return {
335
+ pathname: sanitizePathname(parsed.pathname || "/"),
336
+ inlineQuery
337
+ };
338
+ }
339
+ catch {
340
+ const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
341
+ return splitRelativePathAndQuery(stripped);
342
+ }
343
+ }
344
+ return splitRelativePathAndQuery(cleaned);
345
+ }
346
+ function extractPathParams(pathname) {
347
+ const found = new Set();
348
+ for (const segment of pathname.split("/")) {
349
+ let candidate = null;
350
+ if (segment.startsWith("{") && segment.endsWith("}") && segment.length > 2) {
351
+ candidate = segment.slice(1, -1);
352
+ }
353
+ else if (segment.startsWith(":") && segment.length > 1) {
354
+ candidate = segment.slice(1);
355
+ }
356
+ if (candidate &&
357
+ SAFE_PATH_PARAM_RE.test(candidate) &&
358
+ !isForbiddenKey(candidate) &&
359
+ !isSecretFieldName(candidate)) {
360
+ found.add(candidate);
361
+ }
362
+ }
363
+ return [...found];
364
+ }
365
+ function sanitizeQueryEntries(inlineQuery, structuredQuery) {
366
+ const merged = new Map();
367
+ const consider = (rawKey, rawVal) => {
368
+ const rawCleanKey = stripControlChars(rawKey).replace(/[\r\n]+/g, "").trim();
369
+ if (!rawCleanKey || isForbiddenKey(rawCleanKey))
370
+ return;
371
+ if (/\.vibecode-vault/i.test(rawCleanKey) || isAuthSchemeValue(rawCleanKey))
372
+ return;
373
+ const cleanKey = sanitizeText(rawCleanKey).replace(/[\r\n]+/g, "").trim();
374
+ if (!cleanKey || isForbiddenKey(cleanKey))
375
+ return;
376
+ if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey) || isAuthSchemeValue(cleanKey))
377
+ return;
378
+ if (/\.vibecode-vault/i.test(rawVal) || isAuthSchemeValue(rawVal))
379
+ return;
380
+ const cleanVal = sanitizeText(rawVal).replace(/[\r\n]+/g, "").trim();
381
+ if (isAuthSchemeValue(cleanVal))
382
+ return;
383
+ merged.set(cleanKey, cleanVal);
384
+ };
385
+ for (const [k, v] of inlineQuery) {
386
+ consider(k, v);
387
+ }
388
+ if (isRecord(structuredQuery)) {
389
+ for (const key of Object.keys(structuredQuery)) {
390
+ if (isForbiddenKey(key))
391
+ continue;
392
+ const val = structuredQuery[key];
393
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
394
+ if (typeof val === "number" && !Number.isFinite(val))
395
+ continue;
396
+ consider(key, String(val));
397
+ }
398
+ }
399
+ }
400
+ return [...merged.entries()];
401
+ }
402
+ function sanitizeHeaders(rawHeaders) {
403
+ if (!isRecord(rawHeaders))
404
+ return [];
405
+ const byLower = new Map();
406
+ for (const rawKey of Object.keys(rawHeaders)) {
407
+ if (isForbiddenKey(rawKey))
408
+ continue;
409
+ const cleanKey = stripControlChars(rawKey).replace(/[\r\n]+/g, "").trim();
410
+ if (!cleanKey || !HEADER_NAME_TOKEN_RE.test(cleanKey))
411
+ continue;
412
+ if (isSensitiveHeaderName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
413
+ continue;
414
+ const rawVal = rawHeaders[rawKey];
415
+ if (rawVal === undefined || rawVal === null)
416
+ continue;
417
+ const singleLineVal = stripControlChars(String(rawVal))
418
+ .replace(/[\r\n]+/g, " ")
419
+ .trim();
420
+ if (!singleLineVal || singleLineVal === "[REDACTED]")
421
+ continue;
422
+ if (isAuthSchemeValue(singleLineVal) || /\.vibecode-vault/i.test(singleLineVal))
423
+ continue;
424
+ const cleanVal = sanitizeSingleLineText(singleLineVal, 160);
425
+ if (!cleanVal || cleanVal === "[REDACTED]")
426
+ continue;
427
+ byLower.set(cleanKey.toLowerCase(), [cleanKey, cleanVal]);
428
+ }
429
+ return [...byLower.values()];
430
+ }
431
+ function extractExpectedStatuses(rawStatus) {
432
+ const valid = new Set();
433
+ const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 100 && n <= 599;
434
+ if (isValid(rawStatus)) {
435
+ valid.add(rawStatus);
436
+ }
437
+ else if (Array.isArray(rawStatus)) {
438
+ for (const item of rawStatus) {
439
+ if (isValid(item))
440
+ valid.add(item);
441
+ }
442
+ }
443
+ return [...valid];
444
+ }
445
+ function extractExpectedExitCodes(rawExitCode) {
446
+ const valid = new Set();
447
+ const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= 255;
448
+ if (isValid(rawExitCode)) {
449
+ valid.add(rawExitCode);
450
+ }
451
+ else if (Array.isArray(rawExitCode)) {
452
+ for (const item of rawExitCode) {
453
+ if (isValid(item))
454
+ valid.add(item);
455
+ }
456
+ }
457
+ return [...valid];
458
+ }
459
+ function sanitizeJsonValue(value, depth = 0, seen = new Set(), warnings) {
460
+ if (value === null || value === undefined)
461
+ return value;
462
+ if (typeof value === "boolean")
463
+ return value;
464
+ if (typeof value === "number")
465
+ return Number.isFinite(value) ? value : null;
466
+ if (typeof value === "string") {
467
+ const trimmed = value.trim();
468
+ if (depth < MAX_BODY_DEPTH &&
469
+ ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
470
+ (trimmed.startsWith("[") && trimmed.endsWith("]")))) {
471
+ try {
472
+ const parsed = JSON.parse(trimmed);
473
+ if (parsed !== null && typeof parsed === "object") {
474
+ return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen, warnings));
475
+ }
476
+ }
477
+ catch {
478
+ // Fall through to plain string scrubbing
479
+ }
480
+ }
481
+ return sanitizeText(value);
482
+ }
483
+ if (depth >= MAX_BODY_DEPTH) {
484
+ warnings?.push(`Payload nesting exceeded maximum depth (${MAX_BODY_DEPTH}); deeper nodes were truncated.`);
485
+ return "[truncated]";
486
+ }
487
+ if (typeof value !== "object")
488
+ return undefined;
489
+ if (seen.has(value)) {
490
+ warnings?.push("Detected circular payload reference; replaced cycle with placeholder.");
491
+ return "[circular]";
492
+ }
493
+ seen.add(value);
494
+ try {
495
+ if (Array.isArray(value)) {
496
+ return value.slice(0, MAX_TUPLE_ITEMS).map((item) => sanitizeJsonValue(item, depth + 1, seen, warnings));
497
+ }
498
+ const out = Object.create(null);
499
+ const rawObj = value;
500
+ let propCount = 0;
501
+ for (const key of Object.keys(rawObj)) {
502
+ if (isForbiddenKey(key) || isSecretFieldName(key))
503
+ continue;
504
+ if (propCount >= MAX_SCHEMA_PROPERTIES)
505
+ break;
506
+ const cleanKey = sanitizeText(key).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
507
+ if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
508
+ continue;
509
+ const rawVal = rawObj[key];
510
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
511
+ continue;
512
+ }
513
+ propCount += 1;
514
+ out[cleanKey] = sanitizeJsonValue(rawVal, depth + 1, seen, warnings);
515
+ }
516
+ return out;
517
+ }
518
+ finally {
519
+ seen.delete(value);
520
+ }
521
+ }
522
+ function refPointsToSecret(ref) {
523
+ if (!ref.startsWith("#/"))
524
+ return true;
525
+ const segments = ref
526
+ .slice(2)
527
+ .split("/")
528
+ .map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
529
+ for (const seg of segments) {
530
+ if (!seg || isForbiddenKey(seg) || isSecretFieldName(seg)) {
531
+ return true;
532
+ }
533
+ }
534
+ return false;
535
+ }
536
+ function sanitizeSchemaNode(schema, depth = 0, seen = new Set(), warnings) {
537
+ if (!isRecord(schema))
538
+ return undefined;
539
+ if (depth >= MAX_SCHEMA_DEPTH) {
540
+ warnings?.push(`Schema nesting exceeded maximum depth (${MAX_SCHEMA_DEPTH}); truncated branch.`);
541
+ return {};
542
+ }
543
+ if (seen.has(schema)) {
544
+ warnings?.push("Detected circular schema object reference; replaced cycle with empty schema.");
545
+ return {};
546
+ }
547
+ seen.add(schema);
548
+ try {
549
+ const out = {};
550
+ let propCount = 0;
551
+ for (const key of Object.keys(schema)) {
552
+ if (isForbiddenKey(key))
553
+ continue;
554
+ // Never retain raw examples or defaults in exported docs schemas.
555
+ if (key === "example" || key === "examples" || key === "default")
556
+ continue;
557
+ const val = schema[key];
558
+ if (val === undefined)
559
+ continue;
560
+ if (key === "type") {
561
+ if (typeof val === "string") {
562
+ const cleanType = sanitizeSingleLineText(val, 32).toLowerCase();
563
+ if (VALID_JSON_SCHEMA_TYPES.has(cleanType))
564
+ out.type = cleanType;
565
+ }
566
+ else if (Array.isArray(val)) {
567
+ const types = val
568
+ .filter((t) => typeof t === "string")
569
+ .map((t) => sanitizeSingleLineText(t, 32).toLowerCase())
570
+ .filter((t) => VALID_JSON_SCHEMA_TYPES.has(t));
571
+ if (types.length > 0)
572
+ out.type = types;
573
+ }
574
+ }
575
+ else if (key === "nullable" && typeof val === "boolean") {
576
+ out.nullable = val;
577
+ }
578
+ else if (key === "format" && typeof val === "string") {
579
+ const fmt = sanitizeSingleLineText(val, 64);
580
+ if (fmt)
581
+ out.format = fmt;
582
+ }
583
+ else if (key === "description" && typeof val === "string") {
584
+ const desc = sanitizeSingleLineText(val, 200);
585
+ if (desc)
586
+ out.description = desc;
587
+ }
588
+ else if (key === "title" && typeof val === "string") {
589
+ const t = sanitizeSingleLineText(val, 120);
590
+ if (t)
591
+ out.title = t;
592
+ }
593
+ else if (key === "$ref" && typeof val === "string") {
594
+ const cleanRef = sanitizeSingleLineText(val, 200);
595
+ if (cleanRef.startsWith("#/") && !refPointsToSecret(cleanRef)) {
596
+ out.$ref = cleanRef;
597
+ }
598
+ }
599
+ else if ((key === "minLength" ||
600
+ key === "maxLength" ||
601
+ key === "minItems" ||
602
+ key === "maxItems" ||
603
+ key === "minProperties" ||
604
+ key === "maxProperties") &&
605
+ typeof val === "number" &&
606
+ Number.isInteger(val) &&
607
+ val >= 0) {
608
+ out[key] = val;
609
+ }
610
+ else if ((key === "minimum" ||
611
+ key === "maximum" ||
612
+ key === "exclusiveMinimum" ||
613
+ key === "exclusiveMaximum") &&
614
+ typeof val === "number" &&
615
+ Number.isFinite(val)) {
616
+ out[key] = val;
617
+ }
618
+ else if (key === "multipleOf" && typeof val === "number" && Number.isFinite(val) && val > 0) {
619
+ out.multipleOf = val;
620
+ }
621
+ else if (key === "uniqueItems" && typeof val === "boolean") {
622
+ out.uniqueItems = val;
623
+ }
624
+ else if (key === "pattern" && typeof val === "string" && val.length <= 256 && !val.includes("\0")) {
625
+ const pat = sanitizeSingleLineText(val, 256);
626
+ if (pat && !pat.includes("[REDACTED")) {
627
+ out.pattern = pat;
628
+ }
629
+ }
630
+ else if (key === "required" && Array.isArray(val)) {
631
+ const reqs = val
632
+ .filter((item) => typeof item === "string" &&
633
+ item.length > 0 &&
634
+ !isForbiddenKey(item) &&
635
+ !isSecretFieldName(item) &&
636
+ !/\.vibecode-vault/i.test(item))
637
+ .map((item) => sanitizeSingleLineText(item, 80))
638
+ .filter((item) => item.length > 0 && !isForbiddenKey(item) && !isSecretFieldName(item));
639
+ if (reqs.length > 0)
640
+ out.required = [...new Set(reqs)];
641
+ }
642
+ else if (key === "properties" && isRecord(val)) {
643
+ const props = Object.create(null);
644
+ for (const propKey of Object.keys(val)) {
645
+ if (isForbiddenKey(propKey) || isSecretFieldName(propKey))
646
+ continue;
647
+ if (propCount >= MAX_SCHEMA_PROPERTIES)
648
+ break;
649
+ const cleanPropKey = sanitizeText(propKey).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
650
+ if (!cleanPropKey || isForbiddenKey(cleanPropKey) || isSecretFieldName(cleanPropKey)) {
651
+ continue;
652
+ }
653
+ propCount += 1;
654
+ const sanitizedProp = sanitizeSchemaNode(val[propKey], depth + 1, seen, warnings);
655
+ props[cleanPropKey] = sanitizedProp ?? {};
656
+ }
657
+ out.properties = props;
658
+ }
659
+ else if (key === "additionalProperties") {
660
+ if (typeof val === "boolean") {
661
+ out.additionalProperties = val;
662
+ }
663
+ else if (isRecord(val)) {
664
+ out.additionalProperties = sanitizeSchemaNode(val, depth + 1, seen, warnings) ?? {};
665
+ }
666
+ }
667
+ else if (key === "items") {
668
+ if (Array.isArray(val)) {
669
+ out.items = val
670
+ .slice(0, MAX_TUPLE_ITEMS)
671
+ .map((item) => sanitizeSchemaNode(item, depth + 1, seen, warnings) ?? {});
672
+ }
673
+ else if (isRecord(val)) {
674
+ out.items = sanitizeSchemaNode(val, depth + 1, seen, warnings) ?? {};
675
+ }
676
+ }
677
+ else if (key === "allOf" || key === "anyOf" || key === "oneOf") {
678
+ if (Array.isArray(val)) {
679
+ const branches = val
680
+ .map((item) => sanitizeSchemaNode(item, depth + 1, seen, warnings))
681
+ .filter((item) => item !== undefined);
682
+ if (branches.length > 0)
683
+ out[key] = branches;
684
+ }
685
+ }
686
+ else if (key === "const") {
687
+ out.const = sanitizeJsonValue(val, depth + 1, seen, warnings);
688
+ }
689
+ else if (key === "enum" && Array.isArray(val)) {
690
+ const cleanedEnum = val
691
+ .slice(0, MAX_ENUM_VALUES)
692
+ .map((item) => sanitizeJsonValue(item, depth + 1, seen, warnings))
693
+ .filter((item) => item !== undefined);
694
+ if (cleanedEnum.length > 0)
695
+ out.enum = cleanedEnum;
696
+ }
697
+ else if ((key === "$defs" || key === "definitions") && isRecord(val)) {
698
+ const defs = Object.create(null);
699
+ for (const defKey of Object.keys(val)) {
700
+ if (isForbiddenKey(defKey) || isSecretFieldName(defKey))
701
+ continue;
702
+ const cleanDefKey = sanitizeText(defKey).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
703
+ if (!cleanDefKey || isForbiddenKey(cleanDefKey) || isSecretFieldName(cleanDefKey)) {
704
+ continue;
705
+ }
706
+ const defSchema = sanitizeSchemaNode(val[defKey], depth + 1, seen, warnings);
707
+ if (defSchema)
708
+ defs[cleanDefKey] = defSchema;
709
+ }
710
+ out[key] = defs;
711
+ }
712
+ }
713
+ // Ensure `required` never references a dropped secret or forbidden property.
714
+ if (Array.isArray(out.required) && isRecord(out.properties)) {
715
+ const kept = out.required.filter((reqKey) => hasOwn(out.properties, reqKey));
716
+ if (kept.length > 0) {
717
+ out.required = kept;
718
+ }
719
+ else {
720
+ delete out.required;
721
+ }
722
+ }
723
+ return out;
724
+ }
725
+ finally {
726
+ seen.delete(schema);
727
+ }
728
+ }
729
+ function inferSchemaFromValue(value, depth = 0, seen = new Set()) {
730
+ if (depth >= MAX_SCHEMA_DEPTH)
731
+ return {};
732
+ if (value === null)
733
+ return { type: "null" };
734
+ if (typeof value === "boolean")
735
+ return { type: "boolean" };
736
+ if (typeof value === "number") {
737
+ return { type: Number.isInteger(value) ? "integer" : "number" };
738
+ }
739
+ if (typeof value === "string")
740
+ return { type: "string" };
741
+ if (typeof value !== "object")
742
+ return {};
743
+ if (seen.has(value))
744
+ return {};
745
+ seen.add(value);
746
+ try {
747
+ if (Array.isArray(value)) {
748
+ if (value.length === 0)
749
+ return { type: "array", items: {} };
750
+ return { type: "array", items: inferSchemaFromValue(value[0], depth + 1, seen) };
751
+ }
752
+ const obj = value;
753
+ const properties = Object.create(null);
754
+ const required = [];
755
+ let count = 0;
756
+ for (const key of Object.keys(obj)) {
757
+ if (isForbiddenKey(key) || isSecretFieldName(key))
758
+ continue;
759
+ if (count >= MAX_SCHEMA_PROPERTIES)
760
+ break;
761
+ const cleanKey = sanitizeText(key).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
762
+ if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
763
+ continue;
764
+ count += 1;
765
+ const val = obj[key];
766
+ properties[cleanKey] = inferSchemaFromValue(val, depth + 1, seen);
767
+ if (val !== undefined && val !== null) {
768
+ required.push(cleanKey);
769
+ }
770
+ }
771
+ return {
772
+ type: "object",
773
+ properties,
774
+ ...(required.length > 0 ? { required } : {})
775
+ };
776
+ }
777
+ finally {
778
+ seen.delete(value);
779
+ }
780
+ }
781
+ function resolveLocalRef(rootSchema, ref) {
782
+ if (!rootSchema || !ref.startsWith("#/") || refPointsToSecret(ref))
783
+ return undefined;
784
+ const parts = ref
785
+ .slice(2)
786
+ .split("/")
787
+ .map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
788
+ let current = rootSchema;
789
+ for (const part of parts) {
790
+ if (!part || isForbiddenKey(part) || isSecretFieldName(part))
791
+ return undefined;
792
+ if (!isRecord(current) || !hasOwn(current, part))
793
+ return undefined;
794
+ current = current[part];
795
+ }
796
+ return isRecord(current) ? current : undefined;
797
+ }
798
+ function describeSchemaType(schema, rootSchema, depth = 0) {
799
+ if (depth >= MAX_SCHEMA_DEPTH)
800
+ return "any";
801
+ if (typeof schema.$ref === "string") {
802
+ const refName = schema.$ref.split("/").pop() ?? "ref";
803
+ const resolved = resolveLocalRef(rootSchema, schema.$ref);
804
+ if (resolved) {
805
+ const inner = describeSchemaType(resolved, rootSchema, depth + 1);
806
+ return inner && inner !== "any" ? `${refName} (${inner})` : refName;
807
+ }
808
+ return refName;
809
+ }
810
+ if (Array.isArray(schema.type)) {
811
+ return schema.type.join(" | ");
812
+ }
813
+ if (schema.type === "array") {
814
+ if (isRecord(schema.items)) {
815
+ return `${describeSchemaType(schema.items, rootSchema, depth + 1)}[]`;
816
+ }
817
+ return "array";
818
+ }
819
+ if (typeof schema.type === "string" && schema.type) {
820
+ return schema.nullable ? `${schema.type} | null` : schema.type;
821
+ }
822
+ if (isRecord(schema.properties))
823
+ return "object";
824
+ if (Array.isArray(schema.oneOf)) {
825
+ return schema.oneOf
826
+ .slice(0, 4)
827
+ .map((s) => describeSchemaType(s, rootSchema, depth + 1))
828
+ .join(" | ");
829
+ }
830
+ if (Array.isArray(schema.anyOf)) {
831
+ return schema.anyOf
832
+ .slice(0, 4)
833
+ .map((s) => describeSchemaType(s, rootSchema, depth + 1))
834
+ .join(" | ");
835
+ }
836
+ if (Array.isArray(schema.allOf)) {
837
+ return schema.allOf
838
+ .slice(0, 4)
839
+ .map((s) => describeSchemaType(s, rootSchema, depth + 1))
840
+ .join(" & ");
841
+ }
842
+ if (schema.const !== undefined)
843
+ return `const`;
844
+ if (Array.isArray(schema.enum))
845
+ return `enum`;
846
+ return "any";
847
+ }
848
+ function formatSchemaConstraints(schema, strict) {
849
+ const parts = [];
850
+ if (typeof schema.format === "string" && schema.format)
851
+ parts.push(`format: ${schema.format}`);
852
+ if (schema.minimum !== undefined)
853
+ parts.push(`min: ${schema.minimum}`);
854
+ if (schema.maximum !== undefined)
855
+ parts.push(`max: ${schema.maximum}`);
856
+ if (schema.minLength !== undefined)
857
+ parts.push(`minLen: ${schema.minLength}`);
858
+ if (schema.maxLength !== undefined)
859
+ parts.push(`maxLen: ${schema.maxLength}`);
860
+ if (schema.minItems !== undefined)
861
+ parts.push(`minItems: ${schema.minItems}`);
862
+ if (schema.maxItems !== undefined)
863
+ parts.push(`maxItems: ${schema.maxItems}`);
864
+ if (schema.uniqueItems === true)
865
+ parts.push("uniqueItems");
866
+ if (typeof schema.pattern === "string" && schema.pattern)
867
+ parts.push(`pattern: /${schema.pattern}/`);
868
+ if (schema.const !== undefined)
869
+ parts.push(`const: ${JSON.stringify(schema.const)}`);
870
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
871
+ const shown = schema.enum.slice(0, 6).map((v) => JSON.stringify(v)).join(", ");
872
+ parts.push(`enum: [${shown}${schema.enum.length > 6 ? ", ..." : ""}]`);
873
+ }
874
+ if (schema.additionalProperties === false || (strict && (schema.type === "object" || isRecord(schema.properties)))) {
875
+ parts.push("no extra keys");
876
+ }
877
+ if (typeof schema.description === "string" && schema.description) {
878
+ parts.push(schema.description);
879
+ }
880
+ return parts.join("; ");
881
+ }
882
+ function flattenSchemaFields(schema, strict, rootSchema, prefix = "", depth = 0, visited = new Set(), out = []) {
883
+ if (!schema || depth >= MAX_SCHEMA_DEPTH || out.length >= MAX_SCHEMA_FIELDS_TABLE) {
884
+ return out;
885
+ }
886
+ if (visited.has(schema))
887
+ return out;
888
+ visited.add(schema);
889
+ const root = rootSchema ?? schema;
890
+ try {
891
+ let target = schema;
892
+ if (typeof schema.$ref === "string") {
893
+ const resolved = resolveLocalRef(root, schema.$ref);
894
+ if (!resolved) {
895
+ if (prefix) {
896
+ out.push({
897
+ path: prefix,
898
+ type: describeSchemaType(schema, root, depth),
899
+ required: false,
900
+ constraints: formatSchemaConstraints(schema, strict)
901
+ });
902
+ }
903
+ return out;
904
+ }
905
+ target = resolved;
906
+ }
907
+ if (isRecord(target.properties)) {
908
+ const reqSet = new Set(Array.isArray(target.required) ? target.required : []);
909
+ for (const propKey of Object.keys(target.properties)) {
910
+ if (out.length >= MAX_SCHEMA_FIELDS_TABLE)
911
+ break;
912
+ if (isForbiddenKey(propKey) || isSecretFieldName(propKey))
913
+ continue;
914
+ const propSchema = target.properties[propKey];
915
+ if (!isRecord(propSchema))
916
+ continue;
917
+ const fieldPath = prefix ? `${prefix}.${propKey}` : propKey;
918
+ out.push({
919
+ path: fieldPath,
920
+ type: describeSchemaType(propSchema, root, depth + 1),
921
+ required: reqSet.has(propKey),
922
+ constraints: formatSchemaConstraints(propSchema, strict)
923
+ });
924
+ const resolvedChild = typeof propSchema.$ref === "string"
925
+ ? resolveLocalRef(root, propSchema.$ref)
926
+ : propSchema;
927
+ if (resolvedChild && isRecord(resolvedChild.properties)) {
928
+ flattenSchemaFields(resolvedChild, strict, root, fieldPath, depth + 1, visited, out);
929
+ }
930
+ else if (resolvedChild &&
931
+ resolvedChild.type === "array" &&
932
+ isRecord(resolvedChild.items)) {
933
+ flattenSchemaFields(resolvedChild.items, strict, root, `${fieldPath}[]`, depth + 1, visited, out);
934
+ }
935
+ }
936
+ return out;
937
+ }
938
+ if (target.type === "array" && isRecord(target.items)) {
939
+ const itemPath = prefix ? `${prefix}[]` : "[]";
940
+ if (!prefix) {
941
+ out.push({
942
+ path: "[]",
943
+ type: describeSchemaType(target.items, root, depth + 1),
944
+ required: true,
945
+ constraints: formatSchemaConstraints(target, strict)
946
+ });
947
+ }
948
+ flattenSchemaFields(target.items, strict, root, itemPath, depth + 1, visited, out);
949
+ return out;
950
+ }
951
+ if (Array.isArray(target.allOf)) {
952
+ for (const branch of target.allOf) {
953
+ flattenSchemaFields(branch, strict, root, prefix, depth + 1, visited, out);
954
+ }
955
+ return out;
956
+ }
957
+ if (!prefix && (target.type || target.enum || target.const !== undefined)) {
958
+ out.push({
959
+ path: "(root)",
960
+ type: describeSchemaType(target, root, depth),
961
+ required: true,
962
+ constraints: formatSchemaConstraints(target, strict)
963
+ });
964
+ }
965
+ return out;
966
+ }
967
+ finally {
968
+ visited.delete(schema);
969
+ }
970
+ }
971
+ function parseJsonBody(rawBody) {
972
+ if (rawBody === undefined || rawBody === null)
973
+ return { isJson: false };
974
+ if (typeof rawBody === "string") {
975
+ const trimmed = rawBody.trim();
976
+ if (!trimmed)
977
+ return { isJson: false };
978
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
979
+ try {
980
+ return { parsed: JSON.parse(trimmed), isJson: true };
981
+ }
982
+ catch {
983
+ return { parsed: rawBody, isJson: false };
984
+ }
985
+ }
986
+ return { parsed: rawBody, isJson: false };
987
+ }
988
+ if (typeof rawBody === "object") {
989
+ return { parsed: rawBody, isJson: true };
990
+ }
991
+ return { parsed: rawBody, isJson: false };
992
+ }
993
+ function shellQuote(arg) {
994
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(arg))
995
+ return arg;
996
+ return `'${arg.replace(/'/g, "'\\''")}'`;
997
+ }
998
+ function buildCurlExample(baseUrl, method, pathname, queryParams, headers, requestExample) {
999
+ const origin = baseUrl ?? "https://api.example.com";
1000
+ const qs = queryParams.length > 0
1001
+ ? `?${new URLSearchParams(queryParams).toString()}`
1002
+ : "";
1003
+ const url = `${origin}${pathname}${qs}`;
1004
+ const lines = [`curl -X ${method} ${shellQuote(url)}`];
1005
+ for (const [k, v] of headers) {
1006
+ lines.push(` -H ${shellQuote(`${k}: ${v}`)}`);
1007
+ }
1008
+ if (requestExample !== undefined) {
1009
+ const hasContentType = headers.some(([k]) => k.toLowerCase() === "content-type");
1010
+ if (!hasContentType && typeof requestExample === "object" && requestExample !== null) {
1011
+ lines.push(` -H 'Content-Type: application/json'`);
1012
+ }
1013
+ const serialized = typeof requestExample === "string"
1014
+ ? requestExample
1015
+ : JSON.stringify(requestExample);
1016
+ if (serialized) {
1017
+ lines.push(` -d ${shellQuote(serialized)}`);
1018
+ }
1019
+ }
1020
+ return lines.join(" \\\n");
1021
+ }
1022
+ // ============================================================================
1023
+ // Invariant Normalizers (HTTP, CLI, Web)
1024
+ // ============================================================================
1025
+ function normalizeHttpInvariant(inv, invId, baseUrl, strict, warnings) {
1026
+ const input = isRecord(inv.input) ? inv.input : {};
1027
+ const expected = isRecord(inv.expected) ? inv.expected : {};
1028
+ const methodRaw = typeof input.method === "string" && stripControlChars(input.method).trim()
1029
+ ? stripControlChars(input.method).trim().toUpperCase()
1030
+ : "GET";
1031
+ if (!SUPPORTED_HTTP_METHODS.has(methodRaw)) {
1032
+ return null;
1033
+ }
1034
+ const rawPath = typeof input.path === "string"
1035
+ ? input.path
1036
+ : typeof input.urlPath === "string"
1037
+ ? input.urlPath
1038
+ : undefined;
1039
+ const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
1040
+ const pathParams = extractPathParams(pathname);
1041
+ const queryParams = sanitizeQueryEntries(inlineQuery, input.query);
1042
+ const headers = sanitizeHeaders(input.headers);
1043
+ const expectedStatuses = extractExpectedStatuses(expected.status);
1044
+ const responseHeaders = sanitizeHeaders(expected.headers);
1045
+ let requestSchema;
1046
+ let requestExample;
1047
+ if (BODY_HTTP_METHODS.has(methodRaw) && input.body !== undefined && input.body !== null) {
1048
+ const { parsed, isJson } = parseJsonBody(input.body);
1049
+ if (isJson && parsed !== undefined) {
1050
+ const sanitizedBody = sanitizeJsonValue(parsed, 0, new Set(), warnings);
1051
+ requestExample = sanitizedBody;
1052
+ requestSchema = sanitizeSchemaNode(inferSchemaFromValue(sanitizedBody), 0, new Set(), warnings);
1053
+ }
1054
+ else if (typeof parsed === "string" && parsed.trim()) {
1055
+ const cleanStr = sanitizeText(parsed);
1056
+ requestExample = cleanStr;
1057
+ requestSchema = { type: "string" };
1058
+ }
1059
+ }
1060
+ if (isRecord(input.jsonSchema)) {
1061
+ requestSchema = sanitizeSchemaNode(input.jsonSchema, 0, new Set(), warnings) ?? requestSchema;
1062
+ }
1063
+ let responseSchema;
1064
+ let responseExample;
1065
+ if (isRecord(expected.jsonSchema)) {
1066
+ responseSchema = sanitizeSchemaNode(expected.jsonSchema, 0, new Set(), warnings);
1067
+ }
1068
+ if (expected.jsonSubset !== undefined && expected.jsonSubset !== null) {
1069
+ const sanitizedSubset = sanitizeJsonValue(expected.jsonSubset, 0, new Set(), warnings);
1070
+ responseExample = sanitizedSubset;
1071
+ if (!responseSchema) {
1072
+ responseSchema = sanitizeSchemaNode(inferSchemaFromValue(sanitizedSubset), 0, new Set(), warnings);
1073
+ }
1074
+ }
1075
+ const bodyContains = [];
1076
+ if (typeof expected.bodyContains === "string" && expected.bodyContains.trim()) {
1077
+ bodyContains.push(sanitizeSingleLineText(expected.bodyContains, 160));
1078
+ }
1079
+ else if (Array.isArray(expected.bodyContains)) {
1080
+ for (const item of expected.bodyContains.slice(0, 12)) {
1081
+ if (typeof item === "string" && item.trim()) {
1082
+ bodyContains.push(sanitizeSingleLineText(item, 160));
1083
+ }
1084
+ }
1085
+ }
1086
+ const jsonPaths = [];
1087
+ if (Array.isArray(expected.jsonPaths)) {
1088
+ for (const jp of expected.jsonPaths.slice(0, 24)) {
1089
+ if (!isRecord(jp) || typeof jp.path !== "string")
1090
+ continue;
1091
+ const cleanPath = sanitizeSingleLineText(jp.path, 120);
1092
+ if (!cleanPath || isSecretFieldName(cleanPath))
1093
+ continue;
1094
+ const typed = jp;
1095
+ let matcher = "exists";
1096
+ if (typed.equals !== undefined) {
1097
+ matcher = `equals ${JSON.stringify(sanitizeJsonValue(typed.equals, 0, new Set(), warnings))}`;
1098
+ }
1099
+ else if (typeof typed.matches === "string") {
1100
+ matcher = `matches /${sanitizeSingleLineText(typed.matches, 80)}/`;
1101
+ }
1102
+ jsonPaths.push({ path: cleanPath, matcher });
1103
+ }
1104
+ }
1105
+ const maxLatencyMs = typeof expected.maxLatencyMs === "number" &&
1106
+ Number.isFinite(expected.maxLatencyMs) &&
1107
+ expected.maxLatencyMs > 0
1108
+ ? expected.maxLatencyMs
1109
+ : undefined;
1110
+ const description = typeof inv.description === "string" && inv.description.trim()
1111
+ ? sanitizeSingleLineText(inv.description, 200)
1112
+ : `${methodRaw} ${pathname}`;
1113
+ const tags = Array.isArray(inv.tags)
1114
+ ? inv.tags
1115
+ .filter((t) => typeof t === "string" && t.trim().length > 0)
1116
+ .map((t) => sanitizeSingleLineText(t, 40))
1117
+ .filter(Boolean)
1118
+ : [];
1119
+ const requestFields = flattenSchemaFields(requestSchema, strict);
1120
+ const responseFields = flattenSchemaFields(responseSchema, strict);
1121
+ const curlExample = buildCurlExample(baseUrl, methodRaw, pathname, queryParams, headers, requestExample);
1122
+ return {
1123
+ id: invId,
1124
+ severity: inv.severity === "soft" ? "soft" : "hard",
1125
+ tags,
1126
+ description,
1127
+ method: methodRaw,
1128
+ pathname,
1129
+ pathParams,
1130
+ queryParams,
1131
+ headers,
1132
+ expectedStatuses,
1133
+ responseHeaders,
1134
+ ...(requestSchema ? { requestSchema } : {}),
1135
+ requestFields,
1136
+ ...(requestExample !== undefined ? { requestExample } : {}),
1137
+ ...(responseSchema ? { responseSchema } : {}),
1138
+ responseFields,
1139
+ ...(responseExample !== undefined ? { responseExample } : {}),
1140
+ bodyContains,
1141
+ jsonPaths,
1142
+ ...(maxLatencyMs !== undefined ? { maxLatencyMs } : {}),
1143
+ curlExample
1144
+ };
1145
+ }
1146
+ function isSensitiveCliValue(raw) {
1147
+ if (/\.vibecode-vault/i.test(raw) || isAuthSchemeValue(raw))
1148
+ return true;
1149
+ const kvMatch = raw.match(/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)\s*[:=]/);
1150
+ if (kvMatch &&
1151
+ kvMatch[1] &&
1152
+ (isSensitiveHeaderName(kvMatch[1]) ||
1153
+ isSensitiveQueryName(kvMatch[1]) ||
1154
+ isSecretFieldName(kvMatch[1]))) {
1155
+ return true;
1156
+ }
1157
+ return false;
1158
+ }
1159
+ function sanitizeCliArgList(rawArgs) {
1160
+ const out = [];
1161
+ for (let i = 0; i < rawArgs.length; i++) {
1162
+ const raw = rawArgs[i];
1163
+ if (typeof raw !== "string")
1164
+ continue;
1165
+ const noControl = stripControlChars(raw).replace(/[\r\n]+/g, "");
1166
+ if (!noControl)
1167
+ continue;
1168
+ if (isSensitiveCliValue(noControl))
1169
+ continue;
1170
+ const flagName = noControl.split("=")[0]?.replace(/^-{1,2}/, "") ?? "";
1171
+ if (SENSITIVE_CLI_FLAG_RE.test(noControl) ||
1172
+ (noControl.startsWith("-") && flagName.length > 0 && isSecretFieldName(flagName))) {
1173
+ if (!noControl.includes("=")) {
1174
+ i += 1;
1175
+ }
1176
+ continue;
1177
+ }
1178
+ const headerEqMatch = noControl.match(/^(?:--header|-H)=(.+)$/);
1179
+ if (headerEqMatch && headerEqMatch[1] !== undefined && isSensitiveCliValue(headerEqMatch[1])) {
1180
+ continue;
1181
+ }
1182
+ if ((noControl === "-H" || noControl === "--header") && i + 1 < rawArgs.length) {
1183
+ const nextRaw = stripControlChars(String(rawArgs[i + 1] ?? "")).replace(/[\r\n]+/g, "");
1184
+ if (isSensitiveCliValue(nextRaw)) {
1185
+ i += 1;
1186
+ continue;
1187
+ }
1188
+ }
1189
+ const sanitized = sanitizeText(noControl);
1190
+ if (!sanitized || isSensitiveCliValue(sanitized))
1191
+ continue;
1192
+ out.push(sanitized);
1193
+ if (out.length >= MAX_CLI_ARGS)
1194
+ break;
1195
+ }
1196
+ return out;
1197
+ }
1198
+ function resolveCliCommandTokens(inv, contract) {
1199
+ const input = isRecord(inv.input) ? inv.input : {};
1200
+ if (typeof input.command === "string" && input.command.trim()) {
1201
+ const tokens = splitCommand(input.command.trim());
1202
+ if (tokens.length > 0)
1203
+ return tokens;
1204
+ }
1205
+ else if (Array.isArray(input.command)) {
1206
+ const tokens = input.command.filter((t) => typeof t === "string" && t.trim().length > 0);
1207
+ if (tokens.length > 0)
1208
+ return tokens;
1209
+ }
1210
+ const sources = isRecord(contract.target) && Array.isArray(contract.target.sources)
1211
+ ? contract.target.sources
1212
+ : [];
1213
+ const extractFromSource = (src) => {
1214
+ if (!isRecord(src))
1215
+ return null;
1216
+ if (isRecord(src.meta) && typeof src.meta.command === "string" && src.meta.command.trim()) {
1217
+ const tokens = splitCommand(src.meta.command.trim());
1218
+ if (tokens.length > 0)
1219
+ return tokens;
1220
+ }
1221
+ if (typeof src.ref === "string" && src.ref.trim() && !/^https?:\/\//i.test(src.ref.trim())) {
1222
+ const kind = typeof src.kind === "string" ? src.kind.toLowerCase() : "";
1223
+ if (kind === "cli" || kind === "script" || kind === "command" || kind === "") {
1224
+ const tokens = splitCommand(src.ref.trim());
1225
+ if (tokens.length > 0)
1226
+ return tokens;
1227
+ }
1228
+ }
1229
+ return null;
1230
+ };
1231
+ if (typeof inv.sourceId === "string" && inv.sourceId.trim()) {
1232
+ const matched = sources.find((s) => isRecord(s) && s.id === inv.sourceId);
1233
+ const tokens = extractFromSource(matched);
1234
+ if (tokens)
1235
+ return tokens;
1236
+ }
1237
+ for (const src of sources) {
1238
+ const tokens = extractFromSource(src);
1239
+ if (tokens)
1240
+ return tokens;
1241
+ }
1242
+ const targetName = isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()
1243
+ ? sanitizeSingleLineText(contract.target.name, 48).toLowerCase().replace(/[^a-z0-9._-]+/g, "-")
1244
+ : "cli";
1245
+ return [targetName || "cli"];
1246
+ }
1247
+ function normalizeCliInvariant(inv, invId, contract, strict, warnings) {
1248
+ const input = isRecord(inv.input) ? inv.input : {};
1249
+ const expected = isRecord(inv.expected) ? inv.expected : {};
1250
+ const cmdTokens = resolveCliCommandTokens(inv, contract);
1251
+ const rawExec = stripControlChars(cmdTokens[0] ?? "cli").replace(/[\r\n]+/g, "").trim();
1252
+ const executable = !rawExec || /\.vibecode-vault/i.test(rawExec) || isAuthSchemeValue(rawExec)
1253
+ ? "cli"
1254
+ : sanitizeSingleLineText(rawExec, 80);
1255
+ const sourceArgs = sanitizeCliArgList(cmdTokens.slice(1));
1256
+ const rawInvArgs = Array.isArray(input.args)
1257
+ ? input.args.filter((a) => typeof a === "string")
1258
+ : [];
1259
+ const args = [...sourceArgs, ...sanitizeCliArgList(rawInvArgs)].slice(0, MAX_CLI_ARGS);
1260
+ const commandPreview = [executable, ...args.map(shellQuote)].join(" ");
1261
+ const safeEnvKeys = [];
1262
+ if (isRecord(input.env)) {
1263
+ for (const key of Object.keys(input.env)) {
1264
+ if (isForbiddenKey(key) || isSecretFieldName(key))
1265
+ continue;
1266
+ const cleanKey = sanitizeSingleLineText(key, 64);
1267
+ if (cleanKey && !isSecretFieldName(cleanKey)) {
1268
+ safeEnvKeys.push(cleanKey);
1269
+ }
1270
+ }
1271
+ }
1272
+ let stdinPreview;
1273
+ let stdinSchema;
1274
+ if (typeof input.stdin === "string" && input.stdin.trim()) {
1275
+ const { parsed, isJson } = parseJsonBody(input.stdin);
1276
+ if (isJson && parsed !== undefined) {
1277
+ const cleanJson = sanitizeJsonValue(parsed, 0, new Set(), warnings);
1278
+ stdinPreview = JSON.stringify(cleanJson, null, 2);
1279
+ stdinSchema = sanitizeSchemaNode(inferSchemaFromValue(cleanJson), 0, new Set(), warnings);
1280
+ }
1281
+ else {
1282
+ stdinPreview = sanitizeSingleLineText(input.stdin, 200);
1283
+ }
1284
+ }
1285
+ const expectedExitCodes = extractExpectedExitCodes(expected.exitCode);
1286
+ const stdoutContains = Array.isArray(expected.stdoutContains)
1287
+ ? expected.stdoutContains
1288
+ .filter((s) => typeof s === "string" && s.trim().length > 0)
1289
+ .slice(0, 12)
1290
+ .map((s) => sanitizeSingleLineText(s, 160))
1291
+ : [];
1292
+ const stdoutNotContains = Array.isArray(expected.stdoutNotContains)
1293
+ ? expected.stdoutNotContains
1294
+ .filter((s) => typeof s === "string" && s.trim().length > 0)
1295
+ .slice(0, 12)
1296
+ .map((s) => sanitizeSingleLineText(s, 160))
1297
+ : [];
1298
+ const stderrContains = Array.isArray(expected.stderrContains)
1299
+ ? expected.stderrContains
1300
+ .filter((s) => typeof s === "string" && s.trim().length > 0)
1301
+ .slice(0, 12)
1302
+ .map((s) => sanitizeSingleLineText(s, 160))
1303
+ : [];
1304
+ let stdoutSchema;
1305
+ let stdoutExample;
1306
+ if (isRecord(expected.jsonSchema)) {
1307
+ stdoutSchema = sanitizeSchemaNode(expected.jsonSchema, 0, new Set(), warnings);
1308
+ }
1309
+ if (expected.jsonSubset !== undefined && expected.jsonSubset !== null) {
1310
+ const cleanSubset = sanitizeJsonValue(expected.jsonSubset, 0, new Set(), warnings);
1311
+ stdoutExample = cleanSubset;
1312
+ if (!stdoutSchema) {
1313
+ stdoutSchema = sanitizeSchemaNode(inferSchemaFromValue(cleanSubset), 0, new Set(), warnings);
1314
+ }
1315
+ }
1316
+ const description = typeof inv.description === "string" && inv.description.trim()
1317
+ ? sanitizeSingleLineText(inv.description, 200)
1318
+ : `Run ${executable}`;
1319
+ const tags = Array.isArray(inv.tags)
1320
+ ? inv.tags
1321
+ .filter((t) => typeof t === "string" && t.trim().length > 0)
1322
+ .map((t) => sanitizeSingleLineText(t, 40))
1323
+ .filter(Boolean)
1324
+ : [];
1325
+ return {
1326
+ id: invId,
1327
+ severity: inv.severity === "soft" ? "soft" : "hard",
1328
+ tags,
1329
+ description,
1330
+ executable,
1331
+ args,
1332
+ commandPreview,
1333
+ safeEnvKeys,
1334
+ ...(stdinPreview ? { stdinPreview } : {}),
1335
+ ...(stdinSchema ? { stdinSchema } : {}),
1336
+ stdinFields: flattenSchemaFields(stdinSchema, strict),
1337
+ expectedExitCodes,
1338
+ stdoutContains,
1339
+ stdoutNotContains,
1340
+ stderrContains,
1341
+ ...(stdoutSchema ? { stdoutSchema } : {}),
1342
+ stdoutFields: flattenSchemaFields(stdoutSchema, strict),
1343
+ ...(stdoutExample !== undefined ? { stdoutExample } : {})
1344
+ };
1345
+ }
1346
+ function formatViewport(raw) {
1347
+ if (!isRecord(raw))
1348
+ return undefined;
1349
+ const vp = raw;
1350
+ if (typeof vp.width === "number" &&
1351
+ Number.isFinite(vp.width) &&
1352
+ vp.width > 0 &&
1353
+ typeof vp.height === "number" &&
1354
+ Number.isFinite(vp.height) &&
1355
+ vp.height > 0) {
1356
+ return `${Math.round(vp.width)}x${Math.round(vp.height)}`;
1357
+ }
1358
+ return undefined;
1359
+ }
1360
+ function sanitizeWebStep(step) {
1361
+ const action = typeof step.action === "string" && step.action.trim()
1362
+ ? sanitizeSingleLineText(step.action, 48)
1363
+ : "step";
1364
+ const rawTarget = typeof step.selector === "string"
1365
+ ? step.selector
1366
+ : typeof step.path === "string"
1367
+ ? parsePathAndInlineQuery(step.path).pathname
1368
+ : typeof step.url === "string"
1369
+ ? parsePathAndInlineQuery(step.url).pathname
1370
+ : "";
1371
+ const target = sanitizeSingleLineText(rawTarget, 120);
1372
+ const isSecretTarget = isSecretFieldName(target);
1373
+ let detail = "";
1374
+ if (typeof step.key === "string" && step.key.trim()) {
1375
+ detail = `key: ${sanitizeSingleLineText(step.key, 32)}`;
1376
+ }
1377
+ else if (step.value !== undefined && step.value !== null) {
1378
+ detail = isSecretTarget
1379
+ ? "value: [REDACTED]"
1380
+ : `value: ${sanitizeSingleLineText(String(step.value), 120)}`;
1381
+ }
1382
+ else if (typeof step.text === "string" && step.text.trim()) {
1383
+ detail = isSecretTarget
1384
+ ? "text: [REDACTED]"
1385
+ : `text: ${sanitizeSingleLineText(step.text, 120)}`;
1386
+ }
1387
+ else if (typeof step.waitUntil === "string" && step.waitUntil.trim()) {
1388
+ detail = `waitUntil: ${sanitizeSingleLineText(step.waitUntil, 32)}`;
1389
+ }
1390
+ return { action, target, detail };
1391
+ }
1392
+ function normalizeWebInvariant(inv, invId, strict, warnings) {
1393
+ const input = isRecord(inv.input) ? inv.input : {};
1394
+ const expected = isRecord(inv.expected) ? inv.expected : {};
1395
+ const rawRoute = typeof input.path === "string"
1396
+ ? input.path
1397
+ : typeof input.urlPath === "string"
1398
+ ? input.urlPath
1399
+ : typeof input.startPath === "string"
1400
+ ? input.startPath
1401
+ : typeof input.triggerPath === "string"
1402
+ ? input.triggerPath
1403
+ : "/";
1404
+ const route = parsePathAndInlineQuery(rawRoute).pathname;
1405
+ const viewport = formatViewport(input.viewport);
1406
+ const landmarks = [];
1407
+ if (Array.isArray(expected.landmarks)) {
1408
+ for (const item of expected.landmarks.slice(0, 32)) {
1409
+ if (!isRecord(item))
1410
+ continue;
1411
+ const lm = item;
1412
+ if (typeof lm.tag !== "string" || !lm.tag.trim())
1413
+ continue;
1414
+ landmarks.push({
1415
+ tag: sanitizeSingleLineText(lm.tag, 40),
1416
+ required: lm.required !== false,
1417
+ ...(typeof lm.textContains === "string" && lm.textContains.trim()
1418
+ ? { textContains: sanitizeSingleLineText(lm.textContains, 120) }
1419
+ : {})
1420
+ });
1421
+ }
1422
+ }
1423
+ const interactiveLandmarks = [];
1424
+ if (Array.isArray(expected.interactiveLandmarks)) {
1425
+ for (const item of expected.interactiveLandmarks.slice(0, 32)) {
1426
+ if (!isRecord(item))
1427
+ continue;
1428
+ const lm = item;
1429
+ if (typeof lm.role !== "string" || typeof lm.tag !== "string")
1430
+ continue;
1431
+ interactiveLandmarks.push({
1432
+ role: sanitizeSingleLineText(lm.role, 40),
1433
+ tag: sanitizeSingleLineText(lm.tag, 40),
1434
+ ...(typeof lm.name === "string" && lm.name.trim()
1435
+ ? { name: sanitizeSingleLineText(lm.name, 100) }
1436
+ : {})
1437
+ });
1438
+ }
1439
+ }
1440
+ const domAssertions = [];
1441
+ if (Array.isArray(expected.domAssertions)) {
1442
+ for (const item of expected.domAssertions.slice(0, 32)) {
1443
+ if (!isRecord(item))
1444
+ continue;
1445
+ const da = item;
1446
+ if (typeof da.selector !== "string" || !da.selector.trim())
1447
+ continue;
1448
+ const parts = [];
1449
+ if (typeof da.count === "number" && Number.isInteger(da.count))
1450
+ parts.push(`count = ${da.count}`);
1451
+ if (typeof da.minCount === "number" && Number.isInteger(da.minCount))
1452
+ parts.push(`minCount >= ${da.minCount}`);
1453
+ domAssertions.push({
1454
+ selector: sanitizeSingleLineText(da.selector, 120),
1455
+ constraint: parts.join(", ") || "present"
1456
+ });
1457
+ }
1458
+ }
1459
+ const visibleText = Array.isArray(expected.visibleText)
1460
+ ? expected.visibleText
1461
+ .filter((s) => typeof s === "string" && s.trim().length > 0)
1462
+ .slice(0, 20)
1463
+ .map((s) => sanitizeSingleLineText(s, 140))
1464
+ : [];
1465
+ const hiddenText = Array.isArray(expected.hiddenText)
1466
+ ? expected.hiddenText
1467
+ .filter((s) => typeof s === "string" && s.trim().length > 0)
1468
+ .slice(0, 20)
1469
+ .map((s) => sanitizeSingleLineText(s, 140))
1470
+ : [];
1471
+ const steps = [];
1472
+ if (Array.isArray(input.steps)) {
1473
+ for (const rawStep of input.steps.slice(0, MAX_WEB_STEPS)) {
1474
+ if (!isRecord(rawStep))
1475
+ continue;
1476
+ steps.push(sanitizeWebStep(rawStep));
1477
+ }
1478
+ }
1479
+ const networkCalls = [];
1480
+ if (Array.isArray(expected.networkCalls)) {
1481
+ for (const rawNet of expected.networkCalls.slice(0, 32)) {
1482
+ if (!isRecord(rawNet))
1483
+ continue;
1484
+ const net = rawNet;
1485
+ const method = typeof net.method === "string" && net.method.trim()
1486
+ ? sanitizeSingleLineText(net.method, 16).toUpperCase()
1487
+ : "GET";
1488
+ const netPath = typeof net.path === "string"
1489
+ ? parsePathAndInlineQuery(net.path).pathname
1490
+ : typeof net.pathPattern === "string"
1491
+ ? sanitizeSingleLineText(net.pathPattern, 160)
1492
+ : "/";
1493
+ const netSchema = isRecord(net.jsonSchema)
1494
+ ? sanitizeSchemaNode(net.jsonSchema, 0, new Set(), warnings)
1495
+ : undefined;
1496
+ networkCalls.push({
1497
+ method,
1498
+ path: netPath,
1499
+ ...(typeof net.status === "number" && Number.isInteger(net.status) ? { status: net.status } : {}),
1500
+ ...(typeof net.contentType === "string" && net.contentType.trim()
1501
+ ? { contentType: sanitizeSingleLineText(net.contentType, 80) }
1502
+ : {}),
1503
+ responseFields: flattenSchemaFields(netSchema, strict)
1504
+ });
1505
+ }
1506
+ }
1507
+ const consoleChecks = [];
1508
+ if (expected.noConsoleErrors === true)
1509
+ consoleChecks.push("No console errors");
1510
+ if (expected.noUncaughtExceptions === true)
1511
+ consoleChecks.push("No uncaught exceptions");
1512
+ if (expected.noPageErrors === true)
1513
+ consoleChecks.push("No page errors");
1514
+ if (expected.noServerErrors === true)
1515
+ consoleChecks.push("No 5xx server errors");
1516
+ const description = typeof inv.description === "string" && inv.description.trim()
1517
+ ? sanitizeSingleLineText(inv.description, 200)
1518
+ : `${inv.type} ${route}`;
1519
+ const tags = Array.isArray(inv.tags)
1520
+ ? inv.tags
1521
+ .filter((t) => typeof t === "string" && t.trim().length > 0)
1522
+ .map((t) => sanitizeSingleLineText(t, 40))
1523
+ .filter(Boolean)
1524
+ : [];
1525
+ return {
1526
+ id: invId,
1527
+ type: inv.type,
1528
+ severity: inv.severity === "soft" ? "soft" : "hard",
1529
+ tags,
1530
+ description,
1531
+ route,
1532
+ ...(viewport ? { viewport } : {}),
1533
+ ...(typeof expected.titleContains === "string" && expected.titleContains.trim()
1534
+ ? { titleContains: sanitizeSingleLineText(expected.titleContains, 120) }
1535
+ : {}),
1536
+ ...(typeof expected.finalUrlIncludes === "string" && expected.finalUrlIncludes.trim()
1537
+ ? { finalUrlIncludes: sanitizeSingleLineText(expected.finalUrlIncludes, 120) }
1538
+ : {}),
1539
+ landmarks,
1540
+ interactiveLandmarks,
1541
+ domAssertions,
1542
+ visibleText,
1543
+ hiddenText,
1544
+ steps,
1545
+ networkCalls,
1546
+ consoleChecks
1547
+ };
1548
+ }
1549
+ // ============================================================================
1550
+ // Format Renderers: Markdown (GFM), HTML Portal, llms.txt
1551
+ // ============================================================================
1552
+ function renderSchemaFieldsMarkdownTable(fields) {
1553
+ const lines = [
1554
+ "| Field | Type | Required | Constraints |",
1555
+ "| --- | --- | --- | --- |"
1556
+ ];
1557
+ for (const row of fields) {
1558
+ lines.push(`| ${markdownCodeSpan(row.path)} | ${markdownCodeSpan(row.type)} | ${row.required ? "Yes" : "No"} | ${row.constraints ? escapeMarkdownCell(row.constraints) : "—"} |`);
1559
+ }
1560
+ return lines;
1561
+ }
1562
+ function renderMarkdownDocs(model) {
1563
+ const lines = [];
1564
+ const total = model.http.length + model.cli.length + model.web.length;
1565
+ lines.push(`# ${escapeMarkdownInline(model.title, 160)}`);
1566
+ lines.push("");
1567
+ lines.push(`> Generated API, CLI, and Web reference documentation for **${escapeMarkdownInline(model.targetName, 120)}**.`);
1568
+ lines.push("");
1569
+ lines.push("| Metric | Value |");
1570
+ lines.push("| --- | --- |");
1571
+ lines.push(`| Documented Invariants | ${total} |`);
1572
+ lines.push(`| HTTP Endpoints | ${model.http.length} |`);
1573
+ lines.push(`| CLI Commands | ${model.cli.length} |`);
1574
+ lines.push(`| Web Routes & Flows | ${model.web.length} |`);
1575
+ if (model.baseUrl) {
1576
+ lines.push(`| Base URL | ${markdownCodeSpan(model.baseUrl)} |`);
1577
+ }
1578
+ if (model.strict) {
1579
+ lines.push(`| Schema Mode | Strict (additional properties disallowed) |`);
1580
+ }
1581
+ lines.push("");
1582
+ if (total === 0) {
1583
+ lines.push("_No visible HTTP, CLI, or Web invariants were found in this contract._");
1584
+ lines.push("");
1585
+ }
1586
+ if (model.http.length > 0) {
1587
+ lines.push("## HTTP API Reference");
1588
+ lines.push("");
1589
+ lines.push("| Method | Path | Expected Status | Severity | Description |");
1590
+ lines.push("| --- | --- | --- | --- | --- |");
1591
+ for (const item of model.http) {
1592
+ const statuses = item.expectedStatuses.length > 0 ? item.expectedStatuses.join(", ") : "any";
1593
+ lines.push(`| ${markdownCodeSpan(item.method)} | ${markdownCodeSpan(item.pathname)} | ${escapeMarkdownCell(statuses)} | ${escapeMarkdownCell(item.severity)} | ${escapeMarkdownCell(item.description)} |`);
1594
+ }
1595
+ lines.push("");
1596
+ for (const item of model.http) {
1597
+ lines.push(`### ${escapeMarkdownInline(item.method, 16)} ${markdownCodeSpan(item.pathname)}`);
1598
+ lines.push("");
1599
+ lines.push(escapeMarkdownInline(item.description, 240));
1600
+ lines.push("");
1601
+ const metaBits = [
1602
+ `ID: ${markdownCodeSpan(item.id)}`,
1603
+ `Severity: ${markdownCodeSpan(item.severity)}`
1604
+ ];
1605
+ if (item.expectedStatuses.length > 0) {
1606
+ metaBits.push(`Statuses: ${markdownCodeSpan(item.expectedStatuses.join(", "))}`);
1607
+ }
1608
+ if (item.maxLatencyMs !== undefined) {
1609
+ metaBits.push(`Max Latency: ${markdownCodeSpan(`${item.maxLatencyMs}ms`)}`);
1610
+ }
1611
+ lines.push(`- ${metaBits.join(" | ")}`);
1612
+ lines.push("");
1613
+ if (item.pathParams.length > 0) {
1614
+ lines.push("#### Path Parameters");
1615
+ lines.push("");
1616
+ lines.push("| Name | Type | Required |");
1617
+ lines.push("| --- | --- | --- |");
1618
+ for (const p of item.pathParams) {
1619
+ lines.push(`| ${markdownCodeSpan(p)} | \`string\` | Yes |`);
1620
+ }
1621
+ lines.push("");
1622
+ }
1623
+ if (item.queryParams.length > 0) {
1624
+ lines.push("#### Query Parameters");
1625
+ lines.push("");
1626
+ lines.push("| Name | Sample Value |");
1627
+ lines.push("| --- | --- |");
1628
+ for (const [k, v] of item.queryParams) {
1629
+ lines.push(`| ${markdownCodeSpan(k)} | ${markdownCodeSpan(v)} |`);
1630
+ }
1631
+ lines.push("");
1632
+ }
1633
+ if (item.headers.length > 0) {
1634
+ lines.push("#### Request Headers");
1635
+ lines.push("");
1636
+ lines.push("| Header | Value |");
1637
+ lines.push("| --- | --- |");
1638
+ for (const [k, v] of item.headers) {
1639
+ lines.push(`| ${markdownCodeSpan(k)} | ${markdownCodeSpan(v)} |`);
1640
+ }
1641
+ lines.push("");
1642
+ }
1643
+ if (item.requestFields.length > 0) {
1644
+ lines.push("#### Request Body Schema");
1645
+ lines.push("");
1646
+ lines.push(...renderSchemaFieldsMarkdownTable(item.requestFields));
1647
+ lines.push("");
1648
+ }
1649
+ if (item.responseFields.length > 0) {
1650
+ lines.push("#### Response Schema");
1651
+ lines.push("");
1652
+ lines.push(...renderSchemaFieldsMarkdownTable(item.responseFields));
1653
+ lines.push("");
1654
+ }
1655
+ if (item.responseHeaders.length > 0) {
1656
+ lines.push("#### Expected Response Headers");
1657
+ lines.push("");
1658
+ lines.push("| Header | Value |");
1659
+ lines.push("| --- | --- |");
1660
+ for (const [k, v] of item.responseHeaders) {
1661
+ lines.push(`| ${markdownCodeSpan(k)} | ${markdownCodeSpan(v)} |`);
1662
+ }
1663
+ lines.push("");
1664
+ }
1665
+ if (item.jsonPaths.length > 0) {
1666
+ lines.push("#### JSONPath Assertions");
1667
+ lines.push("");
1668
+ lines.push("| JSONPath | Expectation |");
1669
+ lines.push("| --- | --- |");
1670
+ for (const jp of item.jsonPaths) {
1671
+ lines.push(`| ${markdownCodeSpan(jp.path)} | ${escapeMarkdownCell(jp.matcher)} |`);
1672
+ }
1673
+ lines.push("");
1674
+ }
1675
+ if (item.bodyContains.length > 0) {
1676
+ lines.push(`- Response body contains: ${item.bodyContains.map(markdownCodeSpan).join(", ")}`);
1677
+ lines.push("");
1678
+ }
1679
+ lines.push("#### Example Request");
1680
+ lines.push("");
1681
+ lines.push(markdownCodeBlock(item.curlExample, "bash"));
1682
+ lines.push("");
1683
+ if (item.responseExample !== undefined) {
1684
+ lines.push("#### Example Response");
1685
+ lines.push("");
1686
+ lines.push(markdownCodeBlock(JSON.stringify(item.responseExample, null, 2), "json"));
1687
+ lines.push("");
1688
+ }
1689
+ }
1690
+ }
1691
+ if (model.cli.length > 0) {
1692
+ lines.push("## CLI Reference");
1693
+ lines.push("");
1694
+ lines.push("| ID | Command | Expected Exit Codes | Description |");
1695
+ lines.push("| --- | --- | --- | --- |");
1696
+ for (const item of model.cli) {
1697
+ const exits = item.expectedExitCodes.length > 0 ? item.expectedExitCodes.join(", ") : "0";
1698
+ lines.push(`| ${markdownCodeSpan(item.id)} | ${markdownCodeSpan(item.commandPreview)} | ${escapeMarkdownCell(exits)} | ${escapeMarkdownCell(item.description)} |`);
1699
+ }
1700
+ lines.push("");
1701
+ for (const item of model.cli) {
1702
+ lines.push(`### ${escapeMarkdownInline(item.id, 80)}`);
1703
+ lines.push("");
1704
+ lines.push(escapeMarkdownInline(item.description, 240));
1705
+ lines.push("");
1706
+ lines.push(markdownCodeBlock(item.commandPreview, "bash"));
1707
+ lines.push("");
1708
+ if (item.expectedExitCodes.length > 0) {
1709
+ lines.push(`- Expected Exit Codes: ${markdownCodeSpan(item.expectedExitCodes.join(", "))}`);
1710
+ }
1711
+ if (item.safeEnvKeys.length > 0) {
1712
+ lines.push(`- Safe Environment Variables: ${item.safeEnvKeys.map(markdownCodeSpan).join(", ")}`);
1713
+ }
1714
+ if (item.stdoutContains.length > 0) {
1715
+ lines.push(`- Stdout Contains: ${item.stdoutContains.map(markdownCodeSpan).join(", ")}`);
1716
+ }
1717
+ if (item.stdoutNotContains.length > 0) {
1718
+ lines.push(`- Stdout Must Exclude: ${item.stdoutNotContains.map(markdownCodeSpan).join(", ")}`);
1719
+ }
1720
+ if (item.stderrContains.length > 0) {
1721
+ lines.push(`- Stderr Contains: ${item.stderrContains.map(markdownCodeSpan).join(", ")}`);
1722
+ }
1723
+ lines.push("");
1724
+ if (item.stdinFields.length > 0) {
1725
+ lines.push("#### Stdin JSON Schema");
1726
+ lines.push("");
1727
+ lines.push(...renderSchemaFieldsMarkdownTable(item.stdinFields));
1728
+ lines.push("");
1729
+ }
1730
+ else if (item.stdinPreview) {
1731
+ lines.push("#### Example Stdin");
1732
+ lines.push("");
1733
+ lines.push(markdownCodeBlock(item.stdinPreview, "text"));
1734
+ lines.push("");
1735
+ }
1736
+ if (item.stdoutFields.length > 0) {
1737
+ lines.push("#### Stdout JSON Schema");
1738
+ lines.push("");
1739
+ lines.push(...renderSchemaFieldsMarkdownTable(item.stdoutFields));
1740
+ lines.push("");
1741
+ }
1742
+ if (item.stdoutExample !== undefined) {
1743
+ lines.push("#### Example Stdout");
1744
+ lines.push("");
1745
+ lines.push(markdownCodeBlock(JSON.stringify(item.stdoutExample, null, 2), "json"));
1746
+ lines.push("");
1747
+ }
1748
+ }
1749
+ }
1750
+ if (model.web.length > 0) {
1751
+ lines.push("## Web Routes & Flows");
1752
+ lines.push("");
1753
+ lines.push("| ID | Type | Route | Viewport | Description |");
1754
+ lines.push("| --- | --- | --- | --- | --- |");
1755
+ for (const item of model.web) {
1756
+ lines.push(`| ${markdownCodeSpan(item.id)} | ${markdownCodeSpan(item.type)} | ${markdownCodeSpan(item.route)} | ${escapeMarkdownCell(item.viewport ?? "default")} | ${escapeMarkdownCell(item.description)} |`);
1757
+ }
1758
+ lines.push("");
1759
+ for (const item of model.web) {
1760
+ lines.push(`### ${markdownCodeSpan(item.route)} (${escapeMarkdownInline(item.id, 80)})`);
1761
+ lines.push("");
1762
+ lines.push(escapeMarkdownInline(item.description, 240));
1763
+ lines.push("");
1764
+ if (item.titleContains) {
1765
+ lines.push(`- Title Contains: ${markdownCodeSpan(item.titleContains)}`);
1766
+ }
1767
+ if (item.finalUrlIncludes) {
1768
+ lines.push(`- Final URL Includes: ${markdownCodeSpan(item.finalUrlIncludes)}`);
1769
+ }
1770
+ if (item.consoleChecks.length > 0) {
1771
+ lines.push(`- Runtime Checks: ${escapeMarkdownInline(item.consoleChecks.join(", "), 200)}`);
1772
+ }
1773
+ if (item.visibleText.length > 0) {
1774
+ lines.push(`- Visible Text: ${item.visibleText.map(markdownCodeSpan).join(", ")}`);
1775
+ }
1776
+ if (item.hiddenText.length > 0) {
1777
+ lines.push(`- Hidden Text: ${item.hiddenText.map(markdownCodeSpan).join(", ")}`);
1778
+ }
1779
+ lines.push("");
1780
+ if (item.landmarks.length > 0) {
1781
+ lines.push("#### Landmarks");
1782
+ lines.push("");
1783
+ lines.push("| Tag | Required | Text Contains |");
1784
+ lines.push("| --- | --- | --- |");
1785
+ for (const lm of item.landmarks) {
1786
+ lines.push(`| ${markdownCodeSpan(lm.tag)} | ${lm.required ? "Yes" : "No"} | ${lm.textContains ? escapeMarkdownCell(lm.textContains) : "—"} |`);
1787
+ }
1788
+ lines.push("");
1789
+ }
1790
+ if (item.interactiveLandmarks.length > 0) {
1791
+ lines.push("#### Interactive Landmarks");
1792
+ lines.push("");
1793
+ lines.push("| Role | Tag | Accessible Name |");
1794
+ lines.push("| --- | --- | --- |");
1795
+ for (const lm of item.interactiveLandmarks) {
1796
+ lines.push(`| ${markdownCodeSpan(lm.role)} | ${markdownCodeSpan(lm.tag)} | ${lm.name ? escapeMarkdownCell(lm.name) : "—"} |`);
1797
+ }
1798
+ lines.push("");
1799
+ }
1800
+ if (item.domAssertions.length > 0) {
1801
+ lines.push("#### DOM Assertions");
1802
+ lines.push("");
1803
+ lines.push("| Selector | Constraint |");
1804
+ lines.push("| --- | --- |");
1805
+ for (const da of item.domAssertions) {
1806
+ lines.push(`| ${markdownCodeSpan(da.selector)} | ${escapeMarkdownCell(da.constraint)} |`);
1807
+ }
1808
+ lines.push("");
1809
+ }
1810
+ if (item.steps.length > 0) {
1811
+ lines.push("#### Flow Steps");
1812
+ lines.push("");
1813
+ lines.push("| # | Action | Target | Detail |");
1814
+ lines.push("| --- | --- | --- | --- |");
1815
+ item.steps.forEach((step, idx) => {
1816
+ lines.push(`| ${idx + 1} | ${markdownCodeSpan(step.action)} | ${step.target ? markdownCodeSpan(step.target) : "—"} | ${step.detail ? escapeMarkdownCell(step.detail) : "—"} |`);
1817
+ });
1818
+ lines.push("");
1819
+ }
1820
+ if (item.networkCalls.length > 0) {
1821
+ lines.push("#### Expected Network Calls");
1822
+ lines.push("");
1823
+ lines.push("| Method | Path | Status | Content-Type |");
1824
+ lines.push("| --- | --- | --- | --- |");
1825
+ for (const nc of item.networkCalls) {
1826
+ lines.push(`| ${markdownCodeSpan(nc.method)} | ${markdownCodeSpan(nc.path)} | ${nc.status !== undefined ? String(nc.status) : "any"} | ${nc.contentType ? markdownCodeSpan(nc.contentType) : "—"} |`);
1827
+ }
1828
+ lines.push("");
1829
+ }
1830
+ }
1831
+ }
1832
+ if (model.includeSkippedComments && model.skippedInvariants.length > 0) {
1833
+ lines.push("## Skipped Invariants");
1834
+ lines.push("");
1835
+ lines.push("| Invariant ID | Reason |");
1836
+ lines.push("| --- | --- |");
1837
+ for (const s of model.skippedInvariants) {
1838
+ lines.push(`| ${markdownCodeSpan(s.id)} | ${escapeMarkdownCell(s.reason)} |`);
1839
+ }
1840
+ lines.push("");
1841
+ }
1842
+ return `${lines.join("\n").trimEnd()}\n`;
1843
+ }
1844
+ function summarizeFieldsInline(fields, maxFields = 10) {
1845
+ if (fields.length === 0)
1846
+ return "";
1847
+ const parts = fields.slice(0, maxFields).map((f) => `${f.path}:${f.type}${f.required ? "" : "?"}`);
1848
+ if (fields.length > maxFields) {
1849
+ parts.push(`+${fields.length - maxFields} more`);
1850
+ }
1851
+ return `{ ${parts.join(", ")} }`;
1852
+ }
1853
+ function renderLlmsTxtDocs(model) {
1854
+ const lines = [];
1855
+ const total = model.http.length + model.cli.length + model.web.length;
1856
+ lines.push(`# ${escapeMarkdownInline(model.title, 160)}`);
1857
+ lines.push("");
1858
+ const summaryParts = [
1859
+ `Contract reference for ${escapeMarkdownInline(model.targetName, 120)}`,
1860
+ `${total} documented contracts (${model.http.length} HTTP, ${model.cli.length} CLI, ${model.web.length} Web)`
1861
+ ];
1862
+ if (model.baseUrl) {
1863
+ summaryParts.push(`Base URL: ${escapeMarkdownInline(model.baseUrl, 200)}`);
1864
+ }
1865
+ if (model.strict) {
1866
+ summaryParts.push("Strict schema validation enabled");
1867
+ }
1868
+ lines.push(`> ${summaryParts.join(". ")}.`);
1869
+ lines.push("");
1870
+ if (total === 0) {
1871
+ lines.push("## Overview");
1872
+ lines.push("");
1873
+ lines.push("- No visible HTTP, CLI, or Web invariants were found in this contract.");
1874
+ lines.push("");
1875
+ }
1876
+ if (model.http.length > 0) {
1877
+ lines.push("## HTTP Endpoints");
1878
+ lines.push("");
1879
+ for (const item of model.http) {
1880
+ const statusText = item.expectedStatuses.length > 0 ? ` [status: ${item.expectedStatuses.join("|")}]` : "";
1881
+ lines.push(`- ${markdownCodeSpan(`${item.method} ${item.pathname}`)}${statusText}: ${escapeMarkdownInline(item.description, 240)}`);
1882
+ if (item.pathParams.length > 0) {
1883
+ lines.push(` - Path params: ${item.pathParams.map((p) => escapeMarkdownInline(p, 80)).join(", ")}`);
1884
+ }
1885
+ if (item.queryParams.length > 0) {
1886
+ lines.push(` - Query params: ${item.queryParams
1887
+ .map(([k, v]) => `${escapeMarkdownInline(k, 80)}=${escapeMarkdownInline(v, 120)}`)
1888
+ .join(", ")}`);
1889
+ }
1890
+ if (item.headers.length > 0) {
1891
+ lines.push(` - Headers: ${item.headers
1892
+ .map(([k, v]) => `${escapeMarkdownInline(k, 80)}: ${escapeMarkdownInline(v, 120)}`)
1893
+ .join("; ")}`);
1894
+ }
1895
+ if (item.requestFields.length > 0) {
1896
+ lines.push(` - Request schema: ${escapeMarkdownInline(summarizeFieldsInline(item.requestFields), 240)}`);
1897
+ }
1898
+ if (item.responseFields.length > 0) {
1899
+ lines.push(` - Response schema: ${escapeMarkdownInline(summarizeFieldsInline(item.responseFields), 240)}`);
1900
+ }
1901
+ if (item.jsonPaths.length > 0) {
1902
+ lines.push(` - Assertions: ${item.jsonPaths
1903
+ .map((j) => `${escapeMarkdownInline(j.path, 120)} ${escapeMarkdownInline(j.matcher, 120)}`)
1904
+ .join("; ")}`);
1905
+ }
1906
+ if (item.maxLatencyMs !== undefined) {
1907
+ lines.push(` - Max latency: ${item.maxLatencyMs}ms`);
1908
+ }
1909
+ }
1910
+ lines.push("");
1911
+ }
1912
+ if (model.cli.length > 0) {
1913
+ lines.push("## CLI Commands");
1914
+ lines.push("");
1915
+ for (const item of model.cli) {
1916
+ const exitText = item.expectedExitCodes.length > 0 ? ` [exit: ${item.expectedExitCodes.join("|")}]` : "";
1917
+ lines.push(`- ${markdownCodeSpan(item.commandPreview)}${exitText}: ${escapeMarkdownInline(item.description, 240)}`);
1918
+ if (item.stdinFields.length > 0) {
1919
+ lines.push(` - Stdin schema: ${escapeMarkdownInline(summarizeFieldsInline(item.stdinFields), 240)}`);
1920
+ }
1921
+ if (item.stdoutFields.length > 0) {
1922
+ lines.push(` - Stdout schema: ${escapeMarkdownInline(summarizeFieldsInline(item.stdoutFields), 240)}`);
1923
+ }
1924
+ if (item.stdoutContains.length > 0) {
1925
+ lines.push(` - Stdout contains: ${item.stdoutContains.map((s) => escapeMarkdownInline(s, 120)).join(", ")}`);
1926
+ }
1927
+ if (item.stderrContains.length > 0) {
1928
+ lines.push(` - Stderr contains: ${item.stderrContains.map((s) => escapeMarkdownInline(s, 120)).join(", ")}`);
1929
+ }
1930
+ }
1931
+ lines.push("");
1932
+ }
1933
+ if (model.web.length > 0) {
1934
+ lines.push("## Web Routes & Flows");
1935
+ lines.push("");
1936
+ for (const item of model.web) {
1937
+ const vpText = item.viewport ? ` [${item.viewport}]` : "";
1938
+ lines.push(`- ${markdownCodeSpan(item.route)} (${item.type})${vpText}: ${escapeMarkdownInline(item.description, 240)}`);
1939
+ if (item.titleContains) {
1940
+ lines.push(` - Title contains: ${escapeMarkdownInline(item.titleContains, 120)}`);
1941
+ }
1942
+ if (item.landmarks.length > 0) {
1943
+ lines.push(` - Landmarks: ${item.landmarks
1944
+ .map((lm) => `${lm.tag}${lm.textContains ? `("${escapeMarkdownInline(lm.textContains, 80)}")` : ""}`)
1945
+ .join(", ")}`);
1946
+ }
1947
+ if (item.steps.length > 0) {
1948
+ lines.push(` - Steps: ${item.steps
1949
+ .map((s) => `${escapeMarkdownInline(s.action, 40)}${s.target ? ` ${escapeMarkdownInline(s.target, 80)}` : ""}`)
1950
+ .join(" -> ")}`);
1951
+ }
1952
+ if (item.networkCalls.length > 0) {
1953
+ lines.push(` - Network: ${item.networkCalls
1954
+ .map((n) => `${n.method} ${escapeMarkdownInline(n.path, 120)}${n.status !== undefined ? ` (${n.status})` : ""}`)
1955
+ .join(", ")}`);
1956
+ }
1957
+ if (item.consoleChecks.length > 0) {
1958
+ lines.push(` - Constraints: ${escapeMarkdownInline(item.consoleChecks.join(", "), 200)}`);
1959
+ }
1960
+ }
1961
+ lines.push("");
1962
+ }
1963
+ if (model.includeSkippedComments && model.skippedInvariants.length > 0) {
1964
+ lines.push("## Optional");
1965
+ lines.push("");
1966
+ for (const s of model.skippedInvariants) {
1967
+ lines.push(`- Skipped ${markdownCodeSpan(s.id)}: ${escapeMarkdownInline(s.reason, 200)}`);
1968
+ }
1969
+ lines.push("");
1970
+ }
1971
+ return `${lines.join("\n").trimEnd()}\n`;
1972
+ }
1973
+ function renderHtmlSchemaTable(fields) {
1974
+ const rows = fields
1975
+ .map((row) => `<tr><td><code>${escapeHtml(row.path)}</code></td><td><code>${escapeHtml(row.type)}</code></td><td>${row.required ? '<span class="badge req">required</span>' : '<span class="badge opt">optional</span>'}</td><td>${row.constraints ? escapeHtml(row.constraints) : '<span class="muted">—</span>'}</td></tr>`)
1976
+ .join("");
1977
+ return `<div class="table-wrap"><table><thead><tr><th>Field</th><th>Type</th><th>Required</th><th>Constraints</th></tr></thead><tbody>${rows}</tbody></table></div>`;
1978
+ }
1979
+ function renderHtmlCodeSnippet(label, code) {
1980
+ return [
1981
+ `<div class="code-box">`,
1982
+ `<div class="code-head"><span>${escapeHtml(label)}</span><button type="button" class="copy-btn" data-copy-btn>Copy</button></div>`,
1983
+ `<pre><code>${escapeHtml(sanitizeText(code))}</code></pre>`,
1984
+ `</div>`
1985
+ ].join("");
1986
+ }
1987
+ function methodBadgeClass(method) {
1988
+ switch (method) {
1989
+ case "GET":
1990
+ return "m-get";
1991
+ case "POST":
1992
+ return "m-post";
1993
+ case "PUT":
1994
+ case "PATCH":
1995
+ return "m-put";
1996
+ case "DELETE":
1997
+ return "m-del";
1998
+ default:
1999
+ return "m-other";
2000
+ }
2001
+ }
2002
+ function renderHtmlPortalDocs(model) {
2003
+ const total = model.http.length + model.cli.length + model.web.length;
2004
+ const safeTitle = escapeHtml(model.title);
2005
+ const safeTarget = escapeHtml(model.targetName);
2006
+ const navItems = [];
2007
+ const cards = [];
2008
+ for (let i = 0; i < model.http.length; i++) {
2009
+ const item = model.http[i];
2010
+ const anchor = `http-${i + 1}`;
2011
+ navItems.push(`<li><a href="#${anchor}" data-nav-domain="http"><span class="badge ${methodBadgeClass(item.method)}">${escapeHtml(item.method)}</span><span class="nav-path">${escapeHtml(item.pathname)}</span></a></li>`);
2012
+ const blocks = [];
2013
+ if (item.pathParams.length > 0) {
2014
+ const pRows = item.pathParams
2015
+ .map((p) => `<tr><td><code>${escapeHtml(p)}</code></td><td><code>string</code></td><td><span class="badge req">required</span></td></tr>`)
2016
+ .join("");
2017
+ blocks.push(`<h4>Path Parameters</h4><div class="table-wrap"><table><thead><tr><th>Name</th><th>Type</th><th>Required</th></tr></thead><tbody>${pRows}</tbody></table></div>`);
2018
+ }
2019
+ if (item.queryParams.length > 0) {
2020
+ const qRows = item.queryParams
2021
+ .map(([k, v]) => `<tr><td><code>${escapeHtml(k)}</code></td><td><code>${escapeHtml(v)}</code></td></tr>`)
2022
+ .join("");
2023
+ blocks.push(`<h4>Query Parameters</h4><div class="table-wrap"><table><thead><tr><th>Name</th><th>Sample Value</th></tr></thead><tbody>${qRows}</tbody></table></div>`);
2024
+ }
2025
+ if (item.headers.length > 0) {
2026
+ const hRows = item.headers
2027
+ .map(([k, v]) => `<tr><td><code>${escapeHtml(k)}</code></td><td><code>${escapeHtml(v)}</code></td></tr>`)
2028
+ .join("");
2029
+ blocks.push(`<h4>Request Headers</h4><div class="table-wrap"><table><thead><tr><th>Header</th><th>Value</th></tr></thead><tbody>${hRows}</tbody></table></div>`);
2030
+ }
2031
+ if (item.requestFields.length > 0) {
2032
+ blocks.push(`<h4>Request Body Schema</h4>${renderHtmlSchemaTable(item.requestFields)}`);
2033
+ }
2034
+ if (item.responseFields.length > 0) {
2035
+ blocks.push(`<h4>Response Schema</h4>${renderHtmlSchemaTable(item.responseFields)}`);
2036
+ }
2037
+ if (item.jsonPaths.length > 0) {
2038
+ const jRows = item.jsonPaths
2039
+ .map((jp) => `<tr><td><code>${escapeHtml(jp.path)}</code></td><td>${escapeHtml(jp.matcher)}</td></tr>`)
2040
+ .join("");
2041
+ blocks.push(`<h4>JSONPath Assertions</h4><div class="table-wrap"><table><thead><tr><th>Path</th><th>Expectation</th></tr></thead><tbody>${jRows}</tbody></table></div>`);
2042
+ }
2043
+ blocks.push(renderHtmlCodeSnippet("cURL Request", item.curlExample));
2044
+ if (item.responseExample !== undefined) {
2045
+ blocks.push(renderHtmlCodeSnippet("Response Example (JSON)", JSON.stringify(item.responseExample, null, 2)));
2046
+ }
2047
+ const statusBadges = item.expectedStatuses.length > 0
2048
+ ? item.expectedStatuses
2049
+ .map((s) => `<span class="badge status">${escapeHtml(String(s))}</span>`)
2050
+ .join("")
2051
+ : "";
2052
+ const latencyBadge = item.maxLatencyMs !== undefined
2053
+ ? `<span class="badge opt">&lt;= ${escapeHtml(String(item.maxLatencyMs))}ms</span>`
2054
+ : "";
2055
+ cards.push(`<article class="card" id="${anchor}" data-domain="http">` +
2056
+ `<div class="card-head"><div class="card-title"><span class="badge ${methodBadgeClass(item.method)}">${escapeHtml(item.method)}</span><code class="endpoint">${escapeHtml(item.pathname)}</code></div><div class="card-meta">${statusBadges}${latencyBadge}<span class="badge sev">${escapeHtml(item.severity)}</span><code class="inv-id">${escapeHtml(item.id)}</code></div></div>` +
2057
+ `<p class="desc">${escapeHtml(item.description)}</p>` +
2058
+ blocks.join("") +
2059
+ `</article>`);
2060
+ }
2061
+ for (let i = 0; i < model.cli.length; i++) {
2062
+ const item = model.cli[i];
2063
+ const anchor = `cli-${i + 1}`;
2064
+ navItems.push(`<li><a href="#${anchor}" data-nav-domain="cli"><span class="badge m-cli">CLI</span><span class="nav-path">${escapeHtml(item.id)}</span></a></li>`);
2065
+ const blocks = [renderHtmlCodeSnippet("Command", item.commandPreview)];
2066
+ if (item.stdinFields.length > 0) {
2067
+ blocks.push(`<h4>Stdin JSON Schema</h4>${renderHtmlSchemaTable(item.stdinFields)}`);
2068
+ }
2069
+ else if (item.stdinPreview) {
2070
+ blocks.push(renderHtmlCodeSnippet("Stdin Example", item.stdinPreview));
2071
+ }
2072
+ if (item.stdoutFields.length > 0) {
2073
+ blocks.push(`<h4>Stdout JSON Schema</h4>${renderHtmlSchemaTable(item.stdoutFields)}`);
2074
+ }
2075
+ if (item.stdoutExample !== undefined) {
2076
+ blocks.push(renderHtmlCodeSnippet("Stdout Example (JSON)", JSON.stringify(item.stdoutExample, null, 2)));
2077
+ }
2078
+ const notes = [];
2079
+ if (item.safeEnvKeys.length > 0)
2080
+ notes.push(`Env keys: ${item.safeEnvKeys.join(", ")}`);
2081
+ if (item.stdoutContains.length > 0)
2082
+ notes.push(`Stdout contains: ${item.stdoutContains.join(" | ")}`);
2083
+ if (item.stdoutNotContains.length > 0)
2084
+ notes.push(`Stdout excludes: ${item.stdoutNotContains.join(" | ")}`);
2085
+ if (item.stderrContains.length > 0)
2086
+ notes.push(`Stderr contains: ${item.stderrContains.join(" | ")}`);
2087
+ if (notes.length > 0) {
2088
+ blocks.push(`<ul class="notes">${notes.map((n) => `<li>${escapeHtml(n)}</li>`).join("")}</ul>`);
2089
+ }
2090
+ const exitBadges = item.expectedExitCodes.length > 0
2091
+ ? item.expectedExitCodes
2092
+ .map((c) => `<span class="badge status">exit ${escapeHtml(String(c))}</span>`)
2093
+ .join("")
2094
+ : `<span class="badge status">exit 0</span>`;
2095
+ cards.push(`<article class="card" id="${anchor}" data-domain="cli">` +
2096
+ `<div class="card-head"><div class="card-title"><span class="badge m-cli">CLI</span><code class="endpoint">${escapeHtml(item.executable)}</code></div><div class="card-meta">${exitBadges}<span class="badge sev">${escapeHtml(item.severity)}</span><code class="inv-id">${escapeHtml(item.id)}</code></div></div>` +
2097
+ `<p class="desc">${escapeHtml(item.description)}</p>` +
2098
+ blocks.join("") +
2099
+ `</article>`);
2100
+ }
2101
+ for (let i = 0; i < model.web.length; i++) {
2102
+ const item = model.web[i];
2103
+ const anchor = `web-${i + 1}`;
2104
+ navItems.push(`<li><a href="#${anchor}" data-nav-domain="web"><span class="badge m-web">WEB</span><span class="nav-path">${escapeHtml(item.route)}</span></a></li>`);
2105
+ const blocks = [];
2106
+ const metaNotes = [];
2107
+ if (item.viewport)
2108
+ metaNotes.push(`Viewport: ${item.viewport}`);
2109
+ if (item.titleContains)
2110
+ metaNotes.push(`Title contains: ${item.titleContains}`);
2111
+ if (item.finalUrlIncludes)
2112
+ metaNotes.push(`Final URL includes: ${item.finalUrlIncludes}`);
2113
+ if (item.consoleChecks.length > 0)
2114
+ metaNotes.push(`Checks: ${item.consoleChecks.join(", ")}`);
2115
+ if (item.visibleText.length > 0)
2116
+ metaNotes.push(`Visible text: ${item.visibleText.join(" | ")}`);
2117
+ if (item.hiddenText.length > 0)
2118
+ metaNotes.push(`Hidden text: ${item.hiddenText.join(" | ")}`);
2119
+ if (metaNotes.length > 0) {
2120
+ blocks.push(`<ul class="notes">${metaNotes.map((n) => `<li>${escapeHtml(n)}</li>`).join("")}</ul>`);
2121
+ }
2122
+ if (item.landmarks.length > 0) {
2123
+ const lRows = item.landmarks
2124
+ .map((lm) => `<tr><td><code>${escapeHtml(lm.tag)}</code></td><td>${lm.required ? '<span class="badge req">required</span>' : '<span class="badge opt">optional</span>'}</td><td>${lm.textContains ? escapeHtml(lm.textContains) : '<span class="muted">—</span>'}</td></tr>`)
2125
+ .join("");
2126
+ blocks.push(`<h4>Landmarks</h4><div class="table-wrap"><table><thead><tr><th>Tag</th><th>Required</th><th>Text Contains</th></tr></thead><tbody>${lRows}</tbody></table></div>`);
2127
+ }
2128
+ if (item.interactiveLandmarks.length > 0) {
2129
+ const ilRows = item.interactiveLandmarks
2130
+ .map((lm) => `<tr><td><code>${escapeHtml(lm.role)}</code></td><td><code>${escapeHtml(lm.tag)}</code></td><td>${lm.name ? escapeHtml(lm.name) : '<span class="muted">—</span>'}</td></tr>`)
2131
+ .join("");
2132
+ blocks.push(`<h4>Interactive Landmarks</h4><div class="table-wrap"><table><thead><tr><th>Role</th><th>Tag</th><th>Name</th></tr></thead><tbody>${ilRows}</tbody></table></div>`);
2133
+ }
2134
+ if (item.steps.length > 0) {
2135
+ const sRows = item.steps
2136
+ .map((s, idx) => `<tr><td>${idx + 1}</td><td><code>${escapeHtml(s.action)}</code></td><td>${s.target ? `<code>${escapeHtml(s.target)}</code>` : '<span class="muted">—</span>'}</td><td>${s.detail ? escapeHtml(s.detail) : '<span class="muted">—</span>'}</td></tr>`)
2137
+ .join("");
2138
+ blocks.push(`<h4>Flow Steps</h4><div class="table-wrap"><table><thead><tr><th>#</th><th>Action</th><th>Target</th><th>Detail</th></tr></thead><tbody>${sRows}</tbody></table></div>`);
2139
+ }
2140
+ if (item.networkCalls.length > 0) {
2141
+ const nRows = item.networkCalls
2142
+ .map((nc) => `<tr><td><code>${escapeHtml(nc.method)}</code></td><td><code>${escapeHtml(nc.path)}</code></td><td>${nc.status !== undefined ? escapeHtml(String(nc.status)) : "any"}</td><td>${nc.contentType ? `<code>${escapeHtml(nc.contentType)}</code>` : '<span class="muted">—</span>'}</td></tr>`)
2143
+ .join("");
2144
+ blocks.push(`<h4>Expected Network Calls</h4><div class="table-wrap"><table><thead><tr><th>Method</th><th>Path</th><th>Status</th><th>Content-Type</th></tr></thead><tbody>${nRows}</tbody></table></div>`);
2145
+ }
2146
+ cards.push(`<article class="card" id="${anchor}" data-domain="web">` +
2147
+ `<div class="card-head"><div class="card-title"><span class="badge m-web">${escapeHtml(item.type)}</span><code class="endpoint">${escapeHtml(item.route)}</code></div><div class="card-meta"><span class="badge sev">${escapeHtml(item.severity)}</span><code class="inv-id">${escapeHtml(item.id)}</code></div></div>` +
2148
+ `<p class="desc">${escapeHtml(item.description)}</p>` +
2149
+ blocks.join("") +
2150
+ `</article>`);
2151
+ }
2152
+ const skippedSection = model.includeSkippedComments && model.skippedInvariants.length > 0
2153
+ ? `<section class="skipped-box"><h3>Skipped Invariants (${model.skippedInvariants.length})</h3><div class="table-wrap"><table><thead><tr><th>ID</th><th>Reason</th></tr></thead><tbody>${model.skippedInvariants
2154
+ .map((s) => `<tr><td><code>${escapeHtml(s.id)}</code></td><td>${escapeHtml(s.reason)}</td></tr>`)
2155
+ .join("")}</tbody></table></div></section>`
2156
+ : "";
2157
+ const baseUrlPill = model.baseUrl
2158
+ ? `<span class="meta-pill">Base URL: <code>${escapeHtml(model.baseUrl)}</code></span>`
2159
+ : "";
2160
+ const strictPill = model.strict
2161
+ ? `<span class="meta-pill">Strict Schemas</span>`
2162
+ : "";
2163
+ const emptyState = total === 0
2164
+ ? `<div class="empty-state">No visible HTTP, CLI, or Web invariants were found in this contract.</div>`
2165
+ : "";
2166
+ return `<!DOCTYPE html>
2167
+ <html lang="en">
2168
+ <head>
2169
+ <meta charset="utf-8">
2170
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2171
+ <meta name="color-scheme" content="dark light">
2172
+ <title>${safeTitle}</title>
2173
+ <style>
2174
+ :root {
2175
+ --bg: #0b0f17;
2176
+ --surface: #111827;
2177
+ --surface-2: #182133;
2178
+ --border: #263248;
2179
+ --text: #e5ecf6;
2180
+ --muted: #93a3bc;
2181
+ --accent: #38bdf8;
2182
+ --accent-soft: rgba(56, 189, 248, 0.14);
2183
+ --get: #22c55e;
2184
+ --post: #38bdf8;
2185
+ --put: #f59e0b;
2186
+ --del: #ef4444;
2187
+ --cli: #a78bfa;
2188
+ --web: #14b8a6;
2189
+ --code-bg: #090d14;
2190
+ --radius: 10px;
2191
+ }
2192
+ :root[data-theme="light"] {
2193
+ --bg: #f6f8fb;
2194
+ --surface: #ffffff;
2195
+ --surface-2: #f0f4f9;
2196
+ --border: #d8e1ec;
2197
+ --text: #0f172a;
2198
+ --muted: #52627a;
2199
+ --accent: #0284c7;
2200
+ --accent-soft: rgba(2, 132, 199, 0.1);
2201
+ --code-bg: #f1f5f9;
2202
+ }
2203
+ @media (prefers-color-scheme: light) {
2204
+ :root:not([data-theme="dark"]) {
2205
+ --bg: #f6f8fb;
2206
+ --surface: #ffffff;
2207
+ --surface-2: #f0f4f9;
2208
+ --border: #d8e1ec;
2209
+ --text: #0f172a;
2210
+ --muted: #52627a;
2211
+ --accent: #0284c7;
2212
+ --accent-soft: rgba(2, 132, 199, 0.1);
2213
+ --code-bg: #f1f5f9;
2214
+ }
2215
+ }
2216
+ * { box-sizing: border-box; }
2217
+ body {
2218
+ margin: 0;
2219
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
2220
+ background: var(--bg);
2221
+ color: var(--text);
2222
+ line-height: 1.55;
2223
+ }
2224
+ code, pre {
2225
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
2226
+ }
2227
+ .topbar {
2228
+ position: sticky;
2229
+ top: 0;
2230
+ z-index: 20;
2231
+ display: flex;
2232
+ flex-wrap: wrap;
2233
+ gap: 12px;
2234
+ align-items: center;
2235
+ justify-content: space-between;
2236
+ padding: 14px 20px;
2237
+ background: var(--surface);
2238
+ border-bottom: 1px solid var(--border);
2239
+ }
2240
+ .brand { display: flex; flex-direction: column; gap: 2px; }
2241
+ .brand h1 { margin: 0; font-size: 1.15rem; letter-spacing: -0.01em; }
2242
+ .brand .sub { font-size: 0.82rem; color: var(--muted); }
2243
+ .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
2244
+ .search-input {
2245
+ min-width: 220px;
2246
+ padding: 7px 11px;
2247
+ border-radius: 8px;
2248
+ border: 1px solid var(--border);
2249
+ background: var(--bg);
2250
+ color: var(--text);
2251
+ font-size: 0.9rem;
2252
+ }
2253
+ .search-input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
2254
+ .filter-btn, .theme-btn, .copy-btn {
2255
+ padding: 6px 11px;
2256
+ border-radius: 8px;
2257
+ border: 1px solid var(--border);
2258
+ background: var(--surface-2);
2259
+ color: var(--text);
2260
+ font-size: 0.82rem;
2261
+ cursor: pointer;
2262
+ }
2263
+ .filter-btn.active {
2264
+ background: var(--accent-soft);
2265
+ border-color: var(--accent);
2266
+ color: var(--accent);
2267
+ font-weight: 600;
2268
+ }
2269
+ .layout {
2270
+ display: grid;
2271
+ grid-template-columns: 260px minmax(0, 1fr);
2272
+ min-height: calc(100vh - 64px);
2273
+ }
2274
+ .sidebar {
2275
+ border-right: 1px solid var(--border);
2276
+ padding: 16px;
2277
+ background: var(--surface);
2278
+ overflow-y: auto;
2279
+ max-height: calc(100vh - 64px);
2280
+ position: sticky;
2281
+ top: 64px;
2282
+ }
2283
+ .sidebar h2 {
2284
+ margin: 0 0 10px 0;
2285
+ font-size: 0.78rem;
2286
+ text-transform: uppercase;
2287
+ letter-spacing: 0.06em;
2288
+ color: var(--muted);
2289
+ }
2290
+ .sidebar ul { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 4px; }
2291
+ .sidebar a {
2292
+ display: flex;
2293
+ align-items: center;
2294
+ gap: 8px;
2295
+ padding: 6px 8px;
2296
+ border-radius: 6px;
2297
+ color: var(--text);
2298
+ text-decoration: none;
2299
+ font-size: 0.84rem;
2300
+ }
2301
+ .sidebar a:hover { background: var(--surface-2); }
2302
+ .nav-path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2303
+ .main { padding: 22px 26px 48px; max-width: 1020px; width: 100%; }
2304
+ .summary-bar {
2305
+ display: flex;
2306
+ flex-wrap: wrap;
2307
+ gap: 8px;
2308
+ margin-bottom: 18px;
2309
+ }
2310
+ .meta-pill {
2311
+ padding: 5px 10px;
2312
+ border-radius: 999px;
2313
+ border: 1px solid var(--border);
2314
+ background: var(--surface);
2315
+ font-size: 0.82rem;
2316
+ color: var(--muted);
2317
+ }
2318
+ .meta-pill strong, .meta-pill code { color: var(--text); }
2319
+ .card {
2320
+ background: var(--surface);
2321
+ border: 1px solid var(--border);
2322
+ border-radius: var(--radius);
2323
+ padding: 18px;
2324
+ margin-bottom: 16px;
2325
+ }
2326
+ .card.hidden { display: none; }
2327
+ .card-head {
2328
+ display: flex;
2329
+ flex-wrap: wrap;
2330
+ align-items: center;
2331
+ justify-content: space-between;
2332
+ gap: 10px;
2333
+ margin-bottom: 8px;
2334
+ }
2335
+ .card-title { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
2336
+ .card-meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
2337
+ .endpoint { font-size: 1rem; font-weight: 600; word-break: break-word; }
2338
+ .inv-id { font-size: 0.78rem; color: var(--muted); }
2339
+ .desc { margin: 6px 0 14px; color: var(--muted); font-size: 0.94rem; }
2340
+ .badge {
2341
+ display: inline-block;
2342
+ padding: 2px 7px;
2343
+ border-radius: 6px;
2344
+ font-size: 0.74rem;
2345
+ font-weight: 700;
2346
+ letter-spacing: 0.02em;
2347
+ }
2348
+ .m-get { background: rgba(34, 197, 94, 0.16); color: var(--get); }
2349
+ .m-post { background: rgba(56, 189, 248, 0.16); color: var(--post); }
2350
+ .m-put { background: rgba(245, 158, 11, 0.16); color: var(--put); }
2351
+ .m-del { background: rgba(239, 68, 68, 0.16); color: var(--del); }
2352
+ .m-other { background: var(--surface-2); color: var(--muted); }
2353
+ .m-cli { background: rgba(167, 139, 250, 0.16); color: var(--cli); }
2354
+ .m-web { background: rgba(20, 184, 166, 0.16); color: var(--web); }
2355
+ .status { background: var(--accent-soft); color: var(--accent); }
2356
+ .sev, .opt { background: var(--surface-2); color: var(--muted); }
2357
+ .req { background: rgba(245, 158, 11, 0.16); color: var(--put); }
2358
+ h4 { margin: 14px 0 8px; font-size: 0.85rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }
2359
+ .table-wrap { overflow-x: auto; margin-bottom: 10px; }
2360
+ table { width: 100%; border-collapse: collapse; font-size: 0.86rem; }
2361
+ th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
2362
+ th { color: var(--muted); font-weight: 600; background: var(--surface-2); }
2363
+ .code-box {
2364
+ margin-top: 10px;
2365
+ border: 1px solid var(--border);
2366
+ border-radius: 8px;
2367
+ overflow: hidden;
2368
+ background: var(--code-bg);
2369
+ }
2370
+ .code-head {
2371
+ display: flex;
2372
+ align-items: center;
2373
+ justify-content: space-between;
2374
+ padding: 6px 10px;
2375
+ border-bottom: 1px solid var(--border);
2376
+ background: var(--surface-2);
2377
+ font-size: 0.78rem;
2378
+ color: var(--muted);
2379
+ }
2380
+ pre { margin: 0; padding: 12px; overflow-x: auto; font-size: 0.84rem; }
2381
+ .notes { margin: 8px 0 0; padding-left: 18px; color: var(--muted); font-size: 0.88rem; }
2382
+ .muted { color: var(--muted); }
2383
+ .empty-state, .skipped-box {
2384
+ padding: 18px;
2385
+ border: 1px dashed var(--border);
2386
+ border-radius: var(--radius);
2387
+ color: var(--muted);
2388
+ margin-top: 16px;
2389
+ }
2390
+ .skipped-box h3 { margin: 0 0 10px; font-size: 0.92rem; color: var(--text); }
2391
+ .no-results { display: none; padding: 18px; border: 1px dashed var(--border); border-radius: var(--radius); color: var(--muted); }
2392
+ @media (max-width: 820px) {
2393
+ .layout { grid-template-columns: 1fr; }
2394
+ .sidebar { display: none; }
2395
+ }
2396
+ </style>
2397
+ </head>
2398
+ <body>
2399
+ <header class="topbar">
2400
+ <div class="brand">
2401
+ <h1>${safeTitle}</h1>
2402
+ <div class="sub">Contract Portal &middot; ${safeTarget}</div>
2403
+ </div>
2404
+ <div class="controls">
2405
+ <input id="docs-search" class="search-input" type="search" placeholder="Filter endpoints, commands, routes..." aria-label="Filter documentation">
2406
+ <button type="button" class="filter-btn active" data-filter="all">All (${total})</button>
2407
+ <button type="button" class="filter-btn" data-filter="http">HTTP (${model.http.length})</button>
2408
+ <button type="button" class="filter-btn" data-filter="cli">CLI (${model.cli.length})</button>
2409
+ <button type="button" class="filter-btn" data-filter="web">Web (${model.web.length})</button>
2410
+ <button type="button" class="theme-btn" id="theme-toggle">Theme</button>
2411
+ </div>
2412
+ </header>
2413
+ <div class="layout">
2414
+ <nav class="sidebar" aria-label="Contract navigation">
2415
+ <h2>Navigation</h2>
2416
+ <ul>${navItems.join("")}</ul>
2417
+ </nav>
2418
+ <main class="main">
2419
+ <div class="summary-bar">
2420
+ <span class="meta-pill">Total: <strong>${total}</strong></span>
2421
+ <span class="meta-pill">HTTP: <strong>${model.http.length}</strong></span>
2422
+ <span class="meta-pill">CLI: <strong>${model.cli.length}</strong></span>
2423
+ <span class="meta-pill">Web: <strong>${model.web.length}</strong></span>
2424
+ ${baseUrlPill}${strictPill}
2425
+ </div>
2426
+ ${emptyState}
2427
+ <div id="no-results" class="no-results">No matching contracts found.</div>
2428
+ <section id="cards-container">${cards.join("")}</section>
2429
+ ${skippedSection}
2430
+ </main>
2431
+ </div>
2432
+ <script>
2433
+ (function () {
2434
+ var searchEl = document.getElementById("docs-search");
2435
+ var filterBtns = document.querySelectorAll("[data-filter]");
2436
+ var cards = document.querySelectorAll(".card");
2437
+ var noResultsEl = document.getElementById("no-results");
2438
+ var themeBtn = document.getElementById("theme-toggle");
2439
+ var activeDomain = "all";
2440
+
2441
+ function applyFilters() {
2442
+ var q = (searchEl && searchEl.value ? searchEl.value : "").trim().toLowerCase();
2443
+ var visible = 0;
2444
+ for (var i = 0; i < cards.length; i++) {
2445
+ var card = cards[i];
2446
+ var domain = card.getAttribute("data-domain") || "";
2447
+ var haystack = (domain + " " + (card.textContent || "")).toLowerCase();
2448
+ var domainOk = activeDomain === "all" || domain === activeDomain;
2449
+ var queryOk = !q || haystack.indexOf(q) !== -1;
2450
+ if (domainOk && queryOk) {
2451
+ card.classList.remove("hidden");
2452
+ visible += 1;
2453
+ } else {
2454
+ card.classList.add("hidden");
2455
+ }
2456
+ }
2457
+ if (noResultsEl) {
2458
+ noResultsEl.style.display = cards.length > 0 && visible === 0 ? "block" : "none";
2459
+ }
2460
+ }
2461
+
2462
+ if (searchEl) {
2463
+ searchEl.addEventListener("input", applyFilters);
2464
+ }
2465
+ for (var b = 0; b < filterBtns.length; b++) {
2466
+ filterBtns[b].addEventListener("click", function (ev) {
2467
+ var btn = ev.currentTarget;
2468
+ activeDomain = btn.getAttribute("data-filter") || "all";
2469
+ for (var j = 0; j < filterBtns.length; j++) {
2470
+ filterBtns[j].classList.remove("active");
2471
+ }
2472
+ btn.classList.add("active");
2473
+ applyFilters();
2474
+ });
2475
+ }
2476
+
2477
+ var copyBtns = document.querySelectorAll("[data-copy-btn]");
2478
+ for (var c = 0; c < copyBtns.length; c++) {
2479
+ copyBtns[c].addEventListener("click", function (ev) {
2480
+ var btn = ev.currentTarget;
2481
+ var box = btn.closest(".code-box");
2482
+ var codeEl = box ? box.querySelector("code") : null;
2483
+ var text = codeEl ? codeEl.textContent || "" : "";
2484
+ if (navigator.clipboard && navigator.clipboard.writeText) {
2485
+ navigator.clipboard.writeText(text).then(function () {
2486
+ btn.textContent = "Copied";
2487
+ setTimeout(function () { btn.textContent = "Copy"; }, 1200);
2488
+ });
2489
+ }
2490
+ });
2491
+ }
2492
+
2493
+ if (themeBtn) {
2494
+ themeBtn.addEventListener("click", function () {
2495
+ var root = document.documentElement;
2496
+ var cur = root.getAttribute("data-theme");
2497
+ root.setAttribute("data-theme", cur === "light" ? "dark" : "light");
2498
+ });
2499
+ }
2500
+ })();
2501
+ </script>
2502
+ </body>
2503
+ </html>
2504
+ `;
2505
+ }
2506
+ // ============================================================================
2507
+ // Public Export, Atomic File Writer, and Terminal Pretty Formatter
2508
+ // ============================================================================
2509
+ function extensionForFormat(format) {
2510
+ switch (format) {
2511
+ case "markdown":
2512
+ return ".md";
2513
+ case "html":
2514
+ return ".html";
2515
+ case "llms-txt":
2516
+ return ".txt";
2517
+ }
2518
+ }
2519
+ /**
2520
+ * Export a ContractV02 into interactive documentation (`markdown`, `html`, or `llms-txt`)
2521
+ * with 100% holdout invisibility and secret/XSS sanitization.
2522
+ */
2523
+ export function exportContractDocs(contract, options = {}) {
2524
+ if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
2525
+ throw new VibecodeError("CONTRACT_INVALID", "exportContractDocs requires a valid contract object with an invariants array.", { fallbackHint: "Load or normalize a ContractV02 object before exporting documentation." });
2526
+ }
2527
+ const formatRaw = options.format ?? "markdown";
2528
+ if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
2529
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported docs export format "${String(formatRaw)}". Supported formats: markdown, html, llms-txt.`, { fallbackHint: 'Pass format: "markdown", "html", or "llms-txt".' });
2530
+ }
2531
+ const format = formatRaw;
2532
+ const strict = options.strict === true;
2533
+ const includeSkippedComments = options.includeSkippedComments !== false;
2534
+ const targetNameRaw = isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()
2535
+ ? contract.target.name.trim()
2536
+ : "Contract Target";
2537
+ const targetName = sanitizeSingleLineText(targetNameRaw, 120) || "Contract Target";
2538
+ const titleRaw = typeof options.title === "string" && options.title.trim()
2539
+ ? options.title.trim()
2540
+ : `${targetName} Documentation`;
2541
+ const title = sanitizeSingleLineText(titleRaw, 160) || "Contract Documentation";
2542
+ const baseUrl = resolveBaseUrl(contract, options);
2543
+ const http = [];
2544
+ const cli = [];
2545
+ const web = [];
2546
+ const skippedInvariants = [];
2547
+ const warnings = [];
2548
+ for (const inv of contract.invariants) {
2549
+ if (!isRecord(inv))
2550
+ continue;
2551
+ // 100% Holdout Invisibility: never emit holdout IDs, routes, flags, counts, comments, or warnings.
2552
+ if (inv.holdout === true) {
2553
+ continue;
2554
+ }
2555
+ const invId = typeof inv.id === "string" && inv.id.trim()
2556
+ ? sanitizeSingleLineText(inv.id.trim(), 80)
2557
+ : "unknown";
2558
+ if (inv.type === "http") {
2559
+ const normalized = normalizeHttpInvariant(inv, invId, baseUrl, strict, warnings);
2560
+ if (!normalized) {
2561
+ skippedInvariants.push({
2562
+ id: invId,
2563
+ reason: "Unsupported HTTP method"
2564
+ });
2565
+ warnings.push(`Skipped HTTP invariant "${invId}" due to unsupported HTTP method.`);
2566
+ }
2567
+ else {
2568
+ http.push(normalized);
2569
+ }
2570
+ continue;
2571
+ }
2572
+ if (inv.type === "command") {
2573
+ cli.push(normalizeCliInvariant(inv, invId, contract, strict, warnings));
2574
+ continue;
2575
+ }
2576
+ if (typeof inv.type === "string" && WEB_INVARIANT_TYPES.has(inv.type)) {
2577
+ web.push(normalizeWebInvariant(inv, invId, strict, warnings));
2578
+ continue;
2579
+ }
2580
+ const safeType = sanitizeSingleLineText(String(inv.type ?? "unknown"), 48) || "unknown";
2581
+ skippedInvariants.push({
2582
+ id: invId,
2583
+ reason: `Unsupported invariant type "${safeType}"`
2584
+ });
2585
+ }
2586
+ const documentedCount = http.length + cli.length + web.length;
2587
+ if (documentedCount === 0) {
2588
+ warnings.push("No visible HTTP, CLI, or Web invariants were found to document.");
2589
+ }
2590
+ const dedupedWarnings = [...new Set(warnings)];
2591
+ const model = {
2592
+ title,
2593
+ targetName,
2594
+ ...(baseUrl ? { baseUrl } : {}),
2595
+ strict,
2596
+ http,
2597
+ cli,
2598
+ web,
2599
+ skippedInvariants,
2600
+ warnings: dedupedWarnings,
2601
+ includeSkippedComments
2602
+ };
2603
+ let content;
2604
+ if (format === "html") {
2605
+ content = renderHtmlPortalDocs(model);
2606
+ }
2607
+ else if (format === "llms-txt") {
2608
+ content = renderLlmsTxtDocs(model);
2609
+ }
2610
+ else {
2611
+ content = renderMarkdownDocs(model);
2612
+ }
2613
+ return {
2614
+ format,
2615
+ content,
2616
+ fileExtension: extensionForFormat(format),
2617
+ documentedCount,
2618
+ httpCount: http.length,
2619
+ cliCount: cli.length,
2620
+ webCount: web.length,
2621
+ skippedInvariants,
2622
+ warnings: dedupedWarnings
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Generate and atomically write contract documentation to disk via temp file + rename.
2627
+ */
2628
+ export function writeContractDocs(contract, outPath, options = {}) {
2629
+ if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
2630
+ throw new VibecodeError("CONTRACT_INVALID", "writeContractDocs requires a valid non-empty outPath without NUL bytes.", { fallbackHint: "Pass a file path such as ./docs/api.md or ./docs/portal.html." });
2631
+ }
2632
+ const resolvedOut = path.resolve(outPath.trim());
2633
+ if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
2634
+ throw new VibecodeError("CONTRACT_INVALID", `Cannot write documentation: "${resolvedOut}" is a directory.`, { fallbackHint: "Pass a file path (for example `./docs/portal.html`), not a directory." });
2635
+ }
2636
+ const result = exportContractDocs(contract, options);
2637
+ const parentDir = path.dirname(resolvedOut);
2638
+ fs.mkdirSync(parentDir, { recursive: true });
2639
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
2640
+ try {
2641
+ fs.writeFileSync(tmpPath, result.content, "utf8");
2642
+ fs.renameSync(tmpPath, resolvedOut);
2643
+ }
2644
+ catch (err) {
2645
+ try {
2646
+ if (fs.existsSync(tmpPath)) {
2647
+ fs.rmSync(tmpPath, { force: true });
2648
+ }
2649
+ }
2650
+ catch {
2651
+ // ignore cleanup error
2652
+ }
2653
+ throw err;
2654
+ }
2655
+ return {
2656
+ ...result,
2657
+ outPath: resolvedOut
2658
+ };
2659
+ }
2660
+ function style(text, codes, useColor) {
2661
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
2662
+ }
2663
+ /**
2664
+ * Format a concise, sanitized terminal summary for a documentation export result.
2665
+ */
2666
+ export function formatPrettyDocsExport(result, outPath, color = false) {
2667
+ const useColor = color === true;
2668
+ const lines = [];
2669
+ const banner = style("[DOCS EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
2670
+ const fmtLabel = result.format === "html"
2671
+ ? "HTML Portal"
2672
+ : result.format === "llms-txt"
2673
+ ? "llms.txt"
2674
+ : "Markdown";
2675
+ const safeExt = sanitizeSingleLineText(result.fileExtension || "", 16);
2676
+ lines.push(`${banner} ${style(fmtLabel, ANSI.bold, useColor)} (${safeExt})`);
2677
+ const effectiveOut = (typeof outPath === "string" && outPath.trim()) ||
2678
+ (typeof result.outPath === "string" && result.outPath.trim()) ||
2679
+ "";
2680
+ if (effectiveOut) {
2681
+ lines.push(`Output: ${sanitizeSingleLineText(effectiveOut, 240)}`);
2682
+ }
2683
+ const totalBytes = Buffer.byteLength(result.content || "", "utf8");
2684
+ const docCountStr = style(`${result.documentedCount} ${result.documentedCount === 1 ? "contract" : "contracts"}`, result.documentedCount > 0 ? ANSI.green : ANSI.yellow, useColor);
2685
+ const summaryParts = [
2686
+ docCountStr,
2687
+ `${result.httpCount} HTTP`,
2688
+ `${result.cliCount} CLI`,
2689
+ `${result.webCount} Web`
2690
+ ];
2691
+ if (Array.isArray(result.skippedInvariants) && result.skippedInvariants.length > 0) {
2692
+ summaryParts.push(`${result.skippedInvariants.length} skipped`);
2693
+ }
2694
+ summaryParts.push(`${totalBytes} bytes`);
2695
+ lines.push(`Summary: ${summaryParts.join(", ")}`);
2696
+ if (Array.isArray(result.warnings) && result.warnings.length > 0) {
2697
+ lines.push("Warnings:");
2698
+ for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
2699
+ lines.push(` - ${style(sanitizeSingleLineText(warning, 200), ANSI.yellow, useColor)}`);
2700
+ }
2701
+ if (result.warnings.length > MAX_PRETTY_WARNINGS) {
2702
+ lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
2703
+ }
2704
+ }
2705
+ return lines.join("\n");
2706
+ }