vibecode-anything 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,2245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency declarative stateful fixture & guaranteed rollback engine.
|
|
3
|
+
*
|
|
4
|
+
* Supports workspace file seeding (UTF-8 / base64), recursive workspace snapshots
|
|
5
|
+
* with anti-symlink-swap rollback, relative-origin HTTP setup/teardown hooks
|
|
6
|
+
* (with runtime `{{vars.NAME}}` interpolation, manual redirects, and timeouts),
|
|
7
|
+
* and opt-in shell-free command setup/teardown hooks.
|
|
8
|
+
*/
|
|
9
|
+
import { execFileSync } from "node:child_process";
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { VibecodeError, errorMessage } from "./errors.js";
|
|
14
|
+
import { ANSI, HEADER_VALUE_UNSAFE_RE, HTTP_HEADER_NAME_RE, STRICT_CONTROL_CHARS_RE, USERINFO_IN_FIRST_SEG_RE, VALID_DOMAINS, collectHeaderSecrets, collectSecretValue, defineOwnProp, hasVaultOrHoldoutSegment, isForbiddenObjectKey, isInsideVaultDirectory, isPathWithinDir, isSecretRelativePath, isSensitiveHeaderName, isSensitiveKeyName, redactSensitiveText, safeReadArray, safeReadPlainObject, sanitizeSingleLine, stripTerminalEscapes, styleAnsi, validateOriginRelativePath, validateSafeWorkspaceRelPath } from "./security.js";
|
|
15
|
+
import { redactRuntimeVars, resolveTargetForInvariant } from "./target-map.js";
|
|
16
|
+
export { isSensitiveHeaderName };
|
|
17
|
+
export const MAX_FIXTURE_SEED_FILES = 50;
|
|
18
|
+
export const MAX_FIXTURE_SEED_BYTES = 1024 * 1024;
|
|
19
|
+
export const MAX_FIXTURE_SNAPSHOT_PATHS = 50;
|
|
20
|
+
export const MAX_FIXTURE_SNAPSHOT_FILES = 200;
|
|
21
|
+
export const MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES = 10 * 1024 * 1024;
|
|
22
|
+
export const MAX_FIXTURE_HOOKS = 20;
|
|
23
|
+
export const DEFAULT_FIXTURE_HOOK_TIMEOUT_MS = 10_000;
|
|
24
|
+
export const MAX_FIXTURE_HOOK_TIMEOUT_MS = 30_000;
|
|
25
|
+
const MIN_FIXTURE_HOOK_TIMEOUT_MS = 50;
|
|
26
|
+
const MAX_SNAPSHOT_DEPTH = 16;
|
|
27
|
+
const MAX_REMOVE_DEPTH = 32;
|
|
28
|
+
const MAX_JSON_BODY_DEPTH = 32;
|
|
29
|
+
const MAX_HTTP_HOOK_PATH_CHARS = 4096;
|
|
30
|
+
const MAX_HTTP_HOOK_HEADERS = 64;
|
|
31
|
+
const MAX_HTTP_HOOK_BODY_BYTES = 1024 * 1024;
|
|
32
|
+
const MAX_HTTP_ERROR_BODY_READ_BYTES = 16 * 1024;
|
|
33
|
+
const MAX_HTTP_EXPECT_STATUS_LIST = 20;
|
|
34
|
+
const MAX_COMMAND_LEN = 1024;
|
|
35
|
+
const MAX_COMMAND_ARGS = 64;
|
|
36
|
+
const MAX_COMMAND_ARG_CHARS = 8192;
|
|
37
|
+
const MAX_COMMAND_ENV_VARS = 64;
|
|
38
|
+
const MAX_COMMAND_ENV_VAL_CHARS = 16_384;
|
|
39
|
+
const MAX_COMMAND_OUTPUT_BYTES = 2 * 1024 * 1024;
|
|
40
|
+
const MAX_PRETTY_RECORDS = 25;
|
|
41
|
+
const MAX_PRETTY_WARNINGS = 15;
|
|
42
|
+
const ALLOWED_TOP_LEVEL_KEYS = new Set([
|
|
43
|
+
"seedFiles",
|
|
44
|
+
"snapshotPaths",
|
|
45
|
+
"httpSetup",
|
|
46
|
+
"httpTeardown",
|
|
47
|
+
"commandSetup",
|
|
48
|
+
"commandTeardown"
|
|
49
|
+
]);
|
|
50
|
+
const ALLOWED_SEED_KEYS = new Set(["path", "content", "encoding"]);
|
|
51
|
+
const ALLOWED_HTTP_HOOK_KEYS = new Set([
|
|
52
|
+
"method",
|
|
53
|
+
"path",
|
|
54
|
+
"headers",
|
|
55
|
+
"body",
|
|
56
|
+
"expectStatus",
|
|
57
|
+
"timeoutMs",
|
|
58
|
+
"targetDomain"
|
|
59
|
+
]);
|
|
60
|
+
const ALLOWED_COMMAND_HOOK_KEYS = new Set([
|
|
61
|
+
"command",
|
|
62
|
+
"args",
|
|
63
|
+
"env",
|
|
64
|
+
"timeoutMs",
|
|
65
|
+
"expectExitCode"
|
|
66
|
+
]);
|
|
67
|
+
const VALID_HTTP_METHODS = new Set([
|
|
68
|
+
"GET",
|
|
69
|
+
"POST",
|
|
70
|
+
"PUT",
|
|
71
|
+
"PATCH",
|
|
72
|
+
"DELETE",
|
|
73
|
+
"HEAD",
|
|
74
|
+
"OPTIONS"
|
|
75
|
+
]);
|
|
76
|
+
const FORBIDDEN_FIXTURE_SEGMENTS = new Set([
|
|
77
|
+
".vibecode",
|
|
78
|
+
".git",
|
|
79
|
+
"node_modules",
|
|
80
|
+
".vibecode-vault"
|
|
81
|
+
]);
|
|
82
|
+
const BASE64_STRICT_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
83
|
+
const VAR_PLACEHOLDER_RE = /\{\{\s*vars\.([A-Za-z_][A-Za-z0-9_.-]{0,63})\s*\}\}/g;
|
|
84
|
+
const HAS_VAR_PLACEHOLDER_RE = /\{\{\s*vars\.[A-Za-z_][A-Za-z0-9_.-]{0,63}\s*\}\}/;
|
|
85
|
+
const COMMAND_SHELL_METACHAR_RE = /[;&|`$<>]/;
|
|
86
|
+
function configError(message, details) {
|
|
87
|
+
return new VibecodeError("CONFIG_INVALID", sanitizeSingleLine(message, 400), details !== undefined ? { details } : {});
|
|
88
|
+
}
|
|
89
|
+
function compareStrings(a, b) {
|
|
90
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
91
|
+
}
|
|
92
|
+
function isSamePath(a, b) {
|
|
93
|
+
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
94
|
+
}
|
|
95
|
+
function canonicalRelKey(rel) {
|
|
96
|
+
return process.platform === "win32" ? rel.toLowerCase() : rel;
|
|
97
|
+
}
|
|
98
|
+
function readPlainEntries(raw, label, errors) {
|
|
99
|
+
const res = safeReadPlainObject(raw, label, { forbiddenKeyPolicy: "reject", includeNonEnumerable: true });
|
|
100
|
+
if (!res.ok) {
|
|
101
|
+
errors.push(res.error);
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
return res.entries;
|
|
105
|
+
}
|
|
106
|
+
function readArrayItems(raw, label, maxItems, errors) {
|
|
107
|
+
const res = safeReadArray(raw, label, maxItems);
|
|
108
|
+
if (!res.ok) {
|
|
109
|
+
errors.push(res.error);
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
return res.items;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Deeply validates and clones an arbitrary JSON-compatible value via descriptor-only reads.
|
|
116
|
+
*/
|
|
117
|
+
function safeCloneJsonValue(raw, label, errors, depth = 0, ancestors = new WeakSet()) {
|
|
118
|
+
if (depth > MAX_JSON_BODY_DEPTH) {
|
|
119
|
+
errors.push(`${label}: exceeds maximum nesting depth of ${MAX_JSON_BODY_DEPTH}.`);
|
|
120
|
+
return { ok: false, value: undefined };
|
|
121
|
+
}
|
|
122
|
+
if (raw === null || typeof raw === "string" || typeof raw === "boolean") {
|
|
123
|
+
return { ok: true, value: raw };
|
|
124
|
+
}
|
|
125
|
+
if (typeof raw === "number") {
|
|
126
|
+
if (!Number.isFinite(raw)) {
|
|
127
|
+
errors.push(`${label}: numeric values must be finite.`);
|
|
128
|
+
return { ok: false, value: undefined };
|
|
129
|
+
}
|
|
130
|
+
return { ok: true, value: raw };
|
|
131
|
+
}
|
|
132
|
+
if (typeof raw !== "object") {
|
|
133
|
+
errors.push(`${label}: unsupported JSON value type "${typeof raw}".`);
|
|
134
|
+
return { ok: false, value: undefined };
|
|
135
|
+
}
|
|
136
|
+
let isArr = false;
|
|
137
|
+
try {
|
|
138
|
+
isArr = Array.isArray(raw);
|
|
139
|
+
if (ancestors.has(raw)) {
|
|
140
|
+
errors.push(`${label}: circular reference is not allowed.`);
|
|
141
|
+
return { ok: false, value: undefined };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
errors.push(`${label}: value could not be inspected safely (${sanitizeSingleLine(errorMessage(err), 160)}).`);
|
|
146
|
+
return { ok: false, value: undefined };
|
|
147
|
+
}
|
|
148
|
+
ancestors.add(raw);
|
|
149
|
+
try {
|
|
150
|
+
if (isArr) {
|
|
151
|
+
const items = readArrayItems(raw, label, 10_000, errors);
|
|
152
|
+
if (!items)
|
|
153
|
+
return { ok: false, value: undefined };
|
|
154
|
+
const out = [];
|
|
155
|
+
for (let i = 0; i < items.length; i++) {
|
|
156
|
+
const cloned = safeCloneJsonValue(items[i], `${label}[${i}]`, errors, depth + 1, ancestors);
|
|
157
|
+
if (!cloned.ok)
|
|
158
|
+
return { ok: false, value: undefined };
|
|
159
|
+
out.push(cloned.value);
|
|
160
|
+
}
|
|
161
|
+
return { ok: true, value: out };
|
|
162
|
+
}
|
|
163
|
+
const entries = readPlainEntries(raw, label, errors);
|
|
164
|
+
if (!entries)
|
|
165
|
+
return { ok: false, value: undefined };
|
|
166
|
+
const out = {};
|
|
167
|
+
for (const [k, v] of entries) {
|
|
168
|
+
if (v === undefined)
|
|
169
|
+
continue;
|
|
170
|
+
const cloned = safeCloneJsonValue(v, `${label}.${sanitizeSingleLine(k, 64)}`, errors, depth + 1, ancestors);
|
|
171
|
+
if (!cloned.ok)
|
|
172
|
+
return { ok: false, value: undefined };
|
|
173
|
+
defineOwnProp(out, k, cloned.value);
|
|
174
|
+
}
|
|
175
|
+
return { ok: true, value: out };
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
ancestors.delete(raw);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function validateFixtureRelPath(raw, label, errors) {
|
|
182
|
+
const res = validateSafeWorkspaceRelPath(raw, {
|
|
183
|
+
label,
|
|
184
|
+
forbiddenSegments: FORBIDDEN_FIXTURE_SEGMENTS
|
|
185
|
+
});
|
|
186
|
+
if (!res.ok) {
|
|
187
|
+
errors.push(res.error);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
return res.relPath;
|
|
191
|
+
}
|
|
192
|
+
function validateHttpHookPath(raw, label, errors) {
|
|
193
|
+
const res = validateOriginRelativePath(raw, label, {
|
|
194
|
+
maxLength: MAX_HTTP_HOOK_PATH_CHARS,
|
|
195
|
+
allowVarPlaceholders: true,
|
|
196
|
+
varPlaceholderRe: VAR_PLACEHOLDER_RE
|
|
197
|
+
});
|
|
198
|
+
if (!res.ok) {
|
|
199
|
+
errors.push(res.error);
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
return res.path;
|
|
203
|
+
}
|
|
204
|
+
function validateTimeoutMs(raw, label, errors) {
|
|
205
|
+
if (raw === undefined)
|
|
206
|
+
return undefined;
|
|
207
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) {
|
|
208
|
+
errors.push(`${label}: timeoutMs must be a finite number.`);
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
const value = Math.floor(raw);
|
|
212
|
+
if (value < MIN_FIXTURE_HOOK_TIMEOUT_MS || value > MAX_FIXTURE_HOOK_TIMEOUT_MS) {
|
|
213
|
+
errors.push(`${label}: timeoutMs must be between ${MIN_FIXTURE_HOOK_TIMEOUT_MS} and ${MAX_FIXTURE_HOOK_TIMEOUT_MS} (got ${raw}).`);
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
return value;
|
|
217
|
+
}
|
|
218
|
+
function validateHeadersObject(raw, label, errors, warnings) {
|
|
219
|
+
if (raw === undefined)
|
|
220
|
+
return undefined;
|
|
221
|
+
const entries = readPlainEntries(raw, label, errors);
|
|
222
|
+
if (!entries)
|
|
223
|
+
return undefined;
|
|
224
|
+
if (entries.size > MAX_HTTP_HOOK_HEADERS) {
|
|
225
|
+
errors.push(`${label}: exceeds maximum of ${MAX_HTTP_HOOK_HEADERS} headers.`);
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
const out = {};
|
|
229
|
+
for (const [rawKey, rawVal] of entries) {
|
|
230
|
+
const name = rawKey.trim();
|
|
231
|
+
if (!name || STRICT_CONTROL_CHARS_RE.test(rawKey) || !HTTP_HEADER_NAME_RE.test(name)) {
|
|
232
|
+
errors.push(`${label}: invalid HTTP header name ${JSON.stringify(sanitizeSingleLine(rawKey, 64))}.`);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (typeof rawVal !== "string") {
|
|
236
|
+
errors.push(`${label}[${JSON.stringify(name)}]: header value must be a string.`);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (HEADER_VALUE_UNSAFE_RE.test(rawVal)) {
|
|
240
|
+
errors.push(`${label}[${JSON.stringify(name)}]: header value must not contain CRLF or control characters.`);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (isSensitiveHeaderName(name) && rawVal.trim().length > 0 && !HAS_VAR_PLACEHOLDER_RE.test(rawVal)) {
|
|
244
|
+
warnings.push(`${label}[${JSON.stringify(name)}]: sensitive header uses a literal value; prefer "{{vars.NAME}}" to avoid embedding secrets in contracts.`);
|
|
245
|
+
}
|
|
246
|
+
defineOwnProp(out, name, rawVal);
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
function validateHttpHooks(raw, label, errors, warnings) {
|
|
251
|
+
if (raw === undefined)
|
|
252
|
+
return undefined;
|
|
253
|
+
const items = readArrayItems(raw, label, MAX_FIXTURE_HOOKS, errors);
|
|
254
|
+
if (!items)
|
|
255
|
+
return undefined;
|
|
256
|
+
const normalized = [];
|
|
257
|
+
for (let i = 0; i < items.length; i++) {
|
|
258
|
+
const itemLabel = `${label}[${i}]`;
|
|
259
|
+
const entries = readPlainEntries(items[i], itemLabel, errors);
|
|
260
|
+
if (!entries)
|
|
261
|
+
continue;
|
|
262
|
+
for (const key of entries.keys()) {
|
|
263
|
+
if (!ALLOWED_HTTP_HOOK_KEYS.has(key)) {
|
|
264
|
+
errors.push(`${itemLabel}: unknown property ${JSON.stringify(sanitizeSingleLine(key, 64))}.`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const rawMethod = entries.get("method");
|
|
268
|
+
let method = "";
|
|
269
|
+
if (typeof rawMethod !== "string" || !rawMethod.trim()) {
|
|
270
|
+
errors.push(`${itemLabel}.method: must be a valid HTTP verb.`);
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
const upper = rawMethod.trim().toUpperCase();
|
|
274
|
+
if (!VALID_HTTP_METHODS.has(upper)) {
|
|
275
|
+
errors.push(`${itemLabel}.method: unsupported HTTP verb ${JSON.stringify(sanitizeSingleLine(rawMethod, 32))}; expected one of ${[...VALID_HTTP_METHODS].join(", ")}.`);
|
|
276
|
+
}
|
|
277
|
+
else {
|
|
278
|
+
method = upper;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const hookPath = validateHttpHookPath(entries.get("path"), `${itemLabel}.path`, errors);
|
|
282
|
+
const headers = validateHeadersObject(entries.get("headers"), `${itemLabel}.headers`, errors, warnings);
|
|
283
|
+
let body = undefined;
|
|
284
|
+
if (entries.has("body") && entries.get("body") !== undefined) {
|
|
285
|
+
const rawBody = entries.get("body");
|
|
286
|
+
if (typeof rawBody === "string") {
|
|
287
|
+
if (Buffer.byteLength(rawBody, "utf8") > MAX_HTTP_HOOK_BODY_BYTES) {
|
|
288
|
+
errors.push(`${itemLabel}.body: exceeds maximum size of ${MAX_HTTP_HOOK_BODY_BYTES} bytes.`);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
body = rawBody;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
const cloned = safeCloneJsonValue(rawBody, `${itemLabel}.body`, errors);
|
|
296
|
+
if (cloned.ok) {
|
|
297
|
+
let serialized = "";
|
|
298
|
+
try {
|
|
299
|
+
serialized = JSON.stringify(cloned.value) ?? "";
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
errors.push(`${itemLabel}.body: must be JSON-serializable.`);
|
|
303
|
+
}
|
|
304
|
+
if (Buffer.byteLength(serialized, "utf8") > MAX_HTTP_HOOK_BODY_BYTES) {
|
|
305
|
+
errors.push(`${itemLabel}.body: exceeds maximum size of ${MAX_HTTP_HOOK_BODY_BYTES} bytes.`);
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
body = cloned.value;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
let expectStatus;
|
|
314
|
+
if (entries.has("expectStatus") && entries.get("expectStatus") !== undefined) {
|
|
315
|
+
const rawExpect = entries.get("expectStatus");
|
|
316
|
+
if (typeof rawExpect === "number") {
|
|
317
|
+
if (!Number.isInteger(rawExpect) || rawExpect < 100 || rawExpect > 599) {
|
|
318
|
+
errors.push(`${itemLabel}.expectStatus: HTTP status must be an integer in 100..599.`);
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
expectStatus = rawExpect;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
else if (Array.isArray(rawExpect)) {
|
|
325
|
+
const statusItems = readArrayItems(rawExpect, `${itemLabel}.expectStatus`, MAX_HTTP_EXPECT_STATUS_LIST, errors);
|
|
326
|
+
if (statusItems) {
|
|
327
|
+
if (statusItems.length === 0) {
|
|
328
|
+
errors.push(`${itemLabel}.expectStatus: array must not be empty.`);
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
const list = [];
|
|
332
|
+
for (let j = 0; j < statusItems.length; j++) {
|
|
333
|
+
const s = statusItems[j];
|
|
334
|
+
if (typeof s !== "number" || !Number.isInteger(s) || s < 100 || s > 599) {
|
|
335
|
+
errors.push(`${itemLabel}.expectStatus[${j}]: HTTP status must be an integer in 100..599.`);
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
list.push(s);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
expectStatus = list;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
errors.push(`${itemLabel}.expectStatus: must be an HTTP status integer or array of integers.`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const timeoutMs = validateTimeoutMs(entries.get("timeoutMs"), `${itemLabel}.timeoutMs`, errors);
|
|
350
|
+
let targetDomain;
|
|
351
|
+
if (entries.has("targetDomain") && entries.get("targetDomain") !== undefined) {
|
|
352
|
+
const rawDom = entries.get("targetDomain");
|
|
353
|
+
if (typeof rawDom !== "string" || isForbiddenObjectKey(rawDom) || !VALID_DOMAINS.has(rawDom.trim())) {
|
|
354
|
+
errors.push(`${itemLabel}.targetDomain: invalid domain ${JSON.stringify(sanitizeSingleLine(String(rawDom), 32))}; expected one of ${[...VALID_DOMAINS].join(", ")}.`);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
targetDomain = rawDom.trim();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (method && hookPath) {
|
|
361
|
+
const hook = { method, path: hookPath };
|
|
362
|
+
if (headers !== undefined)
|
|
363
|
+
hook.headers = headers;
|
|
364
|
+
if (body !== undefined)
|
|
365
|
+
hook.body = body;
|
|
366
|
+
if (expectStatus !== undefined)
|
|
367
|
+
hook.expectStatus = expectStatus;
|
|
368
|
+
if (timeoutMs !== undefined)
|
|
369
|
+
hook.timeoutMs = timeoutMs;
|
|
370
|
+
if (targetDomain !== undefined)
|
|
371
|
+
hook.targetDomain = targetDomain;
|
|
372
|
+
normalized.push(hook);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return normalized;
|
|
376
|
+
}
|
|
377
|
+
function validateCommandHooks(raw, label, errors) {
|
|
378
|
+
if (raw === undefined)
|
|
379
|
+
return undefined;
|
|
380
|
+
const items = readArrayItems(raw, label, MAX_FIXTURE_HOOKS, errors);
|
|
381
|
+
if (!items)
|
|
382
|
+
return undefined;
|
|
383
|
+
const normalized = [];
|
|
384
|
+
for (let i = 0; i < items.length; i++) {
|
|
385
|
+
const itemLabel = `${label}[${i}]`;
|
|
386
|
+
const entries = readPlainEntries(items[i], itemLabel, errors);
|
|
387
|
+
if (!entries)
|
|
388
|
+
continue;
|
|
389
|
+
for (const key of entries.keys()) {
|
|
390
|
+
if (!ALLOWED_COMMAND_HOOK_KEYS.has(key)) {
|
|
391
|
+
errors.push(`${itemLabel}: unknown property ${JSON.stringify(sanitizeSingleLine(key, 64))}.`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const rawCmd = entries.get("command");
|
|
395
|
+
let command = "";
|
|
396
|
+
if (typeof rawCmd !== "string" || !rawCmd.trim()) {
|
|
397
|
+
errors.push(`${itemLabel}.command: must be a non-empty string.`);
|
|
398
|
+
}
|
|
399
|
+
else if (STRICT_CONTROL_CHARS_RE.test(rawCmd)) {
|
|
400
|
+
errors.push(`${itemLabel}.command: must not contain NUL, CRLF, or control characters.`);
|
|
401
|
+
}
|
|
402
|
+
else if (COMMAND_SHELL_METACHAR_RE.test(rawCmd)) {
|
|
403
|
+
errors.push(`${itemLabel}.command: must not contain shell metacharacters.`);
|
|
404
|
+
}
|
|
405
|
+
else if (rawCmd.trim().length > MAX_COMMAND_LEN) {
|
|
406
|
+
errors.push(`${itemLabel}.command: exceeds maximum length of ${MAX_COMMAND_LEN} characters.`);
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
command = rawCmd.trim();
|
|
410
|
+
}
|
|
411
|
+
let args;
|
|
412
|
+
if (entries.has("args") && entries.get("args") !== undefined) {
|
|
413
|
+
const rawArgs = readArrayItems(entries.get("args"), `${itemLabel}.args`, MAX_COMMAND_ARGS, errors);
|
|
414
|
+
if (rawArgs) {
|
|
415
|
+
args = [];
|
|
416
|
+
for (let j = 0; j < rawArgs.length; j++) {
|
|
417
|
+
const arg = rawArgs[j];
|
|
418
|
+
if (typeof arg !== "string") {
|
|
419
|
+
errors.push(`${itemLabel}.args[${j}]: must be a string.`);
|
|
420
|
+
}
|
|
421
|
+
else if (arg.includes("\0")) {
|
|
422
|
+
errors.push(`${itemLabel}.args[${j}]: NUL bytes are not allowed.`);
|
|
423
|
+
}
|
|
424
|
+
else if (arg.length > MAX_COMMAND_ARG_CHARS) {
|
|
425
|
+
errors.push(`${itemLabel}.args[${j}]: exceeds maximum length of ${MAX_COMMAND_ARG_CHARS} characters.`);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
args.push(arg);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
let env;
|
|
434
|
+
if (entries.has("env") && entries.get("env") !== undefined) {
|
|
435
|
+
const envEntries = readPlainEntries(entries.get("env"), `${itemLabel}.env`, errors);
|
|
436
|
+
if (envEntries) {
|
|
437
|
+
if (envEntries.size > MAX_COMMAND_ENV_VARS) {
|
|
438
|
+
errors.push(`${itemLabel}.env: exceeds maximum of ${MAX_COMMAND_ENV_VARS} variables.`);
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
env = {};
|
|
442
|
+
for (const [k, v] of envEntries) {
|
|
443
|
+
if (!k || k.includes("=") || STRICT_CONTROL_CHARS_RE.test(k)) {
|
|
444
|
+
errors.push(`${itemLabel}.env: invalid variable name ${JSON.stringify(sanitizeSingleLine(k, 64))}.`);
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
if (typeof v !== "string") {
|
|
448
|
+
errors.push(`${itemLabel}.env[${JSON.stringify(k)}]: value must be a string.`);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (v.includes("\0")) {
|
|
452
|
+
errors.push(`${itemLabel}.env[${JSON.stringify(k)}]: value must not contain NUL bytes.`);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (v.length > MAX_COMMAND_ENV_VAL_CHARS) {
|
|
456
|
+
errors.push(`${itemLabel}.env[${JSON.stringify(k)}]: exceeds maximum length of ${MAX_COMMAND_ENV_VAL_CHARS} characters.`);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
defineOwnProp(env, k, v);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const timeoutMs = validateTimeoutMs(entries.get("timeoutMs"), `${itemLabel}.timeoutMs`, errors);
|
|
465
|
+
let expectExitCode;
|
|
466
|
+
if (entries.has("expectExitCode") && entries.get("expectExitCode") !== undefined) {
|
|
467
|
+
const rawCode = entries.get("expectExitCode");
|
|
468
|
+
if (typeof rawCode !== "number" || !Number.isInteger(rawCode) || rawCode < 0 || rawCode > 255) {
|
|
469
|
+
errors.push(`${itemLabel}.expectExitCode: must be an integer in 0..255.`);
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
expectExitCode = rawCode;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (command) {
|
|
476
|
+
const hook = { command };
|
|
477
|
+
if (args !== undefined)
|
|
478
|
+
hook.args = args;
|
|
479
|
+
if (env !== undefined)
|
|
480
|
+
hook.env = env;
|
|
481
|
+
if (timeoutMs !== undefined)
|
|
482
|
+
hook.timeoutMs = timeoutMs;
|
|
483
|
+
if (expectExitCode !== undefined)
|
|
484
|
+
hook.expectExitCode = expectExitCode;
|
|
485
|
+
normalized.push(hook);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return normalized;
|
|
489
|
+
}
|
|
490
|
+
function decodeSeedBytes(seed) {
|
|
491
|
+
if (seed.encoding === "base64") {
|
|
492
|
+
return Buffer.from(seed.content.replace(/\s+/g, ""), "base64");
|
|
493
|
+
}
|
|
494
|
+
return Buffer.from(seed.content, "utf8");
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Validates and normalizes a declarative `ContractFixtures` configuration.
|
|
498
|
+
* Uses descriptor-only plain-object inspection (immune to hostile Proxies/getters
|
|
499
|
+
* and prototype pollution) and enforces strict path, size, and SSRF invariants.
|
|
500
|
+
*/
|
|
501
|
+
export function validateContractFixtures(raw) {
|
|
502
|
+
const errors = [];
|
|
503
|
+
const warnings = [];
|
|
504
|
+
const entries = readPlainEntries(raw, "fixtures", errors);
|
|
505
|
+
if (!entries) {
|
|
506
|
+
return { valid: false, errors, warnings };
|
|
507
|
+
}
|
|
508
|
+
for (const key of entries.keys()) {
|
|
509
|
+
if (!ALLOWED_TOP_LEVEL_KEYS.has(key)) {
|
|
510
|
+
errors.push(`fixtures: unknown top-level property ${JSON.stringify(sanitizeSingleLine(key, 64))}.`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const normalized = {};
|
|
514
|
+
// 1. seedFiles
|
|
515
|
+
if (entries.has("seedFiles") && entries.get("seedFiles") !== undefined) {
|
|
516
|
+
const rawSeeds = readArrayItems(entries.get("seedFiles"), "fixtures.seedFiles", MAX_FIXTURE_SEED_FILES, errors);
|
|
517
|
+
if (rawSeeds) {
|
|
518
|
+
const seeds = [];
|
|
519
|
+
const seenSeedPaths = new Set();
|
|
520
|
+
for (let i = 0; i < rawSeeds.length; i++) {
|
|
521
|
+
const itemLabel = `fixtures.seedFiles[${i}]`;
|
|
522
|
+
const seedEntries = readPlainEntries(rawSeeds[i], itemLabel, errors);
|
|
523
|
+
if (!seedEntries)
|
|
524
|
+
continue;
|
|
525
|
+
for (const key of seedEntries.keys()) {
|
|
526
|
+
if (!ALLOWED_SEED_KEYS.has(key)) {
|
|
527
|
+
errors.push(`${itemLabel}: unknown property ${JSON.stringify(sanitizeSingleLine(key, 64))}.`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const relPath = validateFixtureRelPath(seedEntries.get("path"), `${itemLabel}.path`, errors);
|
|
531
|
+
const rawEncoding = seedEntries.get("encoding");
|
|
532
|
+
let encoding = "utf8";
|
|
533
|
+
if (rawEncoding !== undefined) {
|
|
534
|
+
if (rawEncoding !== "utf8" && rawEncoding !== "base64") {
|
|
535
|
+
errors.push(`${itemLabel}.encoding: must be "utf8" or "base64".`);
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
encoding = rawEncoding;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const rawContent = seedEntries.get("content");
|
|
542
|
+
let contentOk = false;
|
|
543
|
+
let cleanContent = "";
|
|
544
|
+
if (typeof rawContent !== "string") {
|
|
545
|
+
errors.push(`${itemLabel}.content: must be a string.`);
|
|
546
|
+
}
|
|
547
|
+
else if (encoding === "base64") {
|
|
548
|
+
const maxEncodedChars = Math.ceil(MAX_FIXTURE_SEED_BYTES / 3) * 4 + 4;
|
|
549
|
+
if (rawContent.length > maxEncodedChars * 2) {
|
|
550
|
+
errors.push(`${itemLabel}.content: base64 payload exceeds maximum decoded size of ${MAX_FIXTURE_SEED_BYTES} bytes.`);
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
const compact = rawContent.replace(/\s+/g, "");
|
|
554
|
+
if (compact.length > maxEncodedChars) {
|
|
555
|
+
errors.push(`${itemLabel}.content: base64 payload exceeds maximum decoded size of ${MAX_FIXTURE_SEED_BYTES} bytes.`);
|
|
556
|
+
}
|
|
557
|
+
else if (compact.length % 4 !== 0 || !BASE64_STRICT_RE.test(compact)) {
|
|
558
|
+
errors.push(`${itemLabel}.content: invalid base64 encoding.`);
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
const decodedLen = Buffer.from(compact, "base64").byteLength;
|
|
562
|
+
if (decodedLen > MAX_FIXTURE_SEED_BYTES) {
|
|
563
|
+
errors.push(`${itemLabel}.content: decoded size (${decodedLen} bytes) exceeds maximum of ${MAX_FIXTURE_SEED_BYTES} bytes.`);
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
contentOk = true;
|
|
567
|
+
cleanContent = compact;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
else {
|
|
573
|
+
const byteLen = Buffer.byteLength(rawContent, "utf8");
|
|
574
|
+
if (byteLen > MAX_FIXTURE_SEED_BYTES) {
|
|
575
|
+
errors.push(`${itemLabel}.content: size (${byteLen} bytes) exceeds maximum of ${MAX_FIXTURE_SEED_BYTES} bytes.`);
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
contentOk = true;
|
|
579
|
+
cleanContent = rawContent;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (relPath && contentOk) {
|
|
583
|
+
const dedupeKey = canonicalRelKey(relPath);
|
|
584
|
+
if (seenSeedPaths.has(dedupeKey)) {
|
|
585
|
+
warnings.push(`${itemLabel}.path: duplicate seedFile path "${relPath}"; later entry will overwrite earlier content.`);
|
|
586
|
+
}
|
|
587
|
+
seenSeedPaths.add(dedupeKey);
|
|
588
|
+
const item = { path: relPath, content: cleanContent };
|
|
589
|
+
if (rawEncoding !== undefined)
|
|
590
|
+
item.encoding = encoding;
|
|
591
|
+
seeds.push(item);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
normalized.seedFiles = seeds;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
// 2. snapshotPaths
|
|
598
|
+
if (entries.has("snapshotPaths") && entries.get("snapshotPaths") !== undefined) {
|
|
599
|
+
const rawSnaps = readArrayItems(entries.get("snapshotPaths"), "fixtures.snapshotPaths", MAX_FIXTURE_SNAPSHOT_PATHS, errors);
|
|
600
|
+
if (rawSnaps) {
|
|
601
|
+
const paths = [];
|
|
602
|
+
for (let i = 0; i < rawSnaps.length; i++) {
|
|
603
|
+
const relPath = validateFixtureRelPath(rawSnaps[i], `fixtures.snapshotPaths[${i}]`, errors);
|
|
604
|
+
if (relPath)
|
|
605
|
+
paths.push(relPath);
|
|
606
|
+
}
|
|
607
|
+
normalized.snapshotPaths = paths;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
// 3. HTTP hooks
|
|
611
|
+
const httpSetup = validateHttpHooks(entries.get("httpSetup"), "fixtures.httpSetup", errors, warnings);
|
|
612
|
+
if (httpSetup !== undefined)
|
|
613
|
+
normalized.httpSetup = httpSetup;
|
|
614
|
+
const httpTeardown = validateHttpHooks(entries.get("httpTeardown"), "fixtures.httpTeardown", errors, warnings);
|
|
615
|
+
if (httpTeardown !== undefined)
|
|
616
|
+
normalized.httpTeardown = httpTeardown;
|
|
617
|
+
// 4. Command hooks
|
|
618
|
+
const commandSetup = validateCommandHooks(entries.get("commandSetup"), "fixtures.commandSetup", errors);
|
|
619
|
+
if (commandSetup !== undefined)
|
|
620
|
+
normalized.commandSetup = commandSetup;
|
|
621
|
+
const commandTeardown = validateCommandHooks(entries.get("commandTeardown"), "fixtures.commandTeardown", errors);
|
|
622
|
+
if (commandTeardown !== undefined)
|
|
623
|
+
normalized.commandTeardown = commandTeardown;
|
|
624
|
+
const safeErrors = errors.map((e) => sanitizeSingleLine(e, 300));
|
|
625
|
+
const safeWarnings = warnings.map((w) => sanitizeSingleLine(w, 300));
|
|
626
|
+
if (safeErrors.length > 0) {
|
|
627
|
+
return { valid: false, errors: safeErrors, warnings: safeWarnings };
|
|
628
|
+
}
|
|
629
|
+
return { valid: true, errors: safeErrors, warnings: safeWarnings, normalized };
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Inspects every path component from `rootDir` down to `relPath` via `lstatSync`.
|
|
633
|
+
* Guarantees zero symlink traversal and strict containment within `rootDir` outside vault.
|
|
634
|
+
*/
|
|
635
|
+
function inspectPathChain(rootDir, relPath) {
|
|
636
|
+
const segments = relPath.split("/").filter(Boolean);
|
|
637
|
+
if (segments.length === 0) {
|
|
638
|
+
return { status: "escape", badRel: relPath };
|
|
639
|
+
}
|
|
640
|
+
let cur = rootDir;
|
|
641
|
+
for (let i = 0; i < segments.length; i++) {
|
|
642
|
+
cur = path.join(cur, segments[i]);
|
|
643
|
+
const partialRel = segments.slice(0, i + 1).join("/");
|
|
644
|
+
if (!isPathWithinDir(cur, rootDir, { allowEqual: false }) || isInsideVaultDirectory(cur)) {
|
|
645
|
+
return { status: "escape", badRel: partialRel };
|
|
646
|
+
}
|
|
647
|
+
let stat;
|
|
648
|
+
try {
|
|
649
|
+
stat = fs.lstatSync(cur);
|
|
650
|
+
}
|
|
651
|
+
catch (err) {
|
|
652
|
+
if (err.code === "ENOENT") {
|
|
653
|
+
const finalAbs = path.join(rootDir, ...segments);
|
|
654
|
+
if (!isPathWithinDir(finalAbs, rootDir, { allowEqual: false }) || isInsideVaultDirectory(finalAbs)) {
|
|
655
|
+
return { status: "escape", badRel: relPath };
|
|
656
|
+
}
|
|
657
|
+
return { status: "missing", absPath: finalAbs, firstMissingRel: partialRel };
|
|
658
|
+
}
|
|
659
|
+
throw err;
|
|
660
|
+
}
|
|
661
|
+
const isLast = i === segments.length - 1;
|
|
662
|
+
if (stat.isSymbolicLink()) {
|
|
663
|
+
return isLast
|
|
664
|
+
? { status: "target_symlink", absPath: cur, stat }
|
|
665
|
+
: { status: "ancestor_symlink", symlinkAbs: cur, symlinkRel: partialRel };
|
|
666
|
+
}
|
|
667
|
+
if (!isLast) {
|
|
668
|
+
if (!stat.isDirectory()) {
|
|
669
|
+
return { status: "ancestor_not_dir", blockingAbs: cur, blockingRel: partialRel };
|
|
670
|
+
}
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (stat.isFile())
|
|
674
|
+
return { status: "file", absPath: cur, stat };
|
|
675
|
+
if (stat.isDirectory())
|
|
676
|
+
return { status: "directory", absPath: cur, stat };
|
|
677
|
+
return { status: "special", absPath: cur, stat };
|
|
678
|
+
}
|
|
679
|
+
return { status: "escape", badRel: relPath };
|
|
680
|
+
}
|
|
681
|
+
function readRegularFileNoFollow(absPath, remainingBytes, relLabel) {
|
|
682
|
+
const noFollowFlag = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
|
|
683
|
+
let fd;
|
|
684
|
+
try {
|
|
685
|
+
// Re-check lstat right before open (required on Windows where O_NOFOLLOW is 0).
|
|
686
|
+
const lstat = fs.lstatSync(absPath);
|
|
687
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) {
|
|
688
|
+
throw configError(`Refusing to snapshot non-regular file or symlink "${relLabel}".`);
|
|
689
|
+
}
|
|
690
|
+
if (lstat.size > remainingBytes) {
|
|
691
|
+
throw configError(`Snapshot total byte limit (${MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES} bytes) exceeded at "${relLabel}".`);
|
|
692
|
+
}
|
|
693
|
+
fd = fs.openSync(absPath, fs.constants.O_RDONLY | noFollowFlag);
|
|
694
|
+
const fstat = fs.fstatSync(fd);
|
|
695
|
+
if (!fstat.isFile()) {
|
|
696
|
+
throw configError(`Refusing to snapshot non-regular file "${relLabel}".`);
|
|
697
|
+
}
|
|
698
|
+
if (fstat.size > remainingBytes) {
|
|
699
|
+
throw configError(`Snapshot total byte limit (${MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES} bytes) exceeded at "${relLabel}".`);
|
|
700
|
+
}
|
|
701
|
+
const buf = fs.readFileSync(fd);
|
|
702
|
+
if (buf.byteLength > remainingBytes) {
|
|
703
|
+
throw configError(`Snapshot total byte limit (${MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES} bytes) exceeded at "${relLabel}".`);
|
|
704
|
+
}
|
|
705
|
+
return buf;
|
|
706
|
+
}
|
|
707
|
+
finally {
|
|
708
|
+
if (fd !== undefined) {
|
|
709
|
+
try {
|
|
710
|
+
fs.closeSync(fd);
|
|
711
|
+
}
|
|
712
|
+
catch {
|
|
713
|
+
// ignore close error
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
function isDescendantOf(childRel, parentRel) {
|
|
719
|
+
return canonicalRelKey(childRel).startsWith(`${canonicalRelKey(parentRel)}/`);
|
|
720
|
+
}
|
|
721
|
+
function resolveCanonicalWorkspaceRoot(cwd) {
|
|
722
|
+
if (typeof cwd !== "string" || !cwd.trim()) {
|
|
723
|
+
throw configError("Workspace cwd must be a non-empty directory path.");
|
|
724
|
+
}
|
|
725
|
+
let rootDir;
|
|
726
|
+
try {
|
|
727
|
+
rootDir = fs.realpathSync(cwd);
|
|
728
|
+
const stat = fs.statSync(rootDir);
|
|
729
|
+
if (!stat.isDirectory()) {
|
|
730
|
+
throw configError("Workspace cwd must be an existing directory.");
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
catch (err) {
|
|
734
|
+
if (err instanceof VibecodeError)
|
|
735
|
+
throw err;
|
|
736
|
+
throw configError(`Workspace cwd could not be resolved: ${errorMessage(err)}`);
|
|
737
|
+
}
|
|
738
|
+
if (isInsideVaultDirectory(rootDir)) {
|
|
739
|
+
throw configError("Workspace cwd must not point inside a holdout vault directory.");
|
|
740
|
+
}
|
|
741
|
+
return rootDir;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Captures an in-memory byte-exact snapshot of workspace files, directories, and absent paths.
|
|
745
|
+
* Rejects any symlink, special file, vault/secret path, or escape outside `cwd`.
|
|
746
|
+
*/
|
|
747
|
+
export function captureWorkspaceSnapshots(cwd, paths) {
|
|
748
|
+
return captureWorkspaceSnapshotsInternal(cwd, paths, MAX_FIXTURE_SNAPSHOT_PATHS);
|
|
749
|
+
}
|
|
750
|
+
function captureWorkspaceSnapshotsInternal(cwd, paths, maxPaths) {
|
|
751
|
+
const rootDir = resolveCanonicalWorkspaceRoot(cwd);
|
|
752
|
+
if (!Array.isArray(paths)) {
|
|
753
|
+
throw configError("snapshotPaths must be an array of relative paths.");
|
|
754
|
+
}
|
|
755
|
+
if (paths.length > maxPaths) {
|
|
756
|
+
throw configError(`Too many snapshot paths: maximum allowed is ${maxPaths} (got ${paths.length}).`);
|
|
757
|
+
}
|
|
758
|
+
const validationErrors = [];
|
|
759
|
+
const normalizedByKey = new Map();
|
|
760
|
+
for (let i = 0; i < paths.length; i++) {
|
|
761
|
+
const norm = validateFixtureRelPath(paths[i], `snapshotPaths[${i}]`, validationErrors);
|
|
762
|
+
if (norm) {
|
|
763
|
+
const key = canonicalRelKey(norm);
|
|
764
|
+
if (!normalizedByKey.has(key))
|
|
765
|
+
normalizedByKey.set(key, norm);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (validationErrors.length > 0) {
|
|
769
|
+
throw configError(validationErrors[0], { errors: validationErrors.map((e) => sanitizeSingleLine(e, 300)) });
|
|
770
|
+
}
|
|
771
|
+
// Sort shallowest-first so ancestor directories / missing ancestors are captured before descendants.
|
|
772
|
+
const sortedPaths = [...normalizedByKey.values()].sort((a, b) => {
|
|
773
|
+
const depthDiff = a.split("/").length - b.split("/").length;
|
|
774
|
+
return depthDiff !== 0 ? depthDiff : compareStrings(a, b);
|
|
775
|
+
});
|
|
776
|
+
const entries = [];
|
|
777
|
+
const coveredRoots = [];
|
|
778
|
+
let totalFiles = 0;
|
|
779
|
+
let totalBytes = 0;
|
|
780
|
+
for (const relPath of sortedPaths) {
|
|
781
|
+
if (coveredRoots.some((root) => isDescendantOf(relPath, root))) {
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
const chain = inspectPathChain(rootDir, relPath);
|
|
785
|
+
if (chain.status === "escape") {
|
|
786
|
+
throw configError(`Snapshot path "${relPath}" escapes workspace or touches vault.`);
|
|
787
|
+
}
|
|
788
|
+
if (chain.status === "ancestor_symlink") {
|
|
789
|
+
throw configError(`Refusing to snapshot "${relPath}": ancestor "${chain.symlinkRel}" is a symbolic link.`);
|
|
790
|
+
}
|
|
791
|
+
if (chain.status === "target_symlink") {
|
|
792
|
+
throw configError(`Refusing to snapshot symbolic link "${relPath}".`);
|
|
793
|
+
}
|
|
794
|
+
if (chain.status === "special") {
|
|
795
|
+
throw configError(`Refusing to snapshot special filesystem entry "${relPath}".`);
|
|
796
|
+
}
|
|
797
|
+
if (chain.status === "ancestor_not_dir") {
|
|
798
|
+
throw configError(`Cannot snapshot "${relPath}": ancestor "${chain.blockingRel}" is not a directory.`);
|
|
799
|
+
}
|
|
800
|
+
if (chain.status === "missing") {
|
|
801
|
+
entries.push({
|
|
802
|
+
relPath,
|
|
803
|
+
existed: false,
|
|
804
|
+
kind: "missing",
|
|
805
|
+
firstMissingAncestor: chain.firstMissingRel
|
|
806
|
+
});
|
|
807
|
+
coveredRoots.push(relPath);
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (chain.status === "file") {
|
|
811
|
+
if (totalFiles + 1 > MAX_FIXTURE_SNAPSHOT_FILES) {
|
|
812
|
+
throw configError(`Snapshot exceeds maximum file count of ${MAX_FIXTURE_SNAPSHOT_FILES}.`);
|
|
813
|
+
}
|
|
814
|
+
const buf = readRegularFileNoFollow(chain.absPath, MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES - totalBytes, relPath);
|
|
815
|
+
totalFiles += 1;
|
|
816
|
+
totalBytes += buf.byteLength;
|
|
817
|
+
entries.push({
|
|
818
|
+
relPath,
|
|
819
|
+
existed: true,
|
|
820
|
+
kind: "file",
|
|
821
|
+
content: buf,
|
|
822
|
+
mode: chain.stat.mode
|
|
823
|
+
});
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
// chain.status === "directory"
|
|
827
|
+
const dirFiles = [];
|
|
828
|
+
const dirSubdirs = [];
|
|
829
|
+
const walkDir = (absDir, subRelPrefix, depth) => {
|
|
830
|
+
if (depth > MAX_SNAPSHOT_DEPTH) {
|
|
831
|
+
throw configError(`Snapshot directory "${relPath}" exceeds maximum recursion depth of ${MAX_SNAPSHOT_DEPTH}.`);
|
|
832
|
+
}
|
|
833
|
+
const names = fs.readdirSync(absDir).sort(compareStrings);
|
|
834
|
+
for (const name of names) {
|
|
835
|
+
const childSubRel = subRelPrefix ? `${subRelPrefix}/${name}` : name;
|
|
836
|
+
const childFullRel = `${relPath}/${childSubRel}`;
|
|
837
|
+
const childAbs = path.join(absDir, name);
|
|
838
|
+
if (!isPathWithinDir(childAbs, rootDir, { allowEqual: false }) || isInsideVaultDirectory(childAbs)) {
|
|
839
|
+
throw configError(`Snapshot child "${childFullRel}" escapes workspace or touches vault.`);
|
|
840
|
+
}
|
|
841
|
+
const lowerName = name.toLowerCase();
|
|
842
|
+
if (FORBIDDEN_FIXTURE_SEGMENTS.has(lowerName) ||
|
|
843
|
+
hasVaultOrHoldoutSegment(childFullRel) ||
|
|
844
|
+
isSecretRelativePath(childFullRel)) {
|
|
845
|
+
throw configError(`Refusing to snapshot protected or secret path "${childFullRel}" inside "${relPath}".`);
|
|
846
|
+
}
|
|
847
|
+
const st = fs.lstatSync(childAbs);
|
|
848
|
+
if (st.isSymbolicLink()) {
|
|
849
|
+
throw configError(`Refusing to snapshot symbolic link "${childFullRel}" inside "${relPath}".`);
|
|
850
|
+
}
|
|
851
|
+
if (st.isDirectory()) {
|
|
852
|
+
dirSubdirs.push({ relPath: childSubRel, mode: st.mode });
|
|
853
|
+
walkDir(childAbs, childSubRel, depth + 1);
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
if (!st.isFile()) {
|
|
857
|
+
throw configError(`Refusing to snapshot special filesystem entry "${childFullRel}".`);
|
|
858
|
+
}
|
|
859
|
+
if (totalFiles + 1 > MAX_FIXTURE_SNAPSHOT_FILES) {
|
|
860
|
+
throw configError(`Snapshot exceeds maximum file count of ${MAX_FIXTURE_SNAPSHOT_FILES}.`);
|
|
861
|
+
}
|
|
862
|
+
const buf = readRegularFileNoFollow(childAbs, MAX_FIXTURE_SNAPSHOT_TOTAL_BYTES - totalBytes, childFullRel);
|
|
863
|
+
totalFiles += 1;
|
|
864
|
+
totalBytes += buf.byteLength;
|
|
865
|
+
dirFiles.push({ relPath: childSubRel, content: buf, mode: st.mode });
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
walkDir(chain.absPath, "", 0);
|
|
869
|
+
entries.push({
|
|
870
|
+
relPath,
|
|
871
|
+
existed: true,
|
|
872
|
+
kind: "directory",
|
|
873
|
+
mode: chain.stat.mode,
|
|
874
|
+
files: dirFiles,
|
|
875
|
+
directories: dirSubdirs
|
|
876
|
+
});
|
|
877
|
+
coveredRoots.push(relPath);
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
rootDir,
|
|
881
|
+
capturedAt: new Date().toISOString(),
|
|
882
|
+
entries,
|
|
883
|
+
totalFiles,
|
|
884
|
+
totalBytes
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
function safeUnlinkNonSymlink(absPath) {
|
|
888
|
+
const st = fs.lstatSync(absPath);
|
|
889
|
+
if (st.isSymbolicLink()) {
|
|
890
|
+
throw new Error("Refused to unlink symbolic link as regular file");
|
|
891
|
+
}
|
|
892
|
+
try {
|
|
893
|
+
fs.unlinkSync(absPath);
|
|
894
|
+
}
|
|
895
|
+
catch (err) {
|
|
896
|
+
const code = err.code;
|
|
897
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES") && st.isFile()) {
|
|
898
|
+
const recheck = fs.lstatSync(absPath);
|
|
899
|
+
if (recheck.isSymbolicLink() || !recheck.isFile())
|
|
900
|
+
throw err;
|
|
901
|
+
fs.chmodSync(absPath, 0o666);
|
|
902
|
+
fs.unlinkSync(absPath);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
throw err;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
function removeSymlinkNodeOnly(absPath) {
|
|
909
|
+
const st = fs.lstatSync(absPath);
|
|
910
|
+
if (!st.isSymbolicLink()) {
|
|
911
|
+
throw new Error("Expected symbolic link node");
|
|
912
|
+
}
|
|
913
|
+
try {
|
|
914
|
+
fs.unlinkSync(absPath);
|
|
915
|
+
}
|
|
916
|
+
catch (err) {
|
|
917
|
+
const code = err.code;
|
|
918
|
+
// Windows directory symlinks and NTFS junctions require rmdirSync to remove the reparse point only.
|
|
919
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EISDIR")) {
|
|
920
|
+
fs.rmdirSync(absPath);
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
throw err;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Safely creates all missing parent directories of `relPath` segment by segment,
|
|
928
|
+
* verifying via `lstatSync` that zero symlinks exist along the chain.
|
|
929
|
+
*/
|
|
930
|
+
function ensureParentDirsNoSymlink(rootDir, relPath) {
|
|
931
|
+
const segments = relPath.split("/").filter(Boolean);
|
|
932
|
+
let cur = rootDir;
|
|
933
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
934
|
+
cur = path.join(cur, segments[i]);
|
|
935
|
+
const partialRel = segments.slice(0, i + 1).join("/");
|
|
936
|
+
if (!isPathWithinDir(cur, rootDir, { allowEqual: false }) || isInsideVaultDirectory(cur)) {
|
|
937
|
+
throw new Error(`Parent path "${partialRel}" escapes workspace or touches vault.`);
|
|
938
|
+
}
|
|
939
|
+
let st = null;
|
|
940
|
+
try {
|
|
941
|
+
st = fs.lstatSync(cur);
|
|
942
|
+
}
|
|
943
|
+
catch (err) {
|
|
944
|
+
if (err.code !== "ENOENT")
|
|
945
|
+
throw err;
|
|
946
|
+
}
|
|
947
|
+
if (st === null) {
|
|
948
|
+
fs.mkdirSync(cur);
|
|
949
|
+
st = fs.lstatSync(cur);
|
|
950
|
+
}
|
|
951
|
+
if (st.isSymbolicLink()) {
|
|
952
|
+
throw new Error(`Refused to traverse symlink directory "${partialRel}".`);
|
|
953
|
+
}
|
|
954
|
+
if (!st.isDirectory()) {
|
|
955
|
+
throw new Error(`Parent component "${partialRel}" is not a directory.`);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
function ensureDirNoSymlink(rootDir, relPath) {
|
|
960
|
+
ensureParentDirsNoSymlink(rootDir, relPath);
|
|
961
|
+
const absDir = path.join(rootDir, ...relPath.split("/").filter(Boolean));
|
|
962
|
+
if (!isPathWithinDir(absDir, rootDir, { allowEqual: false }) || isInsideVaultDirectory(absDir)) {
|
|
963
|
+
throw new Error(`Directory path "${relPath}" escapes workspace or touches vault.`);
|
|
964
|
+
}
|
|
965
|
+
let st = null;
|
|
966
|
+
try {
|
|
967
|
+
st = fs.lstatSync(absDir);
|
|
968
|
+
}
|
|
969
|
+
catch (err) {
|
|
970
|
+
if (err.code !== "ENOENT")
|
|
971
|
+
throw err;
|
|
972
|
+
}
|
|
973
|
+
if (st === null) {
|
|
974
|
+
fs.mkdirSync(absDir);
|
|
975
|
+
st = fs.lstatSync(absDir);
|
|
976
|
+
}
|
|
977
|
+
if (st.isSymbolicLink()) {
|
|
978
|
+
throw new Error(`Refused to follow symlink directory "${relPath}".`);
|
|
979
|
+
}
|
|
980
|
+
if (!st.isDirectory()) {
|
|
981
|
+
throw new Error(`Path "${relPath}" is not a directory.`);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Atomically writes `bytes` to `relPath` inside `rootDir` using temp file (`O_EXCL`) + rename.
|
|
986
|
+
* Re-checks every ancestor and the target itself via `lstatSync` to guarantee zero symlink following.
|
|
987
|
+
*/
|
|
988
|
+
function safeAtomicWriteFile(rootDir, relPath, bytes, mode) {
|
|
989
|
+
ensureParentDirsNoSymlink(rootDir, relPath);
|
|
990
|
+
const absPath = path.join(rootDir, ...relPath.split("/").filter(Boolean));
|
|
991
|
+
if (!isPathWithinDir(absPath, rootDir, { allowEqual: false }) || isInsideVaultDirectory(absPath)) {
|
|
992
|
+
throw new Error(`Target path "${relPath}" escapes workspace or touches vault.`);
|
|
993
|
+
}
|
|
994
|
+
let existing = null;
|
|
995
|
+
try {
|
|
996
|
+
existing = fs.lstatSync(absPath);
|
|
997
|
+
}
|
|
998
|
+
catch (err) {
|
|
999
|
+
if (err.code !== "ENOENT")
|
|
1000
|
+
throw err;
|
|
1001
|
+
}
|
|
1002
|
+
if (existing !== null) {
|
|
1003
|
+
if (existing.isSymbolicLink()) {
|
|
1004
|
+
throw new Error(`Refused to follow symbolic link at "${relPath}".`);
|
|
1005
|
+
}
|
|
1006
|
+
if (existing.isDirectory()) {
|
|
1007
|
+
throw new Error(`Cannot write file over directory at "${relPath}".`);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
const parentDir = path.dirname(absPath);
|
|
1011
|
+
const tmpPath = path.join(parentDir, `.vibecode-fixture-${process.pid}-${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
1012
|
+
if (!isPathWithinDir(tmpPath, rootDir, { allowEqual: false })) {
|
|
1013
|
+
throw new Error(`Temp path for "${relPath}" escapes workspace.`);
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
fs.writeFileSync(tmpPath, bytes, { flag: "wx" });
|
|
1017
|
+
// Final anti-TOCTOU lstat verification before atomic replace.
|
|
1018
|
+
try {
|
|
1019
|
+
const preRename = fs.lstatSync(absPath);
|
|
1020
|
+
if (preRename.isSymbolicLink()) {
|
|
1021
|
+
throw new Error(`Refused to follow symbolic link at "${relPath}".`);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
catch (err) {
|
|
1025
|
+
if (err.code !== "ENOENT")
|
|
1026
|
+
throw err;
|
|
1027
|
+
}
|
|
1028
|
+
try {
|
|
1029
|
+
fs.renameSync(tmpPath, absPath);
|
|
1030
|
+
}
|
|
1031
|
+
catch (err) {
|
|
1032
|
+
const code = err.code;
|
|
1033
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES")) {
|
|
1034
|
+
const curStat = fs.lstatSync(absPath);
|
|
1035
|
+
if (curStat.isSymbolicLink() || !curStat.isFile())
|
|
1036
|
+
throw err;
|
|
1037
|
+
fs.chmodSync(absPath, 0o666);
|
|
1038
|
+
fs.renameSync(tmpPath, absPath);
|
|
1039
|
+
}
|
|
1040
|
+
else {
|
|
1041
|
+
throw err;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
if (mode !== undefined && process.platform !== "win32") {
|
|
1045
|
+
const postStat = fs.lstatSync(absPath);
|
|
1046
|
+
if (postStat.isFile()) {
|
|
1047
|
+
try {
|
|
1048
|
+
fs.chmodSync(absPath, mode & 0o777);
|
|
1049
|
+
}
|
|
1050
|
+
catch {
|
|
1051
|
+
// ignore chmod failure on restricted filesystems
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
catch (err) {
|
|
1057
|
+
try {
|
|
1058
|
+
fs.unlinkSync(tmpPath);
|
|
1059
|
+
}
|
|
1060
|
+
catch {
|
|
1061
|
+
// ignore temp cleanup failure
|
|
1062
|
+
}
|
|
1063
|
+
throw err;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Safely deletes a file, symlink node (never following its target), or directory tree inside `rootDir`.
|
|
1068
|
+
* Returns how many leaf entries were removed (0 if missing or blocked).
|
|
1069
|
+
*/
|
|
1070
|
+
function safeRemoveTreeInsideRoot(rootDir, relPath, errors, depth = 0) {
|
|
1071
|
+
if (depth > MAX_REMOVE_DEPTH) {
|
|
1072
|
+
errors.push(`Exceeded max depth while removing "${relPath}" during rollback.`);
|
|
1073
|
+
return 0;
|
|
1074
|
+
}
|
|
1075
|
+
const chain = inspectPathChain(rootDir, relPath);
|
|
1076
|
+
if (chain.status === "missing" || chain.status === "ancestor_not_dir") {
|
|
1077
|
+
return 0;
|
|
1078
|
+
}
|
|
1079
|
+
if (chain.status === "escape") {
|
|
1080
|
+
errors.push(`Refused to remove path "${relPath}" outside workspace or inside vault.`);
|
|
1081
|
+
return 0;
|
|
1082
|
+
}
|
|
1083
|
+
if (chain.status === "ancestor_symlink") {
|
|
1084
|
+
errors.push(`Refused to traverse symlink ancestor "${chain.symlinkRel}" during rollback of "${relPath}".`);
|
|
1085
|
+
return 0;
|
|
1086
|
+
}
|
|
1087
|
+
if (chain.status === "target_symlink") {
|
|
1088
|
+
removeSymlinkNodeOnly(chain.absPath);
|
|
1089
|
+
return 1;
|
|
1090
|
+
}
|
|
1091
|
+
if (chain.status === "file" || chain.status === "special") {
|
|
1092
|
+
safeUnlinkNonSymlink(chain.absPath);
|
|
1093
|
+
return 1;
|
|
1094
|
+
}
|
|
1095
|
+
// Real directory: recursively remove children without ever following symlinks.
|
|
1096
|
+
const childNames = fs.readdirSync(chain.absPath).sort(compareStrings);
|
|
1097
|
+
let removedLeaves = 0;
|
|
1098
|
+
for (const name of childNames) {
|
|
1099
|
+
removedLeaves += safeRemoveTreeInsideRoot(rootDir, `${relPath}/${name}`, errors, depth + 1);
|
|
1100
|
+
}
|
|
1101
|
+
const postStat = fs.lstatSync(chain.absPath);
|
|
1102
|
+
if (postStat.isSymbolicLink() || !postStat.isDirectory()) {
|
|
1103
|
+
errors.push(`Refused to remove unexpected non-directory at "${relPath}".`);
|
|
1104
|
+
return removedLeaves;
|
|
1105
|
+
}
|
|
1106
|
+
fs.rmdirSync(chain.absPath);
|
|
1107
|
+
return removedLeaves > 0 ? removedLeaves : 1;
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Prunes empty parent directories created during seeding/execution, stopping at `stopAtAncestorRel`.
|
|
1111
|
+
*/
|
|
1112
|
+
function pruneEmptyNewParents(rootDir, relPath, stopAtAncestorRel) {
|
|
1113
|
+
if (!stopAtAncestorRel)
|
|
1114
|
+
return;
|
|
1115
|
+
const parts = relPath.split("/").filter(Boolean);
|
|
1116
|
+
const stopParts = stopAtAncestorRel.split("/").filter(Boolean);
|
|
1117
|
+
if (stopParts.length === 0 || parts.length <= stopParts.length)
|
|
1118
|
+
return;
|
|
1119
|
+
if (!isDescendantOf(relPath, stopParts.join("/")))
|
|
1120
|
+
return;
|
|
1121
|
+
for (let len = parts.length - 1; len >= stopParts.length; len--) {
|
|
1122
|
+
const dirRel = parts.slice(0, len).join("/");
|
|
1123
|
+
const chain = inspectPathChain(rootDir, dirRel);
|
|
1124
|
+
if (chain.status !== "directory")
|
|
1125
|
+
break;
|
|
1126
|
+
let remaining;
|
|
1127
|
+
try {
|
|
1128
|
+
remaining = fs.readdirSync(chain.absPath);
|
|
1129
|
+
}
|
|
1130
|
+
catch {
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
if (remaining.length > 0)
|
|
1134
|
+
break;
|
|
1135
|
+
try {
|
|
1136
|
+
fs.rmdirSync(chain.absPath);
|
|
1137
|
+
}
|
|
1138
|
+
catch {
|
|
1139
|
+
break;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Restores a captured `WorkspaceSnapshot` back to exact pre-run state.
|
|
1145
|
+
* Enforces anti-symlink-swap verification via `lstatSync` on every path component
|
|
1146
|
+
* before every mkdir, write, or unlink — never writes or deletes outside `snapshot.rootDir`.
|
|
1147
|
+
*/
|
|
1148
|
+
export function restoreWorkspaceSnapshots(snapshot) {
|
|
1149
|
+
const errors = [];
|
|
1150
|
+
let restoredPaths = 0;
|
|
1151
|
+
let removedNewPaths = 0;
|
|
1152
|
+
if (!snapshot || typeof snapshot.rootDir !== "string" || !snapshot.rootDir) {
|
|
1153
|
+
return { restoredPaths: 0, removedNewPaths: 0, errors: ["Invalid workspace snapshot."] };
|
|
1154
|
+
}
|
|
1155
|
+
let currentRoot;
|
|
1156
|
+
try {
|
|
1157
|
+
currentRoot = fs.realpathSync(snapshot.rootDir);
|
|
1158
|
+
}
|
|
1159
|
+
catch (err) {
|
|
1160
|
+
return {
|
|
1161
|
+
restoredPaths: 0,
|
|
1162
|
+
removedNewPaths: 0,
|
|
1163
|
+
errors: [`Workspace root unavailable during rollback: ${sanitizeSingleLine(errorMessage(err), 200)}`]
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
if (!isSamePath(currentRoot, snapshot.rootDir) || isInsideVaultDirectory(currentRoot)) {
|
|
1167
|
+
return {
|
|
1168
|
+
restoredPaths: 0,
|
|
1169
|
+
removedNewPaths: 0,
|
|
1170
|
+
errors: ["Workspace root changed or points inside vault; refusing rollback."]
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
const rootDir = snapshot.rootDir;
|
|
1174
|
+
// Restore deeper entries first to avoid parent/child interference.
|
|
1175
|
+
const ordered = [...snapshot.entries].sort((a, b) => {
|
|
1176
|
+
const depthDiff = b.relPath.split("/").length - a.relPath.split("/").length;
|
|
1177
|
+
return depthDiff !== 0 ? depthDiff : compareStrings(a.relPath, b.relPath);
|
|
1178
|
+
});
|
|
1179
|
+
for (const entry of ordered) {
|
|
1180
|
+
try {
|
|
1181
|
+
// Re-validate entry relPath defensively in case snapshot object was constructed externally.
|
|
1182
|
+
const pathErrs = [];
|
|
1183
|
+
const validRel = validateFixtureRelPath(entry.relPath, "snapshot.entry.relPath", pathErrs);
|
|
1184
|
+
if (!validRel) {
|
|
1185
|
+
errors.push(pathErrs[0] ?? `Invalid snapshot entry path "${sanitizeSingleLine(entry.relPath, 120)}".`);
|
|
1186
|
+
continue;
|
|
1187
|
+
}
|
|
1188
|
+
if (!entry.existed || entry.kind === "missing") {
|
|
1189
|
+
const chain = inspectPathChain(rootDir, validRel);
|
|
1190
|
+
if (chain.status === "missing" || chain.status === "ancestor_not_dir") {
|
|
1191
|
+
pruneEmptyNewParents(rootDir, validRel, entry.firstMissingAncestor);
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
if (chain.status === "escape") {
|
|
1195
|
+
errors.push(`Refused to delete "${validRel}": path escapes workspace or touches vault.`);
|
|
1196
|
+
continue;
|
|
1197
|
+
}
|
|
1198
|
+
if (chain.status === "ancestor_symlink") {
|
|
1199
|
+
errors.push(`Refused to follow symlink ancestor "${chain.symlinkRel}" during rollback of "${validRel}".`);
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
if (chain.status === "target_symlink") {
|
|
1203
|
+
removeSymlinkNodeOnly(chain.absPath);
|
|
1204
|
+
removedNewPaths += 1;
|
|
1205
|
+
pruneEmptyNewParents(rootDir, validRel, entry.firstMissingAncestor);
|
|
1206
|
+
continue;
|
|
1207
|
+
}
|
|
1208
|
+
if (chain.status === "file" || chain.status === "special") {
|
|
1209
|
+
safeUnlinkNonSymlink(chain.absPath);
|
|
1210
|
+
removedNewPaths += 1;
|
|
1211
|
+
pruneEmptyNewParents(rootDir, validRel, entry.firstMissingAncestor);
|
|
1212
|
+
continue;
|
|
1213
|
+
}
|
|
1214
|
+
// Directory created where nothing existed before.
|
|
1215
|
+
const removed = safeRemoveTreeInsideRoot(rootDir, validRel, errors);
|
|
1216
|
+
if (removed > 0)
|
|
1217
|
+
removedNewPaths += 1;
|
|
1218
|
+
pruneEmptyNewParents(rootDir, validRel, entry.firstMissingAncestor);
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
if (entry.kind === "file") {
|
|
1222
|
+
const expectedBytes = entry.content ?? Buffer.alloc(0);
|
|
1223
|
+
const chain = inspectPathChain(rootDir, validRel);
|
|
1224
|
+
if (chain.status === "escape") {
|
|
1225
|
+
errors.push(`Refused to restore "${validRel}": path escapes workspace or touches vault.`);
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
if (chain.status === "ancestor_symlink") {
|
|
1229
|
+
errors.push(`Refused to follow symlink ancestor "${chain.symlinkRel}" during rollback of "${validRel}".`);
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
if (chain.status === "target_symlink") {
|
|
1233
|
+
errors.push(`Refused to follow symlink at "${validRel}" during rollback; removed planted symlink without touching its target.`);
|
|
1234
|
+
removeSymlinkNodeOnly(chain.absPath);
|
|
1235
|
+
continue;
|
|
1236
|
+
}
|
|
1237
|
+
if (chain.status === "ancestor_not_dir") {
|
|
1238
|
+
errors.push(`Cannot restore "${validRel}": ancestor "${chain.blockingRel}" was replaced by a non-directory.`);
|
|
1239
|
+
continue;
|
|
1240
|
+
}
|
|
1241
|
+
if (chain.status === "directory") {
|
|
1242
|
+
const prevErrCount = errors.length;
|
|
1243
|
+
safeRemoveTreeInsideRoot(rootDir, validRel, errors);
|
|
1244
|
+
if (errors.length > prevErrCount)
|
|
1245
|
+
continue;
|
|
1246
|
+
safeAtomicWriteFile(rootDir, validRel, expectedBytes, entry.mode);
|
|
1247
|
+
restoredPaths += 1;
|
|
1248
|
+
continue;
|
|
1249
|
+
}
|
|
1250
|
+
if (chain.status === "special") {
|
|
1251
|
+
safeUnlinkNonSymlink(chain.absPath);
|
|
1252
|
+
safeAtomicWriteFile(rootDir, validRel, expectedBytes, entry.mode);
|
|
1253
|
+
restoredPaths += 1;
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
if (chain.status === "file") {
|
|
1257
|
+
if (chain.stat.size === expectedBytes.byteLength) {
|
|
1258
|
+
const currentBytes = readRegularFileNoFollow(chain.absPath, expectedBytes.byteLength, validRel);
|
|
1259
|
+
if (currentBytes.equals(expectedBytes)) {
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
safeAtomicWriteFile(rootDir, validRel, expectedBytes, entry.mode);
|
|
1264
|
+
restoredPaths += 1;
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
1267
|
+
// chain.status === "missing"
|
|
1268
|
+
safeAtomicWriteFile(rootDir, validRel, expectedBytes, entry.mode);
|
|
1269
|
+
restoredPaths += 1;
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
// entry.kind === "directory"
|
|
1273
|
+
const origFiles = entry.files ?? [];
|
|
1274
|
+
const origDirs = entry.directories ?? [];
|
|
1275
|
+
const origFileMap = new Map();
|
|
1276
|
+
for (const f of origFiles)
|
|
1277
|
+
origFileMap.set(canonicalRelKey(f.relPath), f);
|
|
1278
|
+
const origDirSet = new Set(origDirs.map((d) => canonicalRelKey(d.relPath)));
|
|
1279
|
+
const blockedBySymlink = new Set();
|
|
1280
|
+
const dirChain = inspectPathChain(rootDir, validRel);
|
|
1281
|
+
let rootDirWasMissing = false;
|
|
1282
|
+
if (dirChain.status === "escape") {
|
|
1283
|
+
errors.push(`Refused to restore directory "${validRel}": path escapes workspace or touches vault.`);
|
|
1284
|
+
continue;
|
|
1285
|
+
}
|
|
1286
|
+
if (dirChain.status === "ancestor_symlink") {
|
|
1287
|
+
errors.push(`Refused to follow symlink ancestor "${dirChain.symlinkRel}" during rollback of "${validRel}".`);
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
if (dirChain.status === "target_symlink") {
|
|
1291
|
+
errors.push(`Refused to follow symlink at directory "${validRel}" during rollback; removed planted symlink without touching its target.`);
|
|
1292
|
+
removeSymlinkNodeOnly(dirChain.absPath);
|
|
1293
|
+
continue;
|
|
1294
|
+
}
|
|
1295
|
+
if (dirChain.status === "ancestor_not_dir") {
|
|
1296
|
+
errors.push(`Cannot restore directory "${validRel}": ancestor "${dirChain.blockingRel}" is not a directory.`);
|
|
1297
|
+
continue;
|
|
1298
|
+
}
|
|
1299
|
+
if (dirChain.status === "file" || dirChain.status === "special") {
|
|
1300
|
+
safeUnlinkNonSymlink(dirChain.absPath);
|
|
1301
|
+
ensureDirNoSymlink(rootDir, validRel);
|
|
1302
|
+
rootDirWasMissing = true;
|
|
1303
|
+
}
|
|
1304
|
+
else if (dirChain.status === "missing") {
|
|
1305
|
+
ensureDirNoSymlink(rootDir, validRel);
|
|
1306
|
+
rootDirWasMissing = true;
|
|
1307
|
+
}
|
|
1308
|
+
// Step A: Walk current directory tree to remove new entries and catch symlink swaps.
|
|
1309
|
+
const cleanCurrentDir = (subRelPrefix, depth) => {
|
|
1310
|
+
if (depth > MAX_REMOVE_DEPTH) {
|
|
1311
|
+
errors.push(`Exceeded max depth scanning "${validRel}/${subRelPrefix}" during rollback.`);
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
const curFullRel = subRelPrefix ? `${validRel}/${subRelPrefix}` : validRel;
|
|
1315
|
+
const curChain = inspectPathChain(rootDir, curFullRel);
|
|
1316
|
+
if (curChain.status !== "directory")
|
|
1317
|
+
return;
|
|
1318
|
+
const childNames = fs.readdirSync(curChain.absPath).sort(compareStrings);
|
|
1319
|
+
for (const name of childNames) {
|
|
1320
|
+
const childSubRel = subRelPrefix ? `${subRelPrefix}/${name}` : name;
|
|
1321
|
+
const childFullRel = `${validRel}/${childSubRel}`;
|
|
1322
|
+
const childAbs = path.join(curChain.absPath, name);
|
|
1323
|
+
if (!isPathWithinDir(childAbs, rootDir, { allowEqual: false }) || isInsideVaultDirectory(childAbs)) {
|
|
1324
|
+
errors.push(`Refused to touch "${childFullRel}" outside workspace or inside vault.`);
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
const childSubKey = canonicalRelKey(childSubRel);
|
|
1328
|
+
const st = fs.lstatSync(childAbs);
|
|
1329
|
+
if (st.isSymbolicLink()) {
|
|
1330
|
+
if (origFileMap.has(childSubKey) || origDirSet.has(childSubKey)) {
|
|
1331
|
+
errors.push(`Refused to follow symlink at "${childFullRel}" during rollback; removed planted symlink without touching its target.`);
|
|
1332
|
+
removeSymlinkNodeOnly(childAbs);
|
|
1333
|
+
blockedBySymlink.add(childSubKey);
|
|
1334
|
+
}
|
|
1335
|
+
else {
|
|
1336
|
+
removeSymlinkNodeOnly(childAbs);
|
|
1337
|
+
removedNewPaths += 1;
|
|
1338
|
+
}
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
if (st.isDirectory()) {
|
|
1342
|
+
if (origDirSet.has(childSubKey)) {
|
|
1343
|
+
cleanCurrentDir(childSubRel, depth + 1);
|
|
1344
|
+
}
|
|
1345
|
+
else if (origFileMap.has(childSubKey)) {
|
|
1346
|
+
safeRemoveTreeInsideRoot(rootDir, childFullRel, errors, depth + 1);
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
removedNewPaths += safeRemoveTreeInsideRoot(rootDir, childFullRel, errors, depth + 1);
|
|
1350
|
+
}
|
|
1351
|
+
continue;
|
|
1352
|
+
}
|
|
1353
|
+
// Regular file or special entry.
|
|
1354
|
+
if (origFileMap.has(childSubKey)) {
|
|
1355
|
+
if (!st.isFile()) {
|
|
1356
|
+
safeUnlinkNonSymlink(childAbs);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
else if (origDirSet.has(childSubKey)) {
|
|
1360
|
+
safeUnlinkNonSymlink(childAbs);
|
|
1361
|
+
}
|
|
1362
|
+
else {
|
|
1363
|
+
safeUnlinkNonSymlink(childAbs);
|
|
1364
|
+
removedNewPaths += 1;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1368
|
+
cleanCurrentDir("", 0);
|
|
1369
|
+
const isBlocked = (subRel) => {
|
|
1370
|
+
const subKey = canonicalRelKey(subRel);
|
|
1371
|
+
if (blockedBySymlink.has(subKey))
|
|
1372
|
+
return true;
|
|
1373
|
+
for (const blocked of blockedBySymlink) {
|
|
1374
|
+
if (subKey.startsWith(`${blocked}/`))
|
|
1375
|
+
return true;
|
|
1376
|
+
}
|
|
1377
|
+
return false;
|
|
1378
|
+
};
|
|
1379
|
+
// Step B: Recreate missing original subdirectories (shallowest first).
|
|
1380
|
+
const dirsSorted = [...origDirs].sort((a, b) => {
|
|
1381
|
+
const depthDiff = a.relPath.split("/").length - b.relPath.split("/").length;
|
|
1382
|
+
return depthDiff !== 0 ? depthDiff : compareStrings(a.relPath, b.relPath);
|
|
1383
|
+
});
|
|
1384
|
+
const dirsWithFiles = new Set();
|
|
1385
|
+
for (const f of origFiles) {
|
|
1386
|
+
const segs = f.relPath.split("/");
|
|
1387
|
+
for (let i = 1; i < segs.length; i++) {
|
|
1388
|
+
dirsWithFiles.add(segs.slice(0, i).join("/"));
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
for (const d of dirsSorted) {
|
|
1392
|
+
if (isBlocked(d.relPath))
|
|
1393
|
+
continue;
|
|
1394
|
+
const fullDirRel = `${validRel}/${d.relPath}`;
|
|
1395
|
+
const cur = inspectPathChain(rootDir, fullDirRel);
|
|
1396
|
+
if (cur.status === "missing") {
|
|
1397
|
+
ensureDirNoSymlink(rootDir, fullDirRel);
|
|
1398
|
+
if (!dirsWithFiles.has(d.relPath)) {
|
|
1399
|
+
restoredPaths += 1;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
// Step C: Restore all missing or modified original files.
|
|
1404
|
+
for (const f of origFiles) {
|
|
1405
|
+
if (isBlocked(f.relPath))
|
|
1406
|
+
continue;
|
|
1407
|
+
const fullFileRel = `${validRel}/${f.relPath}`;
|
|
1408
|
+
const cur = inspectPathChain(rootDir, fullFileRel);
|
|
1409
|
+
if (cur.status === "ancestor_symlink" || cur.status === "target_symlink") {
|
|
1410
|
+
errors.push(`Refused to follow symlink while restoring "${fullFileRel}".`);
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
if (cur.status === "file") {
|
|
1414
|
+
if (cur.stat.size === f.content.byteLength) {
|
|
1415
|
+
const currentBytes = readRegularFileNoFollow(cur.absPath, f.content.byteLength, fullFileRel);
|
|
1416
|
+
if (currentBytes.equals(f.content))
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
safeAtomicWriteFile(rootDir, fullFileRel, f.content, f.mode);
|
|
1421
|
+
restoredPaths += 1;
|
|
1422
|
+
}
|
|
1423
|
+
if (rootDirWasMissing && origFiles.length === 0 && origDirs.length === 0) {
|
|
1424
|
+
restoredPaths += 1;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
catch (err) {
|
|
1428
|
+
errors.push(`Failed to roll back "${sanitizeSingleLine(entry.relPath, 120)}": ${sanitizeSingleLine(errorMessage(err), 200)}`);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
return { restoredPaths, removedNewPaths, errors };
|
|
1432
|
+
}
|
|
1433
|
+
function collectExtraSecrets(optionsHeaders, httpHooks, commandHooks) {
|
|
1434
|
+
const secrets = new Set();
|
|
1435
|
+
const opts = { skipVarPlaceholders: true };
|
|
1436
|
+
collectHeaderSecrets(secrets, optionsHeaders, opts);
|
|
1437
|
+
if (httpHooks) {
|
|
1438
|
+
for (const h of httpHooks)
|
|
1439
|
+
collectHeaderSecrets(secrets, h.headers, opts);
|
|
1440
|
+
}
|
|
1441
|
+
if (commandHooks) {
|
|
1442
|
+
for (const c of commandHooks) {
|
|
1443
|
+
if (!c.env || typeof c.env !== "object")
|
|
1444
|
+
continue;
|
|
1445
|
+
let keys;
|
|
1446
|
+
try {
|
|
1447
|
+
keys = Object.keys(c.env);
|
|
1448
|
+
}
|
|
1449
|
+
catch {
|
|
1450
|
+
continue;
|
|
1451
|
+
}
|
|
1452
|
+
for (const key of keys) {
|
|
1453
|
+
if (isForbiddenObjectKey(key) || !isSensitiveKeyName(key))
|
|
1454
|
+
continue;
|
|
1455
|
+
let desc;
|
|
1456
|
+
try {
|
|
1457
|
+
desc = Object.getOwnPropertyDescriptor(c.env, key);
|
|
1458
|
+
}
|
|
1459
|
+
catch {
|
|
1460
|
+
continue;
|
|
1461
|
+
}
|
|
1462
|
+
if (!desc || !("value" in desc) || typeof desc.value !== "string")
|
|
1463
|
+
continue;
|
|
1464
|
+
collectSecretValue(secrets, desc.value, opts);
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
return secrets;
|
|
1469
|
+
}
|
|
1470
|
+
function buildCombinedSecretVars(vars, extraSecrets) {
|
|
1471
|
+
const hasExtra = Boolean(extraSecrets && extraSecrets.size > 0);
|
|
1472
|
+
if (!hasExtra) {
|
|
1473
|
+
if (!vars || typeof vars !== "object")
|
|
1474
|
+
return undefined;
|
|
1475
|
+
try {
|
|
1476
|
+
const out = {};
|
|
1477
|
+
for (const k of Object.keys(vars)) {
|
|
1478
|
+
if (isForbiddenObjectKey(k))
|
|
1479
|
+
continue;
|
|
1480
|
+
const desc = Object.getOwnPropertyDescriptor(vars, k);
|
|
1481
|
+
if (desc && "value" in desc && typeof desc.value === "string") {
|
|
1482
|
+
defineOwnProp(out, k, desc.value);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
return out;
|
|
1486
|
+
}
|
|
1487
|
+
catch {
|
|
1488
|
+
return undefined;
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
const combined = {};
|
|
1492
|
+
if (vars && typeof vars === "object") {
|
|
1493
|
+
try {
|
|
1494
|
+
for (const k of Object.keys(vars)) {
|
|
1495
|
+
if (isForbiddenObjectKey(k))
|
|
1496
|
+
continue;
|
|
1497
|
+
const desc = Object.getOwnPropertyDescriptor(vars, k);
|
|
1498
|
+
if (desc && "value" in desc && typeof desc.value === "string") {
|
|
1499
|
+
defineOwnProp(combined, k, desc.value);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
catch {
|
|
1504
|
+
// ignore hostile vars proxy during best-effort secret collection
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
let idx = 0;
|
|
1508
|
+
for (const secret of extraSecrets) {
|
|
1509
|
+
if (secret.length >= 4) {
|
|
1510
|
+
defineOwnProp(combined, `__fixture_extra_${idx++}`, secret);
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
return combined;
|
|
1514
|
+
}
|
|
1515
|
+
function scrubFixtureText(text, vars, extraSecrets) {
|
|
1516
|
+
const raw = stripTerminalEscapes(String(text ?? ""));
|
|
1517
|
+
if (!raw)
|
|
1518
|
+
return "";
|
|
1519
|
+
const combinedVars = buildCombinedSecretVars(vars, extraSecrets);
|
|
1520
|
+
const out = redactRuntimeVars(raw, combinedVars);
|
|
1521
|
+
return redactSensitiveText(stripTerminalEscapes(out));
|
|
1522
|
+
}
|
|
1523
|
+
function readRuntimeVar(vars, name) {
|
|
1524
|
+
if (!vars || typeof vars !== "object" || isForbiddenObjectKey(name)) {
|
|
1525
|
+
return { found: false, value: "" };
|
|
1526
|
+
}
|
|
1527
|
+
try {
|
|
1528
|
+
if (!Object.prototype.hasOwnProperty.call(vars, name)) {
|
|
1529
|
+
return { found: false, value: "" };
|
|
1530
|
+
}
|
|
1531
|
+
const desc = Object.getOwnPropertyDescriptor(vars, name);
|
|
1532
|
+
if (!desc || !("value" in desc) || typeof desc.value !== "string") {
|
|
1533
|
+
return { found: false, value: "" };
|
|
1534
|
+
}
|
|
1535
|
+
return { found: true, value: desc.value };
|
|
1536
|
+
}
|
|
1537
|
+
catch (err) {
|
|
1538
|
+
throw configError(`Runtime variable "vars.${name}" could not be read safely (${errorMessage(err)}).`);
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
function interpolateStringWithVars(input, vars) {
|
|
1542
|
+
if (!input.includes("{{"))
|
|
1543
|
+
return input;
|
|
1544
|
+
return input.replace(VAR_PLACEHOLDER_RE, (_match, name) => {
|
|
1545
|
+
const resolved = readRuntimeVar(vars, name);
|
|
1546
|
+
if (!resolved.found) {
|
|
1547
|
+
throw configError(`Fixture references undefined runtime variable "vars.${name}".`);
|
|
1548
|
+
}
|
|
1549
|
+
return resolved.value;
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
function interpolateJsonWithVars(node, vars, depth = 0) {
|
|
1553
|
+
if (depth > MAX_JSON_BODY_DEPTH) {
|
|
1554
|
+
throw configError("Fixture HTTP body exceeds maximum nesting depth during variable interpolation.");
|
|
1555
|
+
}
|
|
1556
|
+
if (typeof node === "string") {
|
|
1557
|
+
return interpolateStringWithVars(node, vars);
|
|
1558
|
+
}
|
|
1559
|
+
if (Array.isArray(node)) {
|
|
1560
|
+
return node.map((item) => interpolateJsonWithVars(item, vars, depth + 1));
|
|
1561
|
+
}
|
|
1562
|
+
if (node !== null && typeof node === "object") {
|
|
1563
|
+
const out = {};
|
|
1564
|
+
for (const key of Object.keys(node)) {
|
|
1565
|
+
if (isForbiddenObjectKey(key))
|
|
1566
|
+
continue;
|
|
1567
|
+
defineOwnProp(out, key, interpolateJsonWithVars(node[key], vars, depth + 1));
|
|
1568
|
+
}
|
|
1569
|
+
return out;
|
|
1570
|
+
}
|
|
1571
|
+
return node;
|
|
1572
|
+
}
|
|
1573
|
+
function mergeHttpHeaders(baseHeaders, hookHeaders, vars) {
|
|
1574
|
+
const out = {};
|
|
1575
|
+
const lowerToKey = new Map();
|
|
1576
|
+
const setHeader = (rawName, rawValue) => {
|
|
1577
|
+
const name = rawName.trim();
|
|
1578
|
+
if (!name || isForbiddenObjectKey(name) || STRICT_CONTROL_CHARS_RE.test(rawName) || !HTTP_HEADER_NAME_RE.test(name)) {
|
|
1579
|
+
throw configError(`Invalid HTTP header name ${JSON.stringify(sanitizeSingleLine(rawName, 64))}.`);
|
|
1580
|
+
}
|
|
1581
|
+
if (HEADER_VALUE_UNSAFE_RE.test(rawValue)) {
|
|
1582
|
+
throw configError(`HTTP header ${JSON.stringify(name)} value contains forbidden CRLF or control characters.`);
|
|
1583
|
+
}
|
|
1584
|
+
const lower = name.toLowerCase();
|
|
1585
|
+
const prevKey = lowerToKey.get(lower);
|
|
1586
|
+
if (prevKey && prevKey !== name) {
|
|
1587
|
+
delete out[prevKey];
|
|
1588
|
+
}
|
|
1589
|
+
lowerToKey.set(lower, name);
|
|
1590
|
+
defineOwnProp(out, name, rawValue);
|
|
1591
|
+
};
|
|
1592
|
+
if (baseHeaders && typeof baseHeaders === "object") {
|
|
1593
|
+
let keys;
|
|
1594
|
+
try {
|
|
1595
|
+
keys = Object.keys(baseHeaders);
|
|
1596
|
+
}
|
|
1597
|
+
catch (err) {
|
|
1598
|
+
throw configError(`Fixture base headers could not be read safely (${errorMessage(err)}).`);
|
|
1599
|
+
}
|
|
1600
|
+
for (const key of keys) {
|
|
1601
|
+
if (isForbiddenObjectKey(key))
|
|
1602
|
+
continue;
|
|
1603
|
+
let desc;
|
|
1604
|
+
try {
|
|
1605
|
+
desc = Object.getOwnPropertyDescriptor(baseHeaders, key);
|
|
1606
|
+
}
|
|
1607
|
+
catch (err) {
|
|
1608
|
+
throw configError(`Fixture base header ${JSON.stringify(sanitizeSingleLine(key, 64))} could not be read safely (${errorMessage(err)}).`);
|
|
1609
|
+
}
|
|
1610
|
+
if (!desc || !("value" in desc) || typeof desc.value !== "string")
|
|
1611
|
+
continue;
|
|
1612
|
+
setHeader(key, desc.value);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
if (hookHeaders && typeof hookHeaders === "object") {
|
|
1616
|
+
for (const key of Object.keys(hookHeaders)) {
|
|
1617
|
+
if (isForbiddenObjectKey(key))
|
|
1618
|
+
continue;
|
|
1619
|
+
const desc = Object.getOwnPropertyDescriptor(hookHeaders, key);
|
|
1620
|
+
if (!desc || !("value" in desc) || typeof desc.value !== "string")
|
|
1621
|
+
continue;
|
|
1622
|
+
setHeader(key, interpolateStringWithVars(desc.value, vars));
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
return out;
|
|
1626
|
+
}
|
|
1627
|
+
function resolveHttpBaseUrl(hook, options) {
|
|
1628
|
+
const domain = (hook.targetDomain ?? "api");
|
|
1629
|
+
const resolved = resolveTargetForInvariant({ domain, type: "http" }, { target: options.target, targets: options.targets });
|
|
1630
|
+
if (!resolved) {
|
|
1631
|
+
throw configError(`Fixture HTTP hook (${hook.method} ${hook.path}) requires an HTTP(S) target for domain "${domain}".`);
|
|
1632
|
+
}
|
|
1633
|
+
let parsed;
|
|
1634
|
+
try {
|
|
1635
|
+
parsed = new URL(resolved);
|
|
1636
|
+
}
|
|
1637
|
+
catch {
|
|
1638
|
+
throw configError(`Fixture HTTP hook target for domain "${domain}" must be a valid HTTP(S) URL.`);
|
|
1639
|
+
}
|
|
1640
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
1641
|
+
throw configError(`Fixture HTTP hook target protocol "${parsed.protocol}" is unsupported; only http: and https: are allowed.`);
|
|
1642
|
+
}
|
|
1643
|
+
return parsed;
|
|
1644
|
+
}
|
|
1645
|
+
function isExpectedHttpStatus(actual, expectStatus) {
|
|
1646
|
+
if (expectStatus === undefined) {
|
|
1647
|
+
return actual >= 200 && actual < 300;
|
|
1648
|
+
}
|
|
1649
|
+
if (Array.isArray(expectStatus)) {
|
|
1650
|
+
return expectStatus.includes(actual);
|
|
1651
|
+
}
|
|
1652
|
+
return actual === expectStatus;
|
|
1653
|
+
}
|
|
1654
|
+
function clampHookTimeout(hookTimeoutMs, defaultTimeoutMs) {
|
|
1655
|
+
const candidate = hookTimeoutMs ?? defaultTimeoutMs ?? DEFAULT_FIXTURE_HOOK_TIMEOUT_MS;
|
|
1656
|
+
if (!Number.isFinite(candidate))
|
|
1657
|
+
return DEFAULT_FIXTURE_HOOK_TIMEOUT_MS;
|
|
1658
|
+
return Math.max(MIN_FIXTURE_HOOK_TIMEOUT_MS, Math.min(MAX_FIXTURE_HOOK_TIMEOUT_MS, Math.floor(candidate)));
|
|
1659
|
+
}
|
|
1660
|
+
async function readBoundedResponseText(response, maxBytes) {
|
|
1661
|
+
if (response.body && typeof response.body.getReader === "function") {
|
|
1662
|
+
const reader = response.body.getReader();
|
|
1663
|
+
const chunks = [];
|
|
1664
|
+
let total = 0;
|
|
1665
|
+
try {
|
|
1666
|
+
while (total < maxBytes) {
|
|
1667
|
+
const { done, value } = await reader.read();
|
|
1668
|
+
if (done)
|
|
1669
|
+
break;
|
|
1670
|
+
if (!value || value.byteLength === 0)
|
|
1671
|
+
continue;
|
|
1672
|
+
const remaining = maxBytes - total;
|
|
1673
|
+
if (value.byteLength <= remaining) {
|
|
1674
|
+
chunks.push(value);
|
|
1675
|
+
total += value.byteLength;
|
|
1676
|
+
}
|
|
1677
|
+
else {
|
|
1678
|
+
chunks.push(value.subarray(0, remaining));
|
|
1679
|
+
total += remaining;
|
|
1680
|
+
break;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
finally {
|
|
1685
|
+
try {
|
|
1686
|
+
await reader.cancel();
|
|
1687
|
+
}
|
|
1688
|
+
catch {
|
|
1689
|
+
// ignore cancel error
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
return Buffer.concat(chunks, total).toString("utf8");
|
|
1693
|
+
}
|
|
1694
|
+
const rawText = await response.text();
|
|
1695
|
+
return rawText.length > maxBytes ? rawText.slice(0, maxBytes) : rawText;
|
|
1696
|
+
}
|
|
1697
|
+
async function executeHttpHook(hook, kind, options, scrub) {
|
|
1698
|
+
const started = Date.now();
|
|
1699
|
+
const displayTarget = scrub(`${hook.method} ${hook.path}`);
|
|
1700
|
+
try {
|
|
1701
|
+
const baseUrl = resolveHttpBaseUrl(hook, options);
|
|
1702
|
+
const interpolatedPath = interpolateStringWithVars(hook.path, options.vars);
|
|
1703
|
+
const pathErrors = [];
|
|
1704
|
+
const safePath = validateHttpHookPath(interpolatedPath, "httpHook.path", pathErrors);
|
|
1705
|
+
if (!safePath) {
|
|
1706
|
+
throw configError(pathErrors[0] ?? "Interpolated HTTP hook path is invalid.");
|
|
1707
|
+
}
|
|
1708
|
+
const finalUrl = new URL(safePath, baseUrl);
|
|
1709
|
+
if (finalUrl.origin !== baseUrl.origin ||
|
|
1710
|
+
finalUrl.username !== "" ||
|
|
1711
|
+
finalUrl.password !== "" ||
|
|
1712
|
+
finalUrl.pathname.startsWith("//") ||
|
|
1713
|
+
USERINFO_IN_FIRST_SEG_RE.test(finalUrl.pathname)) {
|
|
1714
|
+
throw configError("Fixture HTTP hook resolved outside target origin or included credentials.");
|
|
1715
|
+
}
|
|
1716
|
+
const headers = mergeHttpHeaders(options.headers, hook.headers, options.vars);
|
|
1717
|
+
let payload;
|
|
1718
|
+
if (hook.body !== undefined && hook.method !== "GET" && hook.method !== "HEAD") {
|
|
1719
|
+
const interpolatedBody = interpolateJsonWithVars(hook.body, options.vars);
|
|
1720
|
+
if (typeof interpolatedBody === "string") {
|
|
1721
|
+
payload = interpolatedBody;
|
|
1722
|
+
}
|
|
1723
|
+
else {
|
|
1724
|
+
payload = JSON.stringify(interpolatedBody);
|
|
1725
|
+
const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === "content-type");
|
|
1726
|
+
if (!hasContentType) {
|
|
1727
|
+
defineOwnProp(headers, "content-type", "application/json");
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
const timeoutMs = clampHookTimeout(hook.timeoutMs, options.timeoutMs);
|
|
1732
|
+
const controller = new AbortController();
|
|
1733
|
+
// Keep the abort timer ref'd: it may be the only handle keeping a hung fetchImpl alive (Node 22
|
|
1734
|
+
// otherwise exits the event loop early). The finally block below always clears it on settlement.
|
|
1735
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
1736
|
+
const fetchFn = options.fetchImpl ?? globalThis.fetch;
|
|
1737
|
+
if (typeof fetchFn !== "function") {
|
|
1738
|
+
clearTimeout(timer);
|
|
1739
|
+
throw new VibecodeError("EXEC_ERROR", "Global fetch is unavailable for fixture HTTP hook execution.");
|
|
1740
|
+
}
|
|
1741
|
+
let response;
|
|
1742
|
+
try {
|
|
1743
|
+
response = await fetchFn(finalUrl.toString(), {
|
|
1744
|
+
method: hook.method,
|
|
1745
|
+
headers,
|
|
1746
|
+
...(payload !== undefined ? { body: payload } : {}),
|
|
1747
|
+
redirect: "manual",
|
|
1748
|
+
signal: controller.signal
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
finally {
|
|
1752
|
+
clearTimeout(timer);
|
|
1753
|
+
}
|
|
1754
|
+
const status = response.status;
|
|
1755
|
+
// Always drain/cancel response body so keep-alive connections do not linger.
|
|
1756
|
+
// Scrub the full bounded error body BEFORE truncating so ANSI escapes or padding
|
|
1757
|
+
// can never split a secret across the truncation boundary.
|
|
1758
|
+
let scrubbedSnippet = "";
|
|
1759
|
+
try {
|
|
1760
|
+
if (isExpectedHttpStatus(status, hook.expectStatus)) {
|
|
1761
|
+
await response.body?.cancel?.();
|
|
1762
|
+
}
|
|
1763
|
+
else {
|
|
1764
|
+
const rawText = await readBoundedResponseText(response, MAX_HTTP_ERROR_BODY_READ_BYTES);
|
|
1765
|
+
scrubbedSnippet = sanitizeSingleLine(scrub(rawText), 140);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
catch {
|
|
1769
|
+
// ignore body read/cancel error
|
|
1770
|
+
}
|
|
1771
|
+
const durationMs = Date.now() - started;
|
|
1772
|
+
if (!isExpectedHttpStatus(status, hook.expectStatus)) {
|
|
1773
|
+
const expectedDesc = hook.expectStatus === undefined
|
|
1774
|
+
? "2xx"
|
|
1775
|
+
: Array.isArray(hook.expectStatus)
|
|
1776
|
+
? hook.expectStatus.join("|")
|
|
1777
|
+
: String(hook.expectStatus);
|
|
1778
|
+
const redirectHint = status >= 300 && status < 400 ? " (redirects disabled)" : "";
|
|
1779
|
+
const snippetPart = scrubbedSnippet ? `: ${scrubbedSnippet}` : "";
|
|
1780
|
+
const detail = scrub(`HTTP ${status}${redirectHint}; expected ${expectedDesc}${snippetPart}`);
|
|
1781
|
+
return {
|
|
1782
|
+
record: {
|
|
1783
|
+
kind,
|
|
1784
|
+
target: displayTarget,
|
|
1785
|
+
ok: false,
|
|
1786
|
+
status,
|
|
1787
|
+
durationMs,
|
|
1788
|
+
detail
|
|
1789
|
+
},
|
|
1790
|
+
errorCode: "EXEC_ERROR"
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
return {
|
|
1794
|
+
record: {
|
|
1795
|
+
kind,
|
|
1796
|
+
target: displayTarget,
|
|
1797
|
+
ok: true,
|
|
1798
|
+
status,
|
|
1799
|
+
durationMs
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
catch (err) {
|
|
1804
|
+
const durationMs = Date.now() - started;
|
|
1805
|
+
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
1806
|
+
const errorCode = isAbort
|
|
1807
|
+
? "EXEC_TIMEOUT"
|
|
1808
|
+
: err instanceof VibecodeError && err.code === "CONFIG_INVALID"
|
|
1809
|
+
? "CONFIG_INVALID"
|
|
1810
|
+
: "EXEC_ERROR";
|
|
1811
|
+
const detail = isAbort
|
|
1812
|
+
? `HTTP hook timed out after ${clampHookTimeout(hook.timeoutMs, options.timeoutMs)}ms`
|
|
1813
|
+
: sanitizeSingleLine(scrub(errorMessage(err)), 240);
|
|
1814
|
+
return {
|
|
1815
|
+
record: {
|
|
1816
|
+
kind,
|
|
1817
|
+
target: displayTarget,
|
|
1818
|
+
ok: false,
|
|
1819
|
+
durationMs,
|
|
1820
|
+
detail
|
|
1821
|
+
},
|
|
1822
|
+
errorCode
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
function executeCommandHook(hook, kind, rootDir, options, scrub) {
|
|
1827
|
+
const started = Date.now();
|
|
1828
|
+
const displayTarget = scrub(hook.command);
|
|
1829
|
+
const timeoutMs = clampHookTimeout(hook.timeoutMs, options.timeoutMs);
|
|
1830
|
+
const expectedExitCode = hook.expectExitCode ?? 0;
|
|
1831
|
+
try {
|
|
1832
|
+
const resolvedArgs = (hook.args ?? []).map((arg) => {
|
|
1833
|
+
const interpolated = interpolateStringWithVars(arg, options.vars);
|
|
1834
|
+
if (interpolated.includes("\0")) {
|
|
1835
|
+
throw configError("Interpolated fixture command argument contains a NUL byte.");
|
|
1836
|
+
}
|
|
1837
|
+
return interpolated;
|
|
1838
|
+
});
|
|
1839
|
+
let env = process.env;
|
|
1840
|
+
if (hook.env && Object.keys(hook.env).length > 0) {
|
|
1841
|
+
env = { ...process.env };
|
|
1842
|
+
for (const key of Object.keys(hook.env)) {
|
|
1843
|
+
if (isForbiddenObjectKey(key))
|
|
1844
|
+
continue;
|
|
1845
|
+
const interpolated = interpolateStringWithVars(hook.env[key], options.vars);
|
|
1846
|
+
if (interpolated.includes("\0")) {
|
|
1847
|
+
throw configError(`Interpolated fixture command env "${key}" contains a NUL byte.`);
|
|
1848
|
+
}
|
|
1849
|
+
env[key] = interpolated;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
let exitCode = 0;
|
|
1853
|
+
let stderrText = "";
|
|
1854
|
+
let timedOut = false;
|
|
1855
|
+
let spawnErrorMsg = "";
|
|
1856
|
+
try {
|
|
1857
|
+
execFileSync(hook.command, resolvedArgs, {
|
|
1858
|
+
cwd: rootDir,
|
|
1859
|
+
env,
|
|
1860
|
+
timeout: timeoutMs,
|
|
1861
|
+
shell: false,
|
|
1862
|
+
windowsHide: true,
|
|
1863
|
+
maxBuffer: MAX_COMMAND_OUTPUT_BYTES,
|
|
1864
|
+
encoding: "utf8",
|
|
1865
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1866
|
+
});
|
|
1867
|
+
}
|
|
1868
|
+
catch (err) {
|
|
1869
|
+
const execErr = err;
|
|
1870
|
+
if (execErr.code === "ETIMEDOUT") {
|
|
1871
|
+
timedOut = true;
|
|
1872
|
+
}
|
|
1873
|
+
else if (typeof execErr.status === "number") {
|
|
1874
|
+
exitCode = execErr.status;
|
|
1875
|
+
if (execErr.stderr !== undefined && execErr.stderr !== null) {
|
|
1876
|
+
stderrText = Buffer.isBuffer(execErr.stderr)
|
|
1877
|
+
? execErr.stderr.toString("utf8")
|
|
1878
|
+
: String(execErr.stderr);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
else {
|
|
1882
|
+
spawnErrorMsg = errorMessage(err);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
const durationMs = Date.now() - started;
|
|
1886
|
+
if (timedOut) {
|
|
1887
|
+
return {
|
|
1888
|
+
record: {
|
|
1889
|
+
kind,
|
|
1890
|
+
target: displayTarget,
|
|
1891
|
+
ok: false,
|
|
1892
|
+
durationMs,
|
|
1893
|
+
detail: `command hook timed out after ${timeoutMs}ms`
|
|
1894
|
+
},
|
|
1895
|
+
errorCode: "EXEC_TIMEOUT"
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
if (spawnErrorMsg) {
|
|
1899
|
+
return {
|
|
1900
|
+
record: {
|
|
1901
|
+
kind,
|
|
1902
|
+
target: displayTarget,
|
|
1903
|
+
ok: false,
|
|
1904
|
+
durationMs,
|
|
1905
|
+
detail: sanitizeSingleLine(scrub(spawnErrorMsg), 240)
|
|
1906
|
+
},
|
|
1907
|
+
errorCode: "EXEC_ERROR"
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
if (exitCode !== expectedExitCode) {
|
|
1911
|
+
const stderrSnippet = stderrText ? `: ${sanitizeSingleLine(scrub(stderrText), 140)}` : "";
|
|
1912
|
+
return {
|
|
1913
|
+
record: {
|
|
1914
|
+
kind,
|
|
1915
|
+
target: displayTarget,
|
|
1916
|
+
ok: false,
|
|
1917
|
+
status: exitCode,
|
|
1918
|
+
durationMs,
|
|
1919
|
+
detail: scrub(`exit code ${exitCode}; expected ${expectedExitCode}${stderrSnippet}`)
|
|
1920
|
+
},
|
|
1921
|
+
errorCode: "EXEC_ERROR"
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
return {
|
|
1925
|
+
record: {
|
|
1926
|
+
kind,
|
|
1927
|
+
target: displayTarget,
|
|
1928
|
+
ok: true,
|
|
1929
|
+
status: exitCode,
|
|
1930
|
+
durationMs
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
catch (err) {
|
|
1935
|
+
const errorCode = err instanceof VibecodeError && err.code === "CONFIG_INVALID" ? "CONFIG_INVALID" : "EXEC_ERROR";
|
|
1936
|
+
return {
|
|
1937
|
+
record: {
|
|
1938
|
+
kind,
|
|
1939
|
+
target: displayTarget,
|
|
1940
|
+
ok: false,
|
|
1941
|
+
durationMs: Date.now() - started,
|
|
1942
|
+
detail: sanitizeSingleLine(scrub(errorMessage(err)), 240)
|
|
1943
|
+
},
|
|
1944
|
+
errorCode
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
function hasConfiguredFixtures(fixtures) {
|
|
1949
|
+
return Boolean((fixtures.seedFiles && fixtures.seedFiles.length > 0) ||
|
|
1950
|
+
(fixtures.snapshotPaths && fixtures.snapshotPaths.length > 0) ||
|
|
1951
|
+
(fixtures.httpSetup && fixtures.httpSetup.length > 0) ||
|
|
1952
|
+
(fixtures.httpTeardown && fixtures.httpTeardown.length > 0) ||
|
|
1953
|
+
(fixtures.commandSetup && fixtures.commandSetup.length > 0) ||
|
|
1954
|
+
(fixtures.commandTeardown && fixtures.commandTeardown.length > 0));
|
|
1955
|
+
}
|
|
1956
|
+
function createEmptySummary(totalDurationMs, warnings = []) {
|
|
1957
|
+
return {
|
|
1958
|
+
applied: false,
|
|
1959
|
+
rolledBack: false,
|
|
1960
|
+
seededFiles: 0,
|
|
1961
|
+
restoredPaths: 0,
|
|
1962
|
+
removedNewPaths: 0,
|
|
1963
|
+
httpSetupCount: 0,
|
|
1964
|
+
httpTeardownCount: 0,
|
|
1965
|
+
commandSetupCount: 0,
|
|
1966
|
+
commandTeardownCount: 0,
|
|
1967
|
+
failedHooks: 0,
|
|
1968
|
+
warnings,
|
|
1969
|
+
records: [],
|
|
1970
|
+
totalDurationMs
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
function attachFixtureSummaryToError(err, summary) {
|
|
1974
|
+
if (err !== null && (typeof err === "object" || typeof err === "function")) {
|
|
1975
|
+
try {
|
|
1976
|
+
Object.defineProperty(err, "fixtureSummary", {
|
|
1977
|
+
value: summary,
|
|
1978
|
+
enumerable: false,
|
|
1979
|
+
writable: true,
|
|
1980
|
+
configurable: true
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
catch {
|
|
1984
|
+
// ignore frozen or non-extensible error objects
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* Executes `runFn()` wrapped in declarative fixture setup and GUARANTEED `finally`
|
|
1990
|
+
* teardown + workspace snapshot rollback.
|
|
1991
|
+
*/
|
|
1992
|
+
export async function runWithFixtures(fixtures, options, runFn) {
|
|
1993
|
+
const overallStarted = Date.now();
|
|
1994
|
+
if (!options || typeof options !== "object") {
|
|
1995
|
+
throw configError("Fixture execution options must be an object with a valid workspace cwd.");
|
|
1996
|
+
}
|
|
1997
|
+
if (!fixtures || options.skipFixtures === true) {
|
|
1998
|
+
const result = await runFn();
|
|
1999
|
+
return {
|
|
2000
|
+
result,
|
|
2001
|
+
fixtureSummary: createEmptySummary(Date.now() - overallStarted)
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
const validation = validateContractFixtures(fixtures);
|
|
2005
|
+
if (!validation.valid || !validation.normalized) {
|
|
2006
|
+
throw configError(`Invalid contract fixtures: ${validation.errors[0] ?? "validation failed"}`, { errors: validation.errors });
|
|
2007
|
+
}
|
|
2008
|
+
const normalized = validation.normalized;
|
|
2009
|
+
if (!hasConfiguredFixtures(normalized)) {
|
|
2010
|
+
const result = await runFn();
|
|
2011
|
+
return {
|
|
2012
|
+
result,
|
|
2013
|
+
fixtureSummary: createEmptySummary(Date.now() - overallStarted)
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
const hasCommandHooks = Boolean((normalized.commandSetup && normalized.commandSetup.length > 0) ||
|
|
2017
|
+
(normalized.commandTeardown && normalized.commandTeardown.length > 0));
|
|
2018
|
+
if (hasCommandHooks && options.allowCommandHooks !== true) {
|
|
2019
|
+
throw new VibecodeError("CONFIG_INVALID", "Fixture command hooks require explicit CLI opt-in (allowCommandHooks) and are disabled over MCP.");
|
|
2020
|
+
}
|
|
2021
|
+
const extraSecrets = collectExtraSecrets(options.headers, [...(normalized.httpSetup ?? []), ...(normalized.httpTeardown ?? [])], [...(normalized.commandSetup ?? []), ...(normalized.commandTeardown ?? [])]);
|
|
2022
|
+
const scrub = (text) => scrubFixtureText(text, options.vars, extraSecrets);
|
|
2023
|
+
const summary = {
|
|
2024
|
+
applied: true,
|
|
2025
|
+
rolledBack: false,
|
|
2026
|
+
seededFiles: 0,
|
|
2027
|
+
restoredPaths: 0,
|
|
2028
|
+
removedNewPaths: 0,
|
|
2029
|
+
httpSetupCount: 0,
|
|
2030
|
+
httpTeardownCount: 0,
|
|
2031
|
+
commandSetupCount: 0,
|
|
2032
|
+
commandTeardownCount: 0,
|
|
2033
|
+
failedHooks: 0,
|
|
2034
|
+
warnings: validation.warnings.map((w) => sanitizeSingleLine(scrub(w), 300)),
|
|
2035
|
+
records: [],
|
|
2036
|
+
totalDurationMs: 0
|
|
2037
|
+
};
|
|
2038
|
+
const rootDir = resolveCanonicalWorkspaceRoot(options.cwd);
|
|
2039
|
+
// Automatically union snapshotPaths + seedFiles paths BEFORE any mutation on disk.
|
|
2040
|
+
const unionSnapshotPaths = [];
|
|
2041
|
+
const seenPaths = new Set();
|
|
2042
|
+
for (const p of normalized.snapshotPaths ?? []) {
|
|
2043
|
+
const k = canonicalRelKey(p);
|
|
2044
|
+
if (!seenPaths.has(k)) {
|
|
2045
|
+
seenPaths.add(k);
|
|
2046
|
+
unionSnapshotPaths.push(p);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
for (const seed of normalized.seedFiles ?? []) {
|
|
2050
|
+
const k = canonicalRelKey(seed.path);
|
|
2051
|
+
if (!seenPaths.has(k)) {
|
|
2052
|
+
seenPaths.add(k);
|
|
2053
|
+
unionSnapshotPaths.push(seed.path);
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
let snapshot = null;
|
|
2057
|
+
if (unionSnapshotPaths.length > 0) {
|
|
2058
|
+
const snapStarted = Date.now();
|
|
2059
|
+
snapshot = captureWorkspaceSnapshotsInternal(rootDir, unionSnapshotPaths, MAX_FIXTURE_SNAPSHOT_PATHS + MAX_FIXTURE_SEED_FILES);
|
|
2060
|
+
summary.records.push({
|
|
2061
|
+
kind: "snapshot",
|
|
2062
|
+
target: scrub(`${snapshot.entries.length} path(s)`),
|
|
2063
|
+
ok: true,
|
|
2064
|
+
durationMs: Date.now() - snapStarted,
|
|
2065
|
+
detail: scrub(`captured ${snapshot.totalFiles} file(s), ${snapshot.totalBytes} bytes`)
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
let runResult;
|
|
2069
|
+
let caughtError = undefined;
|
|
2070
|
+
let hasCaughtError = false;
|
|
2071
|
+
let teardownFailures = 0;
|
|
2072
|
+
try {
|
|
2073
|
+
// 1. Apply seedFiles
|
|
2074
|
+
for (const seed of normalized.seedFiles ?? []) {
|
|
2075
|
+
const seedStarted = Date.now();
|
|
2076
|
+
const safeTarget = scrub(seed.path);
|
|
2077
|
+
try {
|
|
2078
|
+
const bytes = decodeSeedBytes(seed);
|
|
2079
|
+
safeAtomicWriteFile(rootDir, seed.path, bytes);
|
|
2080
|
+
summary.seededFiles += 1;
|
|
2081
|
+
summary.records.push({
|
|
2082
|
+
kind: "seed",
|
|
2083
|
+
target: safeTarget,
|
|
2084
|
+
ok: true,
|
|
2085
|
+
durationMs: Date.now() - seedStarted,
|
|
2086
|
+
detail: `${bytes.byteLength} bytes`
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
catch (err) {
|
|
2090
|
+
const detail = sanitizeSingleLine(scrub(errorMessage(err)), 240);
|
|
2091
|
+
summary.failedHooks += 1;
|
|
2092
|
+
summary.records.push({
|
|
2093
|
+
kind: "seed",
|
|
2094
|
+
target: safeTarget,
|
|
2095
|
+
ok: false,
|
|
2096
|
+
durationMs: Date.now() - seedStarted,
|
|
2097
|
+
detail
|
|
2098
|
+
});
|
|
2099
|
+
throw new VibecodeError("EXEC_ERROR", scrub(`Failed to seed fixture file "${seed.path}": ${detail}`));
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
// 2. Run commandSetup hooks (shell-free)
|
|
2103
|
+
for (const hook of normalized.commandSetup ?? []) {
|
|
2104
|
+
const outcome = executeCommandHook(hook, "command_setup", rootDir, options, scrub);
|
|
2105
|
+
const rec = outcome.record;
|
|
2106
|
+
summary.commandSetupCount += 1;
|
|
2107
|
+
summary.records.push(rec);
|
|
2108
|
+
if (!rec.ok) {
|
|
2109
|
+
summary.failedHooks += 1;
|
|
2110
|
+
throw new VibecodeError(outcome.errorCode ?? "EXEC_ERROR", scrub(`Fixture commandSetup failed (${rec.target}): ${rec.detail ?? "non-zero exit"}`));
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
// 3. Run httpSetup hooks
|
|
2114
|
+
for (const hook of normalized.httpSetup ?? []) {
|
|
2115
|
+
const outcome = await executeHttpHook(hook, "http_setup", options, scrub);
|
|
2116
|
+
const rec = outcome.record;
|
|
2117
|
+
summary.httpSetupCount += 1;
|
|
2118
|
+
summary.records.push(rec);
|
|
2119
|
+
if (!rec.ok) {
|
|
2120
|
+
summary.failedHooks += 1;
|
|
2121
|
+
throw new VibecodeError(outcome.errorCode ?? "EXEC_ERROR", scrub(`Fixture httpSetup failed (${rec.target}): ${rec.detail ?? "unexpected response"}`));
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
// 4. Execute guarded verification / user callback
|
|
2125
|
+
runResult = await runFn();
|
|
2126
|
+
}
|
|
2127
|
+
catch (err) {
|
|
2128
|
+
caughtError = err;
|
|
2129
|
+
hasCaughtError = true;
|
|
2130
|
+
}
|
|
2131
|
+
finally {
|
|
2132
|
+
// ALWAYS run teardown + rollback in strict order:
|
|
2133
|
+
// 1. httpTeardown (best-effort across all hooks)
|
|
2134
|
+
for (const hook of normalized.httpTeardown ?? []) {
|
|
2135
|
+
const { record: rec } = await executeHttpHook(hook, "http_teardown", options, scrub);
|
|
2136
|
+
summary.httpTeardownCount += 1;
|
|
2137
|
+
summary.records.push(rec);
|
|
2138
|
+
if (!rec.ok) {
|
|
2139
|
+
summary.failedHooks += 1;
|
|
2140
|
+
teardownFailures += 1;
|
|
2141
|
+
summary.warnings.push(sanitizeSingleLine(scrub(`httpTeardown failed (${rec.target}): ${rec.detail ?? "error"}`), 300));
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
// 2. commandTeardown (best-effort, only when explicitly opted in)
|
|
2145
|
+
if (options.allowCommandHooks === true) {
|
|
2146
|
+
for (const hook of normalized.commandTeardown ?? []) {
|
|
2147
|
+
const { record: rec } = executeCommandHook(hook, "command_teardown", rootDir, options, scrub);
|
|
2148
|
+
summary.commandTeardownCount += 1;
|
|
2149
|
+
summary.records.push(rec);
|
|
2150
|
+
if (!rec.ok) {
|
|
2151
|
+
summary.failedHooks += 1;
|
|
2152
|
+
teardownFailures += 1;
|
|
2153
|
+
summary.warnings.push(sanitizeSingleLine(scrub(`commandTeardown failed (${rec.target}): ${rec.detail ?? "error"}`), 300));
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
// 3. Disk rollback ALWAYS runs last so workspace returns to exact pre-run state.
|
|
2158
|
+
let rollbackErrors = [];
|
|
2159
|
+
if (snapshot) {
|
|
2160
|
+
const rbStarted = Date.now();
|
|
2161
|
+
const restored = restoreWorkspaceSnapshots(snapshot);
|
|
2162
|
+
summary.restoredPaths = restored.restoredPaths;
|
|
2163
|
+
summary.removedNewPaths = restored.removedNewPaths;
|
|
2164
|
+
rollbackErrors = restored.errors.map((e) => sanitizeSingleLine(scrub(e), 300));
|
|
2165
|
+
for (const rbErr of rollbackErrors) {
|
|
2166
|
+
summary.warnings.push(rbErr);
|
|
2167
|
+
}
|
|
2168
|
+
summary.records.push({
|
|
2169
|
+
kind: "rollback",
|
|
2170
|
+
target: scrub(`${snapshot.entries.length} path(s)`),
|
|
2171
|
+
ok: rollbackErrors.length === 0,
|
|
2172
|
+
durationMs: Date.now() - rbStarted,
|
|
2173
|
+
detail: scrub(rollbackErrors.length === 0
|
|
2174
|
+
? `restored ${restored.restoredPaths}, removed ${restored.removedNewPaths}`
|
|
2175
|
+
: `restored ${restored.restoredPaths}, removed ${restored.removedNewPaths}, errors ${rollbackErrors.length}`)
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
summary.rolledBack = teardownFailures === 0 && rollbackErrors.length === 0;
|
|
2179
|
+
summary.totalDurationMs = Date.now() - overallStarted;
|
|
2180
|
+
if (hasCaughtError) {
|
|
2181
|
+
attachFixtureSummaryToError(caughtError, summary);
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
if (hasCaughtError) {
|
|
2185
|
+
throw caughtError;
|
|
2186
|
+
}
|
|
2187
|
+
return { result: runResult, fixtureSummary: summary };
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Formats a concise, sanitized terminal summary for a `FixtureRunSummary`.
|
|
2191
|
+
*/
|
|
2192
|
+
export function formatPrettyFixtureSummary(summary, options = {}) {
|
|
2193
|
+
const useColor = options.color === true;
|
|
2194
|
+
const banner = styleAnsi("[FIXTURES]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
2195
|
+
if (!summary.applied) {
|
|
2196
|
+
return `${banner} ${styleAnsi("SKIPPED", ANSI.dim, useColor)} (no fixtures applied)`;
|
|
2197
|
+
}
|
|
2198
|
+
const lines = [];
|
|
2199
|
+
const hasWarnings = summary.warnings.length > 0 || summary.failedHooks > 0;
|
|
2200
|
+
const statusLabel = !summary.rolledBack
|
|
2201
|
+
? styleAnsi("ROLLBACK INCOMPLETE", `${ANSI.bold}${ANSI.red}`, useColor)
|
|
2202
|
+
: hasWarnings
|
|
2203
|
+
? styleAnsi("ROLLED BACK (WITH WARNINGS)", `${ANSI.bold}${ANSI.yellow}`, useColor)
|
|
2204
|
+
: styleAnsi("ROLLED BACK", `${ANSI.bold}${ANSI.green}`, useColor);
|
|
2205
|
+
const totalMs = Number.isFinite(summary.totalDurationMs) ? Math.max(0, Math.round(summary.totalDurationMs)) : 0;
|
|
2206
|
+
lines.push(`${banner} ${statusLabel} (${totalMs}ms)`);
|
|
2207
|
+
lines.push(`Disk: seeded ${summary.seededFiles}, restored ${summary.restoredPaths}, removed ${summary.removedNewPaths}`);
|
|
2208
|
+
const hookParts = [
|
|
2209
|
+
`http ${summary.httpSetupCount} setup / ${summary.httpTeardownCount} teardown`,
|
|
2210
|
+
`cmd ${summary.commandSetupCount} setup / ${summary.commandTeardownCount} teardown`
|
|
2211
|
+
];
|
|
2212
|
+
if (summary.failedHooks > 0) {
|
|
2213
|
+
hookParts.push(styleAnsi(`${summary.failedHooks} failed`, ANSI.red, useColor));
|
|
2214
|
+
}
|
|
2215
|
+
lines.push(`Hooks: ${hookParts.join(", ")}`);
|
|
2216
|
+
if (Array.isArray(summary.records) && summary.records.length > 0) {
|
|
2217
|
+
lines.push("Phases:");
|
|
2218
|
+
for (const rec of summary.records.slice(0, MAX_PRETTY_RECORDS)) {
|
|
2219
|
+
const badge = rec.ok ? styleAnsi("OK", ANSI.green, useColor) : styleAnsi("FAIL", ANSI.red, useColor);
|
|
2220
|
+
const safeKind = sanitizeSingleLine(String(rec.kind), 32);
|
|
2221
|
+
const safeTarget = sanitizeSingleLine(String(rec.target), 120);
|
|
2222
|
+
const meta = [];
|
|
2223
|
+
if (typeof rec.status === "number" && Number.isFinite(rec.status)) {
|
|
2224
|
+
meta.push(`status=${rec.status}`);
|
|
2225
|
+
}
|
|
2226
|
+
const dur = Number.isFinite(rec.durationMs) ? Math.max(0, Math.round(rec.durationMs)) : 0;
|
|
2227
|
+
meta.push(`${dur}ms`);
|
|
2228
|
+
const detail = rec.detail ? ` — ${sanitizeSingleLine(String(rec.detail), 160)}` : "";
|
|
2229
|
+
lines.push(` [${badge}] ${safeKind} ${safeTarget} (${meta.join(", ")})${detail}`);
|
|
2230
|
+
}
|
|
2231
|
+
if (summary.records.length > MAX_PRETTY_RECORDS) {
|
|
2232
|
+
lines.push(` ${styleAnsi(`... and ${summary.records.length - MAX_PRETTY_RECORDS} more`, ANSI.dim, useColor)}`);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
if (Array.isArray(summary.warnings) && summary.warnings.length > 0) {
|
|
2236
|
+
lines.push("Warnings:");
|
|
2237
|
+
for (const warning of summary.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
|
|
2238
|
+
lines.push(` - ${styleAnsi(sanitizeSingleLine(String(warning), 220), ANSI.yellow, useColor)}`);
|
|
2239
|
+
}
|
|
2240
|
+
if (summary.warnings.length > MAX_PRETTY_WARNINGS) {
|
|
2241
|
+
lines.push(` ${styleAnsi(`... and ${summary.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
return lines.join("\n");
|
|
2245
|
+
}
|