@visulima/vis 1.0.0-alpha.11 → 1.0.0-alpha.13
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/CHANGELOG.md +101 -0
- package/LICENSE.md +559 -186
- package/README.md +18 -0
- package/dist/bin.js +1 -9
- package/dist/config/index.d.ts +477 -556
- package/dist/config/index.js +1 -2
- package/dist/generate/index.js +1 -3
- package/dist/packem_chunks/applyDefaults.js +2 -336
- package/dist/packem_chunks/bin.js +234 -9552
- package/dist/packem_chunks/doctor-probe.js +2 -112
- package/dist/packem_chunks/fix.js +11 -234
- package/dist/packem_chunks/handler.js +1 -99
- package/dist/packem_chunks/handler10.js +2 -53
- package/dist/packem_chunks/handler11.js +1 -32
- package/dist/packem_chunks/handler12.js +5 -100
- package/dist/packem_chunks/handler13.js +1 -25
- package/dist/packem_chunks/handler14.js +18 -916
- package/dist/packem_chunks/handler15.js +15 -201
- package/dist/packem_chunks/handler16.js +1 -124
- package/dist/packem_chunks/handler17.js +1 -13
- package/dist/packem_chunks/handler18.js +1 -106
- package/dist/packem_chunks/handler19.js +1 -19
- package/dist/packem_chunks/handler2.js +2 -75
- package/dist/packem_chunks/handler20.js +5 -29
- package/dist/packem_chunks/handler21.js +1 -222
- package/dist/packem_chunks/handler22.js +1 -237
- package/dist/packem_chunks/handler23.js +5 -101
- package/dist/packem_chunks/handler24.js +1 -110
- package/dist/packem_chunks/handler25.js +3 -402
- package/dist/packem_chunks/handler26.js +1 -13
- package/dist/packem_chunks/handler27.js +1 -63
- package/dist/packem_chunks/handler28.js +7 -34
- package/dist/packem_chunks/handler29.js +21 -456
- package/dist/packem_chunks/handler3.js +4 -95
- package/dist/packem_chunks/handler30.js +3 -170
- package/dist/packem_chunks/handler31.js +1 -530
- package/dist/packem_chunks/handler32.js +2 -214
- package/dist/packem_chunks/handler33.js +25 -119
- package/dist/packem_chunks/handler34.js +2 -630
- package/dist/packem_chunks/handler35.js +3 -283
- package/dist/packem_chunks/handler36.js +22 -542
- package/dist/packem_chunks/handler37.js +410 -744
- package/dist/packem_chunks/handler38.js +22 -989
- package/dist/packem_chunks/handler39.js +22 -574
- package/dist/packem_chunks/handler4.js +2 -90
- package/dist/packem_chunks/handler40.js +22 -1685
- package/dist/packem_chunks/handler41.js +6 -1088
- package/dist/packem_chunks/handler42.js +5 -797
- package/dist/packem_chunks/handler43.js +10 -2658
- package/dist/packem_chunks/handler44.js +51 -3784
- package/dist/packem_chunks/handler45.js +25 -2574
- package/dist/packem_chunks/handler46.js +3 -3769
- package/dist/packem_chunks/handler47.js +21 -1485
- package/dist/packem_chunks/handler48.js +42 -0
- package/dist/packem_chunks/handler5.js +8 -174
- package/dist/packem_chunks/handler6.js +1 -95
- package/dist/packem_chunks/handler7.js +1 -115
- package/dist/packem_chunks/handler8.js +1 -12
- package/dist/packem_chunks/handler9.js +1 -29
- package/dist/packem_chunks/heal-accept.js +10 -522
- package/dist/packem_chunks/heal.js +14 -673
- package/dist/packem_chunks/index.js +7 -873
- package/dist/packem_chunks/loader.js +1 -23
- package/dist/packem_chunks/tar.js +3 -0
- package/dist/packem_shared/ai-analysis-hm8d2W7z.js +67 -0
- package/dist/packem_shared/ai-cache-DoiF80AR.js +1 -0
- package/dist/packem_shared/ai-fix-nn4zOE95.js +43 -0
- package/dist/packem_shared/cache-directory-CwHlJhgx.js +1 -0
- package/dist/packem_shared/dependency-scan-COr5n63B.js +2 -0
- package/dist/packem_shared/docker-D6OGr5_S.js +2 -0
- package/dist/packem_shared/failure-log-iUVLf6ts.js +2 -0
- package/dist/packem_shared/flakiness-D9wf0t56.js +1 -0
- package/dist/packem_shared/giget-CcEy_Elm.js +2 -0
- package/dist/packem_shared/index-DH-5hsrC.js +1 -0
- package/dist/packem_shared/otel-DxDUPJJH.js +6 -0
- package/dist/packem_shared/otelPlugin-CQq6poq8.js +1 -0
- package/dist/packem_shared/registry-CkubDdiY.js +2 -0
- package/dist/packem_shared/run-summary-utils-BfBvjzhY.js +1 -0
- package/dist/packem_shared/runtime-check-BXZ43CBW.js +1 -0
- package/dist/packem_shared/selectors-BylODRiM.js +3 -0
- package/dist/packem_shared/symbols-CQmER5MT.js +1 -0
- package/dist/packem_shared/toolchain-BgBOUHII.js +5 -0
- package/dist/packem_shared/typosquats-CcZl99B1.js +1 -0
- package/dist/packem_shared/use-measured-height-DjYgUOKk.js +1 -0
- package/dist/packem_shared/utils-DrNg0XTR.js +1 -0
- package/dist/packem_shared/verify-Baj5mFJ7.js +1 -0
- package/dist/packem_shared/vis-update-app-D1jl0UZZ.js +1 -0
- package/dist/packem_shared/xxh3-DrAUNq4n.js +1 -0
- package/index.js +556 -727
- package/package.json +19 -29
- package/schemas/project.schema.json +739 -297
- package/schemas/vis-config.schema.json +3365 -384
- package/templates/buildkite-ci/template.yml +20 -20
- package/dist/packem_shared/VisUpdateApp-D-Yz_wvg.js +0 -1316
- package/dist/packem_shared/_commonjsHelpers-BqLXS_qQ.js +0 -5
- package/dist/packem_shared/ai-analysis-CHeB1joD.js +0 -367
- package/dist/packem_shared/ai-cache-Be_jexe4.js +0 -142
- package/dist/packem_shared/ai-fix-B9iQVcD2.js +0 -379
- package/dist/packem_shared/cache-directory-2qvs4goY.js +0 -98
- package/dist/packem_shared/catalog-BJTtyi-O.js +0 -1371
- package/dist/packem_shared/dependency-scan-A0KSklpG.js +0 -188
- package/dist/packem_shared/docker-2iZzc280.js +0 -181
- package/dist/packem_shared/failure-log-Cz3Z4SKL.js +0 -100
- package/dist/packem_shared/flakiness-goTxXuCX.js +0 -180
- package/dist/packem_shared/otel-DCvqCTz_.js +0 -158
- package/dist/packem_shared/otelPlugin-DFaLDvJf.js +0 -3
- package/dist/packem_shared/registry-CbqXI0rc.js +0 -272
- package/dist/packem_shared/run-summary-utils-PVMl4aIh.js +0 -130
- package/dist/packem_shared/runtime-check-Cobi3p6l.js +0 -127
- package/dist/packem_shared/selectors-SM69TfqC.js +0 -194
- package/dist/packem_shared/symbols-Ta7g2nU-.js +0 -14
- package/dist/packem_shared/toolchain-BdZd9eBi.js +0 -975
- package/dist/packem_shared/typosquats-C-bCh3PX.js +0 -1210
- package/dist/packem_shared/use-measured-height-CNP0vT4M.js +0 -20
- package/dist/packem_shared/utils-CthVdBPS.js +0 -40
- package/dist/packem_shared/xxh3-Ck8mXNg1.js +0 -239
|
@@ -1,574 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
import { redact } from '@visulima/redact';
|
|
24
|
-
import { fingerprint, scan, scanFiles, inspectRuleset, listRules, listRequiredValidators } from '@visulima/secret-scanner';
|
|
25
|
-
import { p as pail } from './bin.js';
|
|
26
|
-
import { InteractiveManager, InteractiveStreamHook } from '@visulima/interactive-manager';
|
|
27
|
-
import { Spinner } from '@visulima/spinner';
|
|
28
|
-
const {
|
|
29
|
-
pathToFileURL
|
|
30
|
-
} = __cjs_getBuiltinModule("node:url");
|
|
31
|
-
const {
|
|
32
|
-
execFileSync
|
|
33
|
-
} = __cjs_getBuiltinModule("node:child_process");
|
|
34
|
-
|
|
35
|
-
const createSpinner = (options = {}) => {
|
|
36
|
-
const manager = new InteractiveManager(new InteractiveStreamHook(process.stdout), new InteractiveStreamHook(process.stderr));
|
|
37
|
-
return new Spinner(options, manager);
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
const toRelative = (file, root) => {
|
|
41
|
-
if (!isAbsolute(file)) {
|
|
42
|
-
return file;
|
|
43
|
-
}
|
|
44
|
-
const rel = relative(root, file);
|
|
45
|
-
return rel === "" || rel.startsWith("..") ? file : rel;
|
|
46
|
-
};
|
|
47
|
-
const toRelativeFinding = (f, root) => {
|
|
48
|
-
const relativeFile = toRelative(f.file, root);
|
|
49
|
-
return relativeFile === f.file ? f : { ...f, file: relativeFile };
|
|
50
|
-
};
|
|
51
|
-
const readBaseline = (baselinePath) => {
|
|
52
|
-
if (!isAccessibleSync(baselinePath)) {
|
|
53
|
-
return [];
|
|
54
|
-
}
|
|
55
|
-
try {
|
|
56
|
-
const parsed = readJsonSync(baselinePath);
|
|
57
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
58
|
-
} catch {
|
|
59
|
-
return [];
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
const diffBaseline = (findings, baselinePath, root) => {
|
|
63
|
-
const existing = readBaseline(baselinePath).map((f) => toRelativeFinding(f, root));
|
|
64
|
-
const existingKeys = new Set(existing.map((f) => fingerprint(f)));
|
|
65
|
-
const currentRelative = findings.map((f) => toRelativeFinding(f, root));
|
|
66
|
-
const currentKeys = new Set(currentRelative.map((f) => fingerprint(f)));
|
|
67
|
-
return {
|
|
68
|
-
fresh: currentRelative.filter((f) => !existingKeys.has(fingerprint(f))),
|
|
69
|
-
resolved: existing.filter((f) => !currentKeys.has(fingerprint(f))),
|
|
70
|
-
surviving: currentRelative.filter((f) => existingKeys.has(fingerprint(f)))
|
|
71
|
-
};
|
|
72
|
-
};
|
|
73
|
-
const writeBaseline = (findings, baselinePath, root, options = {}) => {
|
|
74
|
-
const incoming = findings.map((f) => toRelativeFinding(f, root));
|
|
75
|
-
let final;
|
|
76
|
-
if (options.replace) {
|
|
77
|
-
final = incoming;
|
|
78
|
-
} else {
|
|
79
|
-
const existing = readBaseline(baselinePath).map((f) => toRelativeFinding(f, root));
|
|
80
|
-
const seen = /* @__PURE__ */ new Set();
|
|
81
|
-
final = [];
|
|
82
|
-
for (const f of [...existing, ...incoming]) {
|
|
83
|
-
const key = fingerprint(f);
|
|
84
|
-
if (seen.has(key)) {
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
seen.add(key);
|
|
88
|
-
final.push(f);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
writeFileSync(baselinePath, `${JSON.stringify(final, null, 4)}
|
|
92
|
-
`);
|
|
93
|
-
return final.length;
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
const CONTEXT_RADIUS = 1;
|
|
97
|
-
const groupByFile = (findings) => {
|
|
98
|
-
const byFile = /* @__PURE__ */ new Map();
|
|
99
|
-
for (const f of findings) {
|
|
100
|
-
const list = byFile.get(f.file);
|
|
101
|
-
if (list) {
|
|
102
|
-
list.push(f);
|
|
103
|
-
} else {
|
|
104
|
-
byFile.set(f.file, [f]);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
return byFile;
|
|
108
|
-
};
|
|
109
|
-
const loadLines = (file) => {
|
|
110
|
-
try {
|
|
111
|
-
return readFileSync(file).split(/\r?\n/);
|
|
112
|
-
} catch {
|
|
113
|
-
return void 0;
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
const caretFor = (line, col, len) => {
|
|
117
|
-
const clampedCol = Math.max(1, col);
|
|
118
|
-
const prefix = line.slice(0, clampedCol - 1).replaceAll(/[^\t]/g, " ");
|
|
119
|
-
return `${prefix}${"^".repeat(Math.max(1, len))}`;
|
|
120
|
-
};
|
|
121
|
-
const formatText = (findings, root, useColor, options = {}) => {
|
|
122
|
-
if (findings.length === 0) {
|
|
123
|
-
return useColor ? dim("No secrets detected.") : "No secrets detected.";
|
|
124
|
-
}
|
|
125
|
-
const color = useColor ? { cyan, dim, green, red, yellow } : {
|
|
126
|
-
cyan: (s) => s,
|
|
127
|
-
dim: (s) => s,
|
|
128
|
-
green: (s) => s,
|
|
129
|
-
red: (s) => s,
|
|
130
|
-
yellow: (s) => s
|
|
131
|
-
};
|
|
132
|
-
const lines = [];
|
|
133
|
-
const byFile = groupByFile(findings);
|
|
134
|
-
for (const [file, items] of byFile) {
|
|
135
|
-
const relativeFile = relative(root, file) || file;
|
|
136
|
-
lines.push(color.cyan(relativeFile));
|
|
137
|
-
const sourceLines = options.redact ? void 0 : loadLines(file);
|
|
138
|
-
for (const f of items) {
|
|
139
|
-
const provenance = [f.source, f.confidence].filter(Boolean).join(", ");
|
|
140
|
-
const provenanceSuffix = provenance ? ` ${color.dim(`(${provenance})`)}` : "";
|
|
141
|
-
const alternates = f.alternateMatches && f.alternateMatches.length > 0 ? ` ${color.dim(`also: ${f.alternateMatches.join(", ")}`)}` : "";
|
|
142
|
-
let validationBadge = "";
|
|
143
|
-
switch (f.validation) {
|
|
144
|
-
case "error": {
|
|
145
|
-
validationBadge = ` ${color.yellow("! error")}`;
|
|
146
|
-
break;
|
|
147
|
-
}
|
|
148
|
-
case "rejected": {
|
|
149
|
-
validationBadge = ` ${color.red("✗ rejected")}`;
|
|
150
|
-
break;
|
|
151
|
-
}
|
|
152
|
-
case "skipped": {
|
|
153
|
-
validationBadge = ` ${color.dim("— unverifiable")}`;
|
|
154
|
-
break;
|
|
155
|
-
}
|
|
156
|
-
case "verified": {
|
|
157
|
-
validationBadge = ` ${color.green("✓ verified")}`;
|
|
158
|
-
break;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
lines.push(
|
|
162
|
-
` ${color.red("✖")} ${color.yellow(`[${f.ruleId}]`)}${provenanceSuffix}${validationBadge} ${color.dim(`line ${String(f.startLine)}:${String(f.startColumn)}`)}${alternates}`
|
|
163
|
-
);
|
|
164
|
-
if (sourceLines) {
|
|
165
|
-
const start = Math.max(0, f.startLine - 1 - CONTEXT_RADIUS);
|
|
166
|
-
const end = Math.min(sourceLines.length, f.startLine + CONTEXT_RADIUS);
|
|
167
|
-
for (let n = start; n < end; n += 1) {
|
|
168
|
-
const lineNumber = String(n + 1).padStart(4, " ");
|
|
169
|
-
const isMatchLine = n + 1 === f.startLine;
|
|
170
|
-
const marker = isMatchLine ? color.red("▶") : " ";
|
|
171
|
-
lines.push(` ${marker} ${color.dim(lineNumber)} │ ${sourceLines[n] ?? ""}`);
|
|
172
|
-
if (isMatchLine) {
|
|
173
|
-
const matchLen = Math.max(1, (f.endColumn ?? f.startColumn + 1) - f.startColumn);
|
|
174
|
-
const caret = caretFor(sourceLines[n] ?? "", f.startColumn, matchLen);
|
|
175
|
-
lines.push(` ${color.dim(" │ ")}${color.red(caret)}`);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
lines.push("");
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
return lines.join("\n").trimEnd();
|
|
183
|
-
};
|
|
184
|
-
const toSarifUri = (path, root) => {
|
|
185
|
-
if (!isAbsolute(path)) {
|
|
186
|
-
return path.replaceAll("\\", "/");
|
|
187
|
-
}
|
|
188
|
-
try {
|
|
189
|
-
return pathToFileURL(path).toString();
|
|
190
|
-
} catch {
|
|
191
|
-
return `file://${resolve(root, path).replaceAll("\\", "/")}`;
|
|
192
|
-
}
|
|
193
|
-
};
|
|
194
|
-
const shortText = (text, limit = 100) => {
|
|
195
|
-
if (text.length <= limit) {
|
|
196
|
-
return text;
|
|
197
|
-
}
|
|
198
|
-
return `${text.slice(0, limit - 1).trimEnd()}…`;
|
|
199
|
-
};
|
|
200
|
-
const formatSarif = (findings, toolVersion, root = process.cwd(), ruleMetadata = []) => {
|
|
201
|
-
const metaById = new Map(ruleMetadata.map((r) => [r.id, r]));
|
|
202
|
-
const seenIds = /* @__PURE__ */ new Set();
|
|
203
|
-
for (const f of findings) {
|
|
204
|
-
seenIds.add(f.ruleId);
|
|
205
|
-
}
|
|
206
|
-
const ruleIds = [.../* @__PURE__ */ new Set([...metaById.keys(), ...seenIds])].sort((a, b) => a.localeCompare(b));
|
|
207
|
-
const ruleIndex = new Map(ruleIds.map((id, i) => [id, i]));
|
|
208
|
-
return JSON.stringify(
|
|
209
|
-
{
|
|
210
|
-
$schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json",
|
|
211
|
-
runs: [
|
|
212
|
-
{
|
|
213
|
-
originalUriBaseIds: {
|
|
214
|
-
SRCROOT: { uri: pathToFileURL(root).toString() }
|
|
215
|
-
},
|
|
216
|
-
results: findings.map((f) => {
|
|
217
|
-
const properties = {};
|
|
218
|
-
if (f.source) {
|
|
219
|
-
properties["source"] = f.source;
|
|
220
|
-
}
|
|
221
|
-
if (f.confidence) {
|
|
222
|
-
properties["confidence"] = f.confidence;
|
|
223
|
-
}
|
|
224
|
-
if (f.alternateMatches && f.alternateMatches.length > 0) {
|
|
225
|
-
properties["alternateRules"] = f.alternateMatches;
|
|
226
|
-
}
|
|
227
|
-
if (f.validation) {
|
|
228
|
-
properties["validation"] = f.validation;
|
|
229
|
-
}
|
|
230
|
-
return {
|
|
231
|
-
level: "error",
|
|
232
|
-
locations: [
|
|
233
|
-
{
|
|
234
|
-
physicalLocation: {
|
|
235
|
-
artifactLocation: {
|
|
236
|
-
uri: toSarifUri(f.file, root),
|
|
237
|
-
uriBaseId: isAbsolute(f.file) ? void 0 : "SRCROOT"
|
|
238
|
-
},
|
|
239
|
-
region: {
|
|
240
|
-
endColumn: f.endColumn,
|
|
241
|
-
endLine: f.endLine,
|
|
242
|
-
snippet: { text: f.match },
|
|
243
|
-
startColumn: f.startColumn,
|
|
244
|
-
startLine: f.startLine
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
],
|
|
249
|
-
message: { text: f.description || f.ruleId },
|
|
250
|
-
properties: Object.keys(properties).length > 0 ? properties : void 0,
|
|
251
|
-
ruleId: f.ruleId,
|
|
252
|
-
ruleIndex: ruleIndex.get(f.ruleId) ?? -1
|
|
253
|
-
};
|
|
254
|
-
}),
|
|
255
|
-
tool: {
|
|
256
|
-
driver: {
|
|
257
|
-
informationUri: "https://visulima.com/packages/secret-scanner",
|
|
258
|
-
name: "visulima-secret-scanner",
|
|
259
|
-
rules: ruleIds.map((id) => {
|
|
260
|
-
const meta = metaById.get(id);
|
|
261
|
-
const description = meta?.description ?? `Detected by rule \`${id}\``;
|
|
262
|
-
const ruleProperties = {};
|
|
263
|
-
if (meta?.tags && meta.tags.length > 0) {
|
|
264
|
-
ruleProperties["tags"] = meta.tags;
|
|
265
|
-
}
|
|
266
|
-
if (meta?.source) {
|
|
267
|
-
ruleProperties["source"] = meta.source;
|
|
268
|
-
}
|
|
269
|
-
if (meta?.confidence) {
|
|
270
|
-
ruleProperties["confidence"] = meta.confidence;
|
|
271
|
-
}
|
|
272
|
-
return {
|
|
273
|
-
defaultConfiguration: { level: "error" },
|
|
274
|
-
fullDescription: { text: description },
|
|
275
|
-
helpUri: "https://visulima.com/packages/secret-scanner",
|
|
276
|
-
id,
|
|
277
|
-
name: id,
|
|
278
|
-
properties: Object.keys(ruleProperties).length > 0 ? ruleProperties : void 0,
|
|
279
|
-
shortDescription: { text: shortText(description) }
|
|
280
|
-
};
|
|
281
|
-
}),
|
|
282
|
-
version: toolVersion
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
],
|
|
287
|
-
version: "2.1.0"
|
|
288
|
-
},
|
|
289
|
-
void 0,
|
|
290
|
-
2
|
|
291
|
-
);
|
|
292
|
-
};
|
|
293
|
-
|
|
294
|
-
const runGit = (root, args) => {
|
|
295
|
-
try {
|
|
296
|
-
return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
297
|
-
} catch {
|
|
298
|
-
return "";
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
const splitFiles = (stdout) => stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
302
|
-
const stagedFiles = (root) => splitFiles(runGit(root, ["diff", "--cached", "--name-only", "--diff-filter=ACMR"])).map((p) => isAbsolute(p) ? p : join(root, p));
|
|
303
|
-
const filesSince = (root, ref) => {
|
|
304
|
-
const stdout = runGit(root, ["diff", "--name-only", "--diff-filter=ACMR", `${ref}...HEAD`]);
|
|
305
|
-
const list = splitFiles(stdout);
|
|
306
|
-
if (list.length === 0) {
|
|
307
|
-
const fallback = runGit(root, ["diff", "--name-only", "--diff-filter=ACMR", ref]);
|
|
308
|
-
return splitFiles(fallback).map((p) => isAbsolute(p) ? p : join(root, p));
|
|
309
|
-
}
|
|
310
|
-
return list.map((p) => isAbsolute(p) ? p : join(root, p));
|
|
311
|
-
};
|
|
312
|
-
const hasGit = (root) => runGit(root, ["rev-parse", "--show-toplevel"]).length > 0;
|
|
313
|
-
|
|
314
|
-
const DEFAULT_BASELINE = ".secrets-baseline.json";
|
|
315
|
-
const toArray = (value) => {
|
|
316
|
-
if (!value) {
|
|
317
|
-
return [];
|
|
318
|
-
}
|
|
319
|
-
return Array.isArray(value) ? value : [value];
|
|
320
|
-
};
|
|
321
|
-
const validateFormat = (raw) => {
|
|
322
|
-
const allowed = /* @__PURE__ */ new Set(["json", "sarif", "text"]);
|
|
323
|
-
if (raw && !allowed.has(raw)) {
|
|
324
|
-
pail.error(`--format must be one of: ${[...allowed].join(", ")} (got "${raw}")`);
|
|
325
|
-
process.exit(2);
|
|
326
|
-
}
|
|
327
|
-
return raw ?? "text";
|
|
328
|
-
};
|
|
329
|
-
const validateConfidence = (raw) => {
|
|
330
|
-
if (raw === void 0) {
|
|
331
|
-
return void 0;
|
|
332
|
-
}
|
|
333
|
-
const allowed = /* @__PURE__ */ new Set(["high", "low", "medium"]);
|
|
334
|
-
if (!allowed.has(raw)) {
|
|
335
|
-
pail.error(`--min-confidence must be one of: ${[...allowed].join(", ")} (got "${raw}")`);
|
|
336
|
-
process.exit(2);
|
|
337
|
-
}
|
|
338
|
-
return raw;
|
|
339
|
-
};
|
|
340
|
-
const printListRules = async (scanOptions, useColor) => {
|
|
341
|
-
const rules = await listRules(scanOptions);
|
|
342
|
-
process.stdout.write(`${String(rules.length)} rules loaded
|
|
343
|
-
|
|
344
|
-
`);
|
|
345
|
-
for (const rule of rules) {
|
|
346
|
-
const id = useColor ? yellow(rule.id) : rule.id;
|
|
347
|
-
const tags = rule.tags.length > 0 ? ` ${useColor ? dim(`[${rule.tags.join(", ")}]`) : `[${rule.tags.join(", ")}]`}` : "";
|
|
348
|
-
process.stdout.write(`${id}${tags}
|
|
349
|
-
${rule.description}
|
|
350
|
-
`);
|
|
351
|
-
if (rule.keywords.length > 0) {
|
|
352
|
-
const kw = `keywords: ${rule.keywords.slice(0, 6).join(", ")}${rule.keywords.length > 6 ? ", ..." : ""}`;
|
|
353
|
-
process.stdout.write(` ${useColor ? dim(kw) : kw}
|
|
354
|
-
`);
|
|
355
|
-
}
|
|
356
|
-
process.stdout.write("\n");
|
|
357
|
-
}
|
|
358
|
-
};
|
|
359
|
-
const printListValidators = async (scanOptions, useColor) => {
|
|
360
|
-
const report = await listRequiredValidators(scanOptions);
|
|
361
|
-
if (report.length === 0) {
|
|
362
|
-
process.stdout.write(
|
|
363
|
-
useColor ? `${dim("No non-HTTP validators required by the current ruleset.")}
|
|
364
|
-
` : "No non-HTTP validators required by the current ruleset.\n"
|
|
365
|
-
);
|
|
366
|
-
return;
|
|
367
|
-
}
|
|
368
|
-
process.stdout.write(`${String(report.length)} non-HTTP validator type(s) referenced by the current ruleset:
|
|
369
|
-
|
|
370
|
-
`);
|
|
371
|
-
for (const entry of report) {
|
|
372
|
-
const title = useColor ? yellow(entry.displayName) : entry.displayName;
|
|
373
|
-
const typeLabel = `(${entry.type}, ${String(entry.ruleCount)} rule${entry.ruleCount === 1 ? "" : "s"})`;
|
|
374
|
-
process.stdout.write(`${title} ${useColor ? dim(typeLabel) : typeLabel}
|
|
375
|
-
`);
|
|
376
|
-
process.stdout.write(` ${entry.summary}
|
|
377
|
-
`);
|
|
378
|
-
const hint = entry.packageName ? `install: npm add ${entry.packageName}` : "no driver — bespoke implementation required";
|
|
379
|
-
process.stdout.write(` ${useColor ? dim(hint) : hint}
|
|
380
|
-
|
|
381
|
-
`);
|
|
382
|
-
}
|
|
383
|
-
};
|
|
384
|
-
const runInit = async (root, scanOptions, dryRun) => {
|
|
385
|
-
const baselinePath = join(root, DEFAULT_BASELINE);
|
|
386
|
-
if (!dryRun && isAccessibleSync(baselinePath)) {
|
|
387
|
-
pail.warn(`Detected existing ${DEFAULT_BASELINE} — refusing to overwrite. Delete it first to re-init.`);
|
|
388
|
-
process.exit(1);
|
|
389
|
-
}
|
|
390
|
-
pail.info(dryRun ? "[dry-run] Previewing init — no files will be written." : "Scanning workspace to seed baseline…");
|
|
391
|
-
const spinner = createSpinner();
|
|
392
|
-
spinner.start("scanning");
|
|
393
|
-
let findings;
|
|
394
|
-
try {
|
|
395
|
-
findings = await scan([root], scanOptions);
|
|
396
|
-
spinner.succeed();
|
|
397
|
-
} catch (error) {
|
|
398
|
-
spinner.failed();
|
|
399
|
-
throw error;
|
|
400
|
-
}
|
|
401
|
-
if (dryRun) {
|
|
402
|
-
pail.info(`[dry-run] Would create ${DEFAULT_BASELINE} with ${String(findings.length)} finding(s).`);
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
|
-
const count = writeBaseline(findings, baselinePath, root, { replace: true });
|
|
406
|
-
pail.success(`Wrote ${DEFAULT_BASELINE} (${String(count)} findings).`);
|
|
407
|
-
pail.notice("Commit it. Use `vis secrets --baseline .secrets-baseline.json` in CI. Add path patterns to .gitignore to exclude directories from scanning.");
|
|
408
|
-
};
|
|
409
|
-
const resolveScanOptions = (flags, visSecrets, root) => {
|
|
410
|
-
const cfg = visSecrets ?? {};
|
|
411
|
-
const resolvePath = (p) => p ? resolve(root, p) : void 0;
|
|
412
|
-
const pickList = (flag, fallback) => {
|
|
413
|
-
const fromFlag = toArray(flag);
|
|
414
|
-
return fromFlag.length > 0 ? fromFlag : fallback;
|
|
415
|
-
};
|
|
416
|
-
const enableRules = pickList(flags.enableRule, cfg.rules?.enable);
|
|
417
|
-
const excludeRules = pickList(flags.excludeRule, cfg.rules?.exclude);
|
|
418
|
-
const includeRules = pickList(flags.includeRule, cfg.rules?.include);
|
|
419
|
-
const excludePatterns = pickList(flags.exclude, cfg.walk?.excludePatterns);
|
|
420
|
-
const excludeFromFlag = toArray(flags.excludeFrom).map((p) => resolve(root, p));
|
|
421
|
-
const excludeFromFiles = excludeFromFlag.length > 0 ? excludeFromFlag : cfg.walk?.excludeFromFiles?.map((p) => resolve(root, p));
|
|
422
|
-
const baselinePath = resolvePath(flags.baseline) ?? resolvePath(cfg.baseline);
|
|
423
|
-
const configPath = resolvePath(flags.config) ?? resolvePath(cfg.config?.path);
|
|
424
|
-
const minConfidence = validateConfidence(flags.minConfidence ?? cfg.config?.minConfidence);
|
|
425
|
-
return {
|
|
426
|
-
baseline: baselinePath,
|
|
427
|
-
concurrency: flags.concurrency,
|
|
428
|
-
config: {
|
|
429
|
-
extendBundled: flags.noExtendBundled ? false : cfg.config?.extendBundled,
|
|
430
|
-
inline: cfg.config?.inline,
|
|
431
|
-
minConfidence,
|
|
432
|
-
onlyVerified: flags.onlyVerified ?? cfg.config?.onlyVerified ?? false,
|
|
433
|
-
path: configPath,
|
|
434
|
-
validate: flags.validate ?? cfg.config?.validate ?? false
|
|
435
|
-
},
|
|
436
|
-
redact: flags.redact ?? cfg.redact,
|
|
437
|
-
rules: { enable: enableRules, exclude: excludeRules, include: includeRules },
|
|
438
|
-
verbose: flags.verbose ?? false,
|
|
439
|
-
walk: {
|
|
440
|
-
excludeFromFiles,
|
|
441
|
-
excludePatterns,
|
|
442
|
-
gitignore: flags.noGitignore ? false : cfg.walk?.gitignore ?? true,
|
|
443
|
-
includeHidden: flags.includeHidden ?? cfg.walk?.includeHidden,
|
|
444
|
-
maxFileSize: flags.maxSize ?? cfg.walk?.maxFileSize
|
|
445
|
-
}
|
|
446
|
-
};
|
|
447
|
-
};
|
|
448
|
-
const printDiff = (diff) => {
|
|
449
|
-
process.stderr.write(
|
|
450
|
-
`${dim("baseline diff: ")}${green(`+${String(diff.fresh.length)} new`)} · ${yellow(`${String(diff.surviving.length)} unchanged`)} · ${dim(`-${String(diff.resolved.length)} resolved`)}
|
|
451
|
-
`
|
|
452
|
-
);
|
|
453
|
-
};
|
|
454
|
-
const chooseScanPaths = async (flags, args, root) => {
|
|
455
|
-
if (flags.staged) {
|
|
456
|
-
if (!hasGit(root)) {
|
|
457
|
-
pail.error("--staged requires a git working tree, and none was detected.");
|
|
458
|
-
process.exit(2);
|
|
459
|
-
}
|
|
460
|
-
return { files: stagedFiles(root) };
|
|
461
|
-
}
|
|
462
|
-
if (flags.since) {
|
|
463
|
-
if (!hasGit(root)) {
|
|
464
|
-
pail.error("--since requires a git working tree, and none was detected.");
|
|
465
|
-
process.exit(2);
|
|
466
|
-
}
|
|
467
|
-
return { files: filesSince(root, flags.since) };
|
|
468
|
-
}
|
|
469
|
-
if (flags.affected) {
|
|
470
|
-
if (!hasGit(root)) {
|
|
471
|
-
pail.warn("--affected requires git; falling back to full scan");
|
|
472
|
-
return { paths: args && args.length > 0 ? args.map((p) => resolve(root, p)) : [root] };
|
|
473
|
-
}
|
|
474
|
-
const baseRef = process.env["VIS_BASE"] ?? "HEAD~1";
|
|
475
|
-
return { files: filesSince(root, baseRef) };
|
|
476
|
-
}
|
|
477
|
-
return { paths: args && args.length > 0 ? args.map((p) => resolve(root, p)) : [root] };
|
|
478
|
-
};
|
|
479
|
-
const emitFindings = (findings, format, root, useColor, toolVersion, ruleMetadata, redactFindings) => {
|
|
480
|
-
switch (format) {
|
|
481
|
-
case "json": {
|
|
482
|
-
const view = findings.map((f) => toRelativeFinding(f, root));
|
|
483
|
-
process.stdout.write(`${JSON.stringify(view, null, 2)}
|
|
484
|
-
`);
|
|
485
|
-
break;
|
|
486
|
-
}
|
|
487
|
-
case "sarif": {
|
|
488
|
-
process.stdout.write(`${formatSarif(findings, toolVersion, root, ruleMetadata)}
|
|
489
|
-
`);
|
|
490
|
-
break;
|
|
491
|
-
}
|
|
492
|
-
default: {
|
|
493
|
-
process.stdout.write(`${formatText(findings, root, useColor, { redact: redactFindings })}
|
|
494
|
-
`);
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
};
|
|
498
|
-
const execute = async ({ argument, options, visConfig, workspaceRoot }) => {
|
|
499
|
-
const flags = options;
|
|
500
|
-
const args = argument;
|
|
501
|
-
const root = workspaceRoot ?? process.cwd();
|
|
502
|
-
const useColor = !flags.quiet && process.stdout.isTTY;
|
|
503
|
-
const visSecrets = visConfig?.secrets;
|
|
504
|
-
const scanOptions = resolveScanOptions(flags, visSecrets, root);
|
|
505
|
-
const toolVersion = "0.0.0-alpha";
|
|
506
|
-
if (flags.listRules) {
|
|
507
|
-
await printListRules(scanOptions, useColor);
|
|
508
|
-
return;
|
|
509
|
-
}
|
|
510
|
-
if (flags.listValidators) {
|
|
511
|
-
await printListValidators(scanOptions, useColor);
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
if (flags.init) {
|
|
515
|
-
await runInit(root, scanOptions, flags.dryRun ?? false);
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
const target = await chooseScanPaths(flags, args ?? [], root);
|
|
519
|
-
if (target.files?.length === 0) {
|
|
520
|
-
if (!flags.quiet) {
|
|
521
|
-
pail.success("No files to scan.");
|
|
522
|
-
}
|
|
523
|
-
return;
|
|
524
|
-
}
|
|
525
|
-
const isInteractive = !flags.quiet && !["json", "sarif"].includes(flags.format ?? "text");
|
|
526
|
-
const spinner = createSpinner({ verbose: isInteractive });
|
|
527
|
-
spinner.start("scanning for secrets");
|
|
528
|
-
let findings;
|
|
529
|
-
try {
|
|
530
|
-
findings = target.files === void 0 ? await scan(target.paths ?? [root], scanOptions) : await scanFiles(target.files, scanOptions);
|
|
531
|
-
spinner.succeed();
|
|
532
|
-
} catch (error) {
|
|
533
|
-
spinner.failed();
|
|
534
|
-
pail.error(`secret scan failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
535
|
-
process.exit(2);
|
|
536
|
-
}
|
|
537
|
-
if (flags.verbose) {
|
|
538
|
-
const skipped = await inspectRuleset(scanOptions);
|
|
539
|
-
if (skipped.length > 0) {
|
|
540
|
-
pail.warn(`${String(skipped.length)} rule(s) skipped due to invalid regex. First few:`);
|
|
541
|
-
for (const s of skipped.slice(0, 5)) {
|
|
542
|
-
process.stderr.write(` - ${s.ruleId}: ${s.reason}
|
|
543
|
-
`);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
const baselineFullPath = scanOptions.baseline ?? join(root, DEFAULT_BASELINE);
|
|
548
|
-
const showDiff = !flags.quiet && isAccessibleSync(baselineFullPath);
|
|
549
|
-
if (flags.updateBaseline) {
|
|
550
|
-
const count = writeBaseline(findings, baselineFullPath, root, { replace: flags.replaceBaseline });
|
|
551
|
-
pail.success(`Baseline updated: ${relative(root, baselineFullPath) || baselineFullPath} now contains ${String(count)} entries.`);
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
const format = validateFormat(flags.format);
|
|
555
|
-
const ruleMetadata = format === "sarif" ? await listRules(scanOptions).catch(() => []) : [];
|
|
556
|
-
const shouldRedact = scanOptions.redact === true;
|
|
557
|
-
const reportFindings = shouldRedact ? redact(findings, ["match", "secret"]) : findings;
|
|
558
|
-
emitFindings(reportFindings, format, root, useColor, toolVersion, ruleMetadata, shouldRedact);
|
|
559
|
-
if (format === "text" && showDiff) {
|
|
560
|
-
printDiff(diffBaseline(findings, baselineFullPath, root));
|
|
561
|
-
}
|
|
562
|
-
if (findings.length > 0) {
|
|
563
|
-
if (!flags.quiet) {
|
|
564
|
-
pail.warn(`${String(findings.length)} potential secret(s) found`);
|
|
565
|
-
pail.notice("Suppress individual lines with `gitleaks:allow` / `secret-scanner:allow`, or run `vis secrets --update-baseline`.");
|
|
566
|
-
}
|
|
567
|
-
process.exit(1);
|
|
568
|
-
}
|
|
569
|
-
if (!flags.quiet) {
|
|
570
|
-
pail.success("No secrets detected.");
|
|
571
|
-
}
|
|
572
|
-
};
|
|
573
|
-
|
|
574
|
-
export { execute as default };
|
|
1
|
+
var ee=Object.defineProperty;var $=(e,t)=>ee(e,"name",{value:t,configurable:!0});import{createRequire as te}from"node:module";import{isAccessibleSync as y,readFileSync as A,ensureDirSync as z}from"@visulima/fs";import{join as l}from"@visulima/path";import{ap as G,aq as ae,ar as le,as as ce,at as fe,au as ue,ao as de,av as pe,aw as K,ax as J,ay as U,az as Y}from"./bin.js";import{readTomlSync as ge}from"@visulima/fs/toml";const se=te(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,B=$(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,s]=F.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return F.getBuiltinModule(e)}return se(e)},"__cjs_getBuiltinModule"),{readdirSync:V,statSync:C,writeFileSync:S,unlinkSync:ne,rmSync:re,chmodSync:ie}=B("node:fs"),{cwd:j}=F,{createInterface:oe}=B("node:readline"),{spawnSync:w}=B("node:child_process");var he=Object.defineProperty,N=$((e,t)=>he(e,"name",{value:t,configurable:!0}),"c$2");const me=/^# ([^:\s]\S*)(?::\s+(.+))?$/,ke=N(e=>{const t=[],s=e.split(`
|
|
2
|
+
`);let n;for(const r of s){if(r.startsWith("#!")||r.startsWith("# Generated by")||r.startsWith("# NOTE:")||r==="set -e"||r==="")continue;const i=me.exec(r);if(i){n&&t.push(n),n={command:"",id:i[1]??"",...i[2]?{name:i[2]}:{}};continue}n?n.command=n.command.length>0?`${n.command}
|
|
3
|
+
${r}`:r:n={command:r,id:"(custom)"}}return n&&t.push(n),t},"parseStageScript"),ye=N((e,t)=>{const s=l(e,t),n=[],r=new Set(G);if(y(s))for(const i of V(s)){if(i.startsWith(".")||i==="_"||!r.has(i))continue;const o=l(s,i);if(!C(o).isFile())continue;const a=A(o),c=ke(a);n.push({blocks:c,rawLineCount:a.split(`
|
|
4
|
+
`).length,stage:i})}return n.sort((i,o)=>i.stage.localeCompare(o.stage)),{hooksDirectory:t,stages:n}},"listHooks"),be=N(e=>{const t=[];if(e.stages.length===0)return t.push(`No hooks installed in ${e.hooksDirectory}/.`),t;t.push(`Hooks in ${e.hooksDirectory}/:`);for(const s of e.stages)if(t.push("",`${s.stage} (${s.rawLineCount} lines)`),s.blocks.length===0)t.push(" (empty)");else for(const n of s.blocks){const r=n.name?`${n.id} — ${n.name}`:n.id;t.push(` - ${r}`);const i=n.command.split(`
|
|
5
|
+
`).find(o=>o.trim()!=="");if(i){const o=i.length>120?`${i.slice(0,117)}...`:i;t.push(` ${o}`)}}return t},"formatListResult"),we=N((e,t)=>{const s=ye(j(),e);for(const n of be(s))t.info(n)},"runList"),E="prek-runner.mjs",xe={css:["css","scss","sass","less"],dockerfile:["dockerfile"],html:["htm","html"],javascript:["cjs","js","jsx","mjs"],json:["json"],jsx:["jsx","tsx"],makefile:["mk","makefile"],markdown:["markdown","md","mdown","mdx"],python:["py","pyi","pyw"],python3:["py","pyi","pyw"],ruby:["rb"],rust:["rs"],shell:["bash","sh","zsh"],sql:["sql"],svg:["svg"],systemd:["service","socket","timer"],toml:["toml"],tsx:["tsx"],typescript:["cts","mts","ts","tsx"],xml:["xml"],yaml:["yaml","yml"]},ve=["binary","directory","executable","non-executable","symlink","text"],$e={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},Ee=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],Se=[...Object.keys(xe),...Object.values($e).flat(),...ve],Re=["#!/usr/bin/env node","// Auto-generated by `vis hook migrate`. Do not edit by hand.","// Replicates the subset of prek / pre-commit framework semantics that a vis","// hook script needs: staged-file discovery, regex + type filters, chunked","// argv dispatch, and a handful of built-in hook implementations.","","import { spawnSync } from 'node:child_process';","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';","import { basename, extname, join } from 'node:path';","import process from 'node:process';","","const TYPES_EXTENSION_MAP = {"," css: ['css', 'scss', 'sass', 'less'],"," dockerfile: ['dockerfile'],"," html: ['htm', 'html'],"," javascript: ['cjs', 'js', 'jsx', 'mjs'],"," json: ['json'],"," jsx: ['jsx', 'tsx'],"," makefile: ['mk', 'makefile'],"," markdown: ['markdown', 'md', 'mdown', 'mdx'],"," python: ['py', 'pyi', 'pyw'],"," python3: ['py', 'pyi', 'pyw'],"," ruby: ['rb'],"," rust: ['rs'],"," shell: ['bash', 'sh', 'zsh'],"," sql: ['sql'],"," svg: ['svg'],"," systemd: ['service', 'socket', 'timer'],"," toml: ['toml'],"," tsx: ['tsx'],"," typescript: ['cts', 'mts', 'ts', 'tsx'],"," xml: ['xml'],"," yaml: ['yaml', 'yml'],","};","","const FILENAME_TYPE_MAP = {"," dockerfile: 'dockerfile',"," makefile: 'makefile',"," 'gnumakefile': 'makefile',","};","","const SHEBANG_INTERPRETER_MAP = {"," bash: ['bash', 'shell'],"," node: ['javascript'],"," nodejs: ['javascript'],"," perl: ['perl'],"," python: ['python'],"," python3: ['python', 'python3'],"," ruby: ['ruby'],"," sh: ['shell'],"," zsh: ['shell', 'zsh'],","};","","const BUILTINS = {"," 'check-json': runCheckJson,"," 'check-merge-conflict': runCheckMergeConflict,"," 'end-of-file-fixer': runEndOfFileFixer,"," 'mixed-line-ending': runMixedLineEnding,"," 'trailing-whitespace': runTrailingWhitespace,","};","","const parseArgs = (argv) => {"," const flags = {"," allFiles: process.env.VIS_HOOK_ALL_FILES === '1',"," alwaysRun: false,"," builtin: null,"," exclude: null,"," excludeTypes: [],"," files: null,"," fromRef: process.env.VIS_HOOK_FROM_REF || null,"," passFilenames: true,"," toRef: process.env.VIS_HOOK_TO_REF || null,"," types: [],"," typesOr: [],"," };"," const rest = [];"," let seenDoubleDash = false;",""," for (let i = 0; i < argv.length; i += 1) {"," const arg = argv[i];",""," if (seenDoubleDash) {"," rest.push(arg);"," continue;"," }",""," switch (arg) {"," case '--':"," seenDoubleDash = true;"," break;"," case '--all-files':"," flags.allFiles = true;"," break;"," case '--always-run':"," flags.alwaysRun = true;"," break;"," case '--builtin':"," i += 1;"," flags.builtin = argv[i];"," break;"," case '--exclude':"," i += 1;"," flags.exclude = argv[i];"," break;"," case '--from-ref':"," i += 1;"," flags.fromRef = argv[i];"," break;"," case '--to-ref':"," i += 1;"," flags.toRef = argv[i];"," break;"," case '--exclude-types':"," i += 1;"," flags.excludeTypes = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--files':"," i += 1;"," flags.files = argv[i];"," break;"," case '--no-pass-filenames':"," flags.passFilenames = false;"," break;"," case '--types':"," i += 1;"," flags.types = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--types-or':"," i += 1;"," flags.typesOr = (argv[i] || '').split(',').filter(Boolean);"," break;"," default:"," process.stderr.write('prek-runner: unknown flag ' + arg + '\\n');"," process.exit(2);"," }"," }",""," return { flags, rest };","};","","const gitListFiles = (args, errorHint) => {"," const result = spawnSync('git', args, { encoding: 'buffer' });"," if (result.status !== 0) {"," process.stderr.write('prek-runner: git ' + errorHint + ' failed\\n');"," process.stderr.write(result.stderr ? result.stderr.toString() : '');"," process.exit(result.status === null ? 1 : result.status);"," }"," const raw = result.stdout.toString('utf8');"," if (raw.length === 0) { return []; }"," return raw.split('\\0').filter(function (f) { return f.length > 0; });","};","","const discoverFiles = (flags) => {"," if (flags.allFiles) {"," return gitListFiles(['ls-files', '-z'], 'ls-files');"," }"," if (flags.fromRef && flags.toRef) {"," return gitListFiles("," ['diff', '--name-only', '--diff-filter=ACM', '-z', flags.fromRef, flags.toRef],"," 'diff --from-ref/--to-ref'"," );"," }"," return gitListFiles(['diff', '--cached', '--name-only', '--diff-filter=ACM', '-z'], 'diff --cached');","};","","const buildRegex = (pattern) => {"," try {"," return new RegExp(pattern);"," } catch (error) {"," process.stderr.write('prek-runner: invalid regex ' + JSON.stringify(pattern) + ': ' + error.message + '\\n');"," process.exit(2);"," }","};","","const readShebang = (file) => {"," try {"," const fd = readFileSync(file, { encoding: null });"," if (fd.length < 2 || fd[0] !== 0x23 || fd[1] !== 0x21) { return null; }"," const nl = fd.indexOf(0x0a);"," const end = nl === -1 ? Math.min(fd.length, 256) : Math.min(nl, 256);"," return fd.slice(2, end).toString('utf8').trim();"," } catch (error) {"," return null;"," }","};","","const interpreterFromShebang = (shebang) => {"," if (!shebang) { return null; }"," const parts = shebang.split(/\\s+/).filter(Boolean);"," if (parts.length === 0) { return null; }"," const first = parts[0];"," let candidate = basename(first);"," if (candidate === 'env' && parts.length > 1) {"," candidate = basename(parts[1].split('=')[0] || parts[1]);"," }"," return candidate.toLowerCase();","};","","const fileMetadataTags = (file) => {"," const tags = new Set();"," let info;"," try { info = statSync(file, { throwIfNoEntry: false }); } catch (error) { info = null; }"," if (!info) { return tags; }"," if (info.isSymbolicLink()) { tags.add('symlink'); }"," if (info.isDirectory()) { tags.add('directory'); }"," if (info.isFile()) {"," if ((info.mode & 0o111) !== 0) { tags.add('executable'); } else { tags.add('non-executable'); }"," }"," return tags;","};","","const isBinaryFile = (file) => {"," try {"," const buf = readFileSync(file);"," const slice = buf.subarray(0, Math.min(buf.length, 8192));"," for (let i = 0; i < slice.length; i += 1) {"," if (slice[i] === 0) { return true; }"," }"," return false;"," } catch (error) {"," return false;"," }","};","","const typesForFile = (file) => {"," const tags = new Set();"," const baseName = basename(file).toLowerCase();"," const ext = extname(file).slice(1).toLowerCase();",""," if (baseName in FILENAME_TYPE_MAP) {"," tags.add(FILENAME_TYPE_MAP[baseName]);"," }",""," for (const [type, extensions] of Object.entries(TYPES_EXTENSION_MAP)) {"," if (extensions.includes(ext) || extensions.includes(baseName)) {"," tags.add(type);"," }"," }",""," const metaTags = fileMetadataTags(file);"," for (const tag of metaTags) { tags.add(tag); }",""," if (tags.size === 0 || tags.has('executable') || tags.has('shell')) {"," const interpreter = interpreterFromShebang(readShebang(file));"," if (interpreter) {"," const interpreterTags = SHEBANG_INTERPRETER_MAP[interpreter];"," if (interpreterTags) {"," for (const tag of interpreterTags) { tags.add(tag); }"," }"," }"," }",""," if (!tags.has('symlink') && !tags.has('directory')) {"," tags.add(isBinaryFile(file) ? 'binary' : 'text');"," }",""," return tags;","};","","const applyFilters = (files, flags) => {"," let filtered = files;",""," if (flags.files) {"," const rx = buildRegex(flags.files);"," filtered = filtered.filter(function (f) { return rx.test(f); });"," }",""," if (flags.exclude) {"," const rx = buildRegex(flags.exclude);"," filtered = filtered.filter(function (f) { return !rx.test(f); });"," }",""," if (flags.types.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.types.every(function (t) { return tags.has(t); });"," });"," }",""," if (flags.typesOr.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.typesOr.some(function (t) { return tags.has(t); });"," });"," }",""," if (flags.excludeTypes.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return !flags.excludeTypes.some(function (t) { return tags.has(t); });"," });"," }",""," return filtered;","};","","// Conservative per-call argv budget. POSIX guarantees 4 KiB, Linux gives ~2 MiB","// in practice. 32 KiB keeps us well clear of Windows' 32767-char limit too.","const ARG_BUDGET = 32 * 1024;","","const chunkFiles = (files) => {"," const chunks = [];"," let current = [];"," let size = 0;",""," for (const file of files) {"," const cost = Buffer.byteLength(file, 'utf8') + 8;",""," if (size + cost > ARG_BUDGET && current.length > 0) {"," chunks.push(current);"," current = [];"," size = 0;"," }",""," current.push(file);"," size += cost;"," }",""," if (current.length > 0) {"," chunks.push(current);"," }",""," return chunks;","};","","const runCommand = (cmd, files, passFilenames) => {"," if (!cmd || cmd.length === 0) {"," process.stderr.write('prek-runner: no command specified after --\\n');"," return 2;"," }",""," const bin = cmd[0];"," const baseArgs = cmd.slice(1);",""," if (!passFilenames) {"," const result = spawnSync(bin, baseArgs, { stdio: 'inherit' });"," return result.status === null ? 1 : result.status;"," }",""," let rc = 0;"," const chunks = files.length === 0 ? [[]] : chunkFiles(files);",""," for (const chunk of chunks) {"," const result = spawnSync(bin, baseArgs.concat(chunk), { stdio: 'inherit' });"," rc = rc | (result.status === null ? 1 : result.status);"," }",""," return rc;","};","","// ─── Built-in hook implementations ──────────────────────────────────","// Each receives the already-filtered file list and returns an exit code.","","function runTrailingWhitespace(files) {"," // Mirrors pre-commit/pre-commit-hooks/trailing_whitespace_fixer.py:"," // strip trailing whitespace from each line, preserve original endings,"," // preserve markdown hard-break trailing two-spaces on non-blank lines."," const WS = new Set([0x20, 0x09, 0x0b, 0x0c, 0x0d]); // SP, TAB, VT, FF, CR"," const MD_RE = /\\.(md|markdown|mdown|mdx)$/i;"," let rc = 0;",""," for (const file of files) {"," const isMarkdown = MD_RE.test(file);"," const buf = readFileSync(file);"," const out = [];"," let i = 0;",""," while (i <= buf.length) {"," let end = i;",""," while (end < buf.length && buf[end] !== 0x0a) {"," end += 1;"," }",""," const hadLf = end < buf.length && buf[end] === 0x0a;"," let contentEnd = end;"," let hadCr = false;",""," if (hadLf && end > i && buf[end - 1] === 0x0d) {"," hadCr = true;"," contentEnd = end - 1;"," }",""," const content = buf.subarray(i, contentEnd);"," let stripEnd = content.length;",""," while (stripEnd > 0 && WS.has(content[stripEnd - 1])) {"," stripEnd -= 1;"," }",""," const nonWhitespace = content.some(function (b) { return !WS.has(b); });",""," if (isMarkdown && content.length >= 2 && content[content.length - 1] === 0x20 && content[content.length - 2] === 0x20 && nonWhitespace) {"," stripEnd = Math.min(stripEnd + 2, content.length);"," }",""," out.push(content.subarray(0, stripEnd));",""," if (hadCr) {"," out.push(Buffer.from([0x0d]));"," }",""," if (hadLf) {"," out.push(Buffer.from([0x0a]));"," }",""," if (!hadLf) {"," break;"," }",""," i = end + 1;"," }",""," const next = Buffer.concat(out);",""," if (!next.equals(buf)) {"," writeFileSync(file, next);"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function runEndOfFileFixer(files) {"," // Mirrors pre-commit/pre-commit-hooks/end_of_file_fixer.py: collapse"," // trailing \\n / \\r\\n / \\r runs to a single newline; add a newline if"," // missing; leave empty files alone."," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);",""," if (buf.length === 0) {"," continue;"," }",""," let end = buf.length;"," const last = buf[end - 1];",""," if (last !== 0x0a && last !== 0x0d) {"," writeFileSync(file, Buffer.concat([buf, Buffer.from([0x0a])]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," while (end > 0 && (buf[end - 1] === 0x0a || buf[end - 1] === 0x0d)) {"," end -= 1;"," }",""," if (end === 0) {"," writeFileSync(file, Buffer.alloc(0));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," const trailing = buf.subarray(end);"," let keep;",""," if (trailing[0] === 0x0d && trailing[1] === 0x0a) {"," keep = Buffer.from([0x0d, 0x0a]);"," } else if (trailing[0] === 0x0d) {"," keep = Buffer.from([0x0d]);"," } else {"," keep = Buffer.from([0x0a]);"," }",""," if (trailing.equals(keep)) {"," continue;"," }",""," writeFileSync(file, Buffer.concat([buf.subarray(0, end), keep]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }",""," return rc;","}","","function isInMerge() {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py:is_in_merge."," const gitDirResult = spawnSync('git', ['rev-parse', '--git-dir'], { encoding: 'utf8' });"," if (gitDirResult.status !== 0) { return false; }"," const gitDir = gitDirResult.stdout.trim();"," if (!existsSync(join(gitDir, 'MERGE_MSG'))) { return false; }"," return existsSync(join(gitDir, 'MERGE_HEAD'))"," || existsSync(join(gitDir, 'rebase-apply'))"," || existsSync(join(gitDir, 'rebase-merge'));","}","","function runCheckMergeConflict(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py: only"," // scans for conflict markers when git is mid-merge/rebase, unless the"," // caller passes --assume-in-merge. Skipping the guard means every"," // legit `<<<<<<<` in docs would fail the hook."," const assumeInMerge = Array.isArray(args) && args.includes('--assume-in-merge');"," if (!assumeInMerge && !isInMerge()) { return 0; }",""," const PATTERNS = ['<<<<<<< ', '======= ', '=======\\r\\n', '=======\\n', '>>>>>>> '];"," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');"," const lines = content.split('\\n');",""," for (let i = 0; i < lines.length; i += 1) {"," const line = lines[i] + (i < lines.length - 1 ? '\\n' : '');",""," for (const pattern of PATTERNS) {"," if (line.startsWith(pattern)) {"," process.stdout.write(file + ':' + (i + 1) + ': Merge conflict string ' + JSON.stringify(pattern.trim()) + ' found\\n');"," rc = 1;"," }"," }"," }"," }",""," return rc;","}","","function runCheckJson(files) {"," // Mirrors pre-commit/pre-commit-hooks/check_json.py: parse each file"," // and additionally reject duplicate keys."," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');",""," try {"," JSON.parse(content);"," detectDuplicateJsonKeys(content, file);"," } catch (error) {"," process.stdout.write(file + ': Failed to json decode (' + error.message + ')\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function detectDuplicateJsonKeys(source, file) {"," // Minimal tokeniser that walks the already-valid JSON source and throws"," // with a message compatible with the Python hook when a duplicate key"," // appears at any object level."," let i = 0;"," const length = source.length;",""," const skipWs = function () {"," while (i < length && /\\s/.test(source[i])) {"," i += 1;"," }"," };",""," const parseString = function () {",` if (source[i] !== '"') {`," throw new Error('expected string at ' + i);"," }"," i += 1;"," let start = i;",` while (i < length && source[i] !== '"') {`," if (source[i] === '\\\\') {"," i += 2;"," } else {"," i += 1;"," }"," }"," const raw = source.slice(start, i);"," i += 1;",` return JSON.parse('"' + raw + '"');`," };",""," const parseValue = function () {"," skipWs();"," const ch = source[i];"," if (ch === '{') { parseObject(); }"," else if (ch === '[') { parseArray(); }",` else if (ch === '"') { parseString(); }`," else {"," while (i < length && ',}]'.indexOf(source[i]) === -1 && !/\\s/.test(source[i])) {"," i += 1;"," }"," }"," };",""," const parseArray = function () {"," i += 1;"," skipWs();"," if (source[i] === ']') { i += 1; return; }"," while (i < length) {"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === ']') { i += 1; return; }"," }"," };",""," const parseObject = function () {"," i += 1;"," skipWs();"," const seen = new Set();"," if (source[i] === '}') { i += 1; return; }"," while (i < length) {"," skipWs();"," const key = parseString();"," if (seen.has(key)) {"," throw new Error('Duplicate key: ' + key);"," }"," seen.add(key);"," skipWs();"," if (source[i] !== ':') {"," throw new Error('expected colon at ' + i);"," }"," i += 1;"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === '}') { i += 1; return; }"," }"," };",""," skipWs();"," parseValue();","}","","function runMixedLineEnding(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/mixed_line_ending.py."," const ENDING = { cr: Buffer.from([0x0d]), crlf: Buffer.from([0x0d, 0x0a]), lf: Buffer.from([0x0a]) };"," let fixArg = 'auto';",""," for (let idx = 0; idx < args.length; idx += 1) {"," const a = args[idx];"," if (a === '-f' || a === '--fix') {"," idx += 1;"," fixArg = args[idx];"," } else if (a.indexOf('--fix=') === 0) {"," fixArg = a.slice('--fix='.length);"," }"," }",""," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);"," const counts = { cr: 0, crlf: 0, lf: 0 };"," const lines = [];"," let start = 0;",""," for (let i = 0; i < buf.length; i += 1) {"," const b = buf[i];",""," if (b === 0x0d && buf[i + 1] === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'crlf' });"," counts.crlf += 1;"," i += 1;"," start = i + 1;"," } else if (b === 0x0d) {"," lines.push({ content: buf.subarray(start, i), ending: 'cr' });"," counts.cr += 1;"," start = i + 1;"," } else if (b === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'lf' });"," counts.lf += 1;"," start = i + 1;"," }"," }",""," if (start < buf.length) {"," lines.push({ content: buf.subarray(start), ending: null });"," }",""," const distinct = Object.values(counts).filter(function (c) { return c > 0; }).length;"," const mixed = distinct > 1;",""," if (fixArg === 'no') {"," if (mixed) {"," process.stdout.write(file + ': mixed line endings\\n');"," rc = 1;"," }"," continue;"," }",""," let target;",""," if (fixArg === 'auto') {"," if (!mixed) { continue; }"," let max = -1;"," for (const key of ['cr', 'crlf', 'lf']) {"," if (counts[key] >= max) {"," max = counts[key];"," target = key;"," }"," }"," } else if (!(fixArg in ENDING)) {"," process.stderr.write('prek-runner: invalid --fix value ' + fixArg + '\\n');"," return 2;"," } else {"," target = fixArg;"," const other = Object.entries(counts).some(function (entry) { return entry[0] !== target && entry[1] > 0; });"," if (!other) { continue; }"," }",""," const ending = ENDING[target];"," const chunks = [];",""," for (const line of lines) {"," chunks.push(line.content);"," if (line.ending !== null) {"," chunks.push(ending);"," }"," }",""," writeFileSync(file, Buffer.concat(chunks));"," process.stdout.write(file + ': fixed mixed line endings\\n');"," rc = 1;"," }",""," return rc;","}","","// ─── Entry point ────────────────────────────────────────────────────","","const parsed = parseArgs(process.argv.slice(2));","const candidateFiles = discoverFiles(parsed.flags);","const filtered = applyFilters(candidateFiles, parsed.flags);","","if (filtered.length === 0 && !parsed.flags.alwaysRun) {"," process.exit(0);","}","","let code;","","if (parsed.flags.builtin) {"," const impl = BUILTINS[parsed.flags.builtin];"," if (!impl) {"," process.stderr.write('prek-runner: unknown builtin ' + parsed.flags.builtin + '\\n');"," process.exit(2);"," }"," code = impl(filtered, parsed.rest);","} else {"," code = runCommand(parsed.rest, filtered, parsed.flags.passFilenames);","}","","process.exit(code);",""],_e=Re.join(`
|
|
6
|
+
`);var Fe=Object.defineProperty,d=$((e,t)=>Fe(e,"name",{value:t,configurable:!0}),"a$1");const je=new Map([["pre-commit/pre-commit-hooks#check-json","check-json"],["pre-commit/pre-commit-hooks#check-merge-conflict","check-merge-conflict"],["pre-commit/pre-commit-hooks#end-of-file-fixer","end-of-file-fixer"],["pre-commit/pre-commit-hooks#mixed-line-ending","mixed-line-ending"],["pre-commit/pre-commit-hooks#trailing-whitespace","trailing-whitespace"]]),Ae=/[<>=!~]=/,Me=/github\.com[/:]([^/\s]+\/[^/\s.]+)/i,X=`node "$(dirname "$0")/.builtins/${E}"`,Oe="# Generated by `vis hook migrate` from prek",v=d(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"shellQuote"),L=d(e=>{for(const t of ae)if(y(l(e,t)))return t},"detectPrekConfig"),Ie=d(e=>le[e]??e,"mapPrekStage"),De=d(e=>Me.exec(e)?.[1]??e,"normalizeRepoKey"),Pe=d(e=>{if(Ae.test(e))return;if(e.startsWith("@")){const n=e.indexOf("@",1);if(n===-1)return{name:e,version:"latest"};const r=e.slice(n+1).trim();return{name:e.slice(0,n),version:r||"latest"}}const t=e.indexOf("@");if(t===-1)return{name:e,version:"latest"};const s=e.slice(t+1).trim();return{name:e.slice(0,t),version:s||"latest"}},"parseAdditionalDep"),Ne=new Set(Se),Te=d(e=>{const t=[];for(const s of[e.types,e.types_or,e.exclude_types])for(const n of s??[])Ne.has(n)||t.push(n);return t},"unknownTypes"),Ce=d((e,t)=>(e.stages&&e.stages.length>0?e.stages:t??["pre-commit"]).map(s=>Ie(s)),"resolveStages"),We=d(e=>{const t=[];return e.files&&t.push("--files",v(e.files)),e.exclude&&t.push("--exclude",v(e.exclude)),e.types&&e.types.length>0&&t.push("--types",v(e.types.join(","))),e.types_or&&e.types_or.length>0&&t.push("--types-or",v(e.types_or.join(","))),e.exclude_types&&e.exclude_types.length>0&&t.push("--exclude-types",v(e.exclude_types.join(","))),e.always_run&&t.push("--always-run"),e.pass_filenames===!1&&t.push("--no-pass-filenames"),t},"buildRunnerFilterFlags"),H=d((e,t)=>{const s=[X,...We(e)];if(t)return s.push("--builtin",t),Array.isArray(e.args)&&e.args.length>0&&s.push("--",...e.args.map(n=>v(n))),s.join(" ");if(s.push("--",e.entry??""),Array.isArray(e.args))for(const n of e.args)s.push(v(n));return s.join(" ")},"buildRunnerInvocation"),Be=d((e,t,s)=>{if(e.language==="fail"){const n=e.entry??e.name??e.id??"hook failed";return`echo ${v(n)}; exit 1`}if(s)return H(e,s);if(ce.has(t)){const n=[];if(e.entry&&n.push(e.entry),Array.isArray(e.args))for(const r of e.args)n.push(v(r));return(e.pass_filenames??!0)&&!e.always_run&&n.push('"$@"'),n.join(" ")}return H(e)},"buildHookCommand"),Le=d((e,t,s,n)=>{if(Array.isArray(e.additional_dependencies))for(const r of e.additional_dependencies){const i=Pe(r);if(!i){n.push(`"${t}": additional_dependency "${r}" uses a pip-style pin and cannot be added to package.json — install manually.`);continue}s.push({hookId:t,name:i.name,raw:r,version:i.version})}},"collectAdditionalDeps"),He=d(e=>{const t=new Map,s=[],n=[],r=[],i=[];let o=!1;(e.files||e.exclude)&&n.push("top-level files/exclude filter dropped — apply it per hook if needed");for(const c of e.repos??[]){const f=c.repo??"<unknown>",b=f==="local",k=b?void 0:De(f);for(const h of c.hooks??[]){const g=h.id??"<unknown>";let M;if(b){const p=h.language??"system";if(!fe.has(p)){s.push({hookId:g,reason:`language "${p}" needs an isolated toolchain — run via prek or reimplement as a system command`,repo:f});continue}if(p!=="fail"&&!h.entry){s.push({hookId:g,reason:"missing `entry`",repo:f});continue}}else if(k&&(M=je.get(`${k}#${g}`)),!M){s.push({hookId:g,reason:`remote repo "${f}"@${c.rev??"?"} has no bundled equivalent — run via prek or replace with a system command`,repo:f});continue}Le(h,g,i,r);const O=Te(h);O.length>0&&n.push(`hook "${g}": unsupported types ${O.join(", ")} — those entries are ignored by the runner`);const I=Ce(h,e.default_stages);for(const p of I){if(p==="manual")continue;if(!ue.has(p)){s.push({hookId:g,reason:`unsupported stage "${p}"`,repo:f});continue}let x=Be(h,p,M);x.startsWith(X)&&(o=!0),h.verbose&&(x=`(set -x; ${x})`);const D=`${`# ${g}${h.name?`: ${h.name}`:""}`}
|
|
7
|
+
${x}`,u=t.get(p);u?u.push(D):t.set(p,[D])}}}const a=new Map;for(const[c,f]of t){const b=["#!/usr/bin/env sh",Oe];e.fail_fast&&b.push("set -e"),b.push("",f.join(`
|
|
8
|
+
|
|
9
|
+
`),""),a.set(c,b.join(`
|
|
10
|
+
`))}return{additionalDeps:i,droppedFilters:n,manualSteps:r,scripts:a,skippedHooks:s,usesRunner:o}},"convertPrekConfig"),qe=d(e=>{const t=de(e);if(t&&typeof t=="object")return t},"parsePrekConfig"),Ve=d(e=>{if(e.endsWith(".toml")){const s=ge(e);return s&&typeof s=="object"?s:void 0}const t=A(e);return qe(t)},"loadPrekConfig"),ze=d((e,t,s)=>{const n=l(e,"package.json"),r=[],i=[];if(!y(n)||t.length===0)return{added:r,skipped:i};const o=A(n),a=JSON.parse(o),c=a.devDependencies??{},f=a.dependencies??{};for(const k of t){if(k.name in c||k.name in f){i.push(k.name);continue}c[k.name]=k.version,r.push(k.name)}if(r.length===0)return{added:r,skipped:i};a.devDependencies=c;const b=pe(n,o,{defaultIndent:" ",useEditorconfig:s});return S(n,`${JSON.stringify(a,void 0,b)}
|
|
11
|
+
`,"utf8"),{added:r,skipped:i}},"mergeAdditionalDependencies"),Ge=d((e,t)=>{const s=l(e,t,".builtins");z(s),S(l(s,E),_e,{mode:493}),S(l(s,"README.md"),["# Vis prek runner","","Auto-generated by `vis hook migrate` from a prek/pre-commit config.","This directory is owned by the migrator — do not edit by hand.","",`Supported built-in hooks: ${Ee.join(", ")}`,""].join(`
|
|
12
|
+
`),"utf8")},"writeRunnerAssets"),Ke=d((e,t)=>{w("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?w("prek",["uninstall"],{cwd:e,encoding:"utf8"}).status===0?t.info("Detached prek via `prek uninstall`."):t.info("`prek uninstall` did not exit cleanly — continuing. You may need to run it manually."):t.info("prek binary not found on PATH — skipping `prek uninstall`. Run it manually if prek is installed elsewhere.")},"detachPrek"),Q=d((e,t,s,n={})=>{const r=L(e),i=n.dryRun===!0;if(!r)return{isError:!0,message:"No prek configuration found (.pre-commit-config.yaml, .pre-commit-config.yml, or prek.toml)"};s.info(`Found prek config at ${r}`);const o=l(e,r),a=A(o),c=Ve(o);if(!c)return{isError:!0,message:`Could not parse ${r}`};const{additionalDeps:f,droppedFilters:b,manualSteps:k,scripts:h,skippedHooks:g,usesRunner:M}=He(c);if(h.size===0&&g.length===0)return{isError:!0,message:`${r} has no hooks to migrate`};if(!i){const u=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(u.status===0){const T=u.stdout?.toString().trim();T&&(T.includes(".prek")||T.includes("prek-hooks"))&&w("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const R=K(t);if(R.isError)return R;R.message&&s.info(R.message)}const O=l(e,t);i||z(O),M&&(i?s.info(` (would write) ${t}/.builtins/${E}`):(Ge(e,t),s.info(` Wrote ${t}/.builtins/${E}`)));let I=0;for(const[u,R]of h)i?s.info(` (would write) ${t}/${u} (${R.split(`
|
|
13
|
+
`).length} lines)`):(S(l(O,u),R,{mode:493}),s.info(` Wrote ${t}/${u}`)),I+=1;const{added:p,skipped:x}=i?{added:f.map(u=>u.name),skipped:[]}:ze(e,f,n.useEditorconfig);if(p.length>0){const u=i?"would add":"Added";s.info(`${u} ${p.length} package${p.length===1?"":"s"} to devDependencies: ${p.join(", ")}`),i||s.info("Run your package manager's install (e.g. `pnpm install`) to pick up the new devDependencies.")}x.length>0&&s.info(`Skipped ${x.length} already-declared package${x.length===1?"":"s"}: ${x.join(", ")}`),i||Ke(e,s);const D=`${o}.bak`;if(i?s.info(` (would remove) ${r} and back it up to ${r}.bak`):(y(D)||S(D,a,"utf8"),ne(o),s.info(`Removed ${r} (backup at ${r}.bak)`)),g.length>0){s.warn(`Skipped ${g.length} hook${g.length===1?"":"s"} that cannot run without prek:`);for(const u of g)s.warn(` - ${u.repo}::${u.hookId} — ${u.reason}`)}if(b.length>0){s.warn("Partial filter translations:");for(const u of b)s.warn(` - ${u}`)}if(k.length>0){s.warn("Manual follow-up required:");for(const u of k)s.warn(` - ${u}`)}return{isError:!1,message:`${i?"would migrate":"Migration complete:"} ${I} stage script${I===1?"":"s"} ${i?"into":"written to"} ${t}/`}},"migrateFromPrek");var Je=Object.defineProperty,Z=$((e,t)=>Je(e,"name",{value:t,configurable:!0}),"a");const Ue="pre-commit",Ye=Z((e,t,s,n)=>{const r=s.stage??Ue,i=l(e,t,r);if(!y(i))throw new Error(`No script found at ${t}/${r}. Install or migrate hooks first.`);if(s.lastCommit&&(s.fromRef||s.toRef))throw new Error("--last-commit cannot be combined with --from-ref or --to-ref");const o=s.lastCommit?"HEAD~1":s.fromRef,a=s.lastCommit?"HEAD":s.toRef;if(o&&!a)throw new Error("--from-ref requires --to-ref");if(a&&!o)throw new Error("--to-ref requires --from-ref");const c={...process.env};s.allFiles&&(c.VIS_HOOK_ALL_FILES="1"),o&&(c.VIS_HOOK_FROM_REF=o),a&&(c.VIS_HOOK_TO_REF=a),n.info(`Running ${t}/${r}${s.allFiles?" (--all-files)":""}${o?` (${o}..${a})`:""}`);const f=w("sh",["-e",i],{cwd:e,env:c,stdio:"inherit"});if(f.error)throw f.error;return f.status??1},"runHookStage"),Xe=Z((e,t,s)=>{const n=Ye(j(),e,t,s);if(n!==0)throw new Error(`Hook stage exited with code ${n}`)},"runRun");var Qe=Object.defineProperty,Ze=$((e,t)=>Qe(e,"name",{value:t,configurable:!0}),"e");const et=Ze((e=J)=>{if(w("git",["config","--local","core.hooksPath"]).status!==0)return{isError:!1,message:"No custom hooks path configured"};const{status:t,stderr:s}=w("git",["config","--local","--unset","core.hooksPath"]);if(t===null)return{isError:!0,message:"git command not found"};if(t&&t!==5)return{isError:!0,message:String(s)};const n=l(e,"_");return y(n)&&re(n,{force:!0,recursive:!0}),{isError:!1,message:""}},"uninstallHooks");var tt=Object.defineProperty,P=$((e,t)=>tt(e,"name",{value:t,configurable:!0}),"u");const st=new Set(G),nt=P(e=>{const t=w("sh",["-n",e],{encoding:"utf8"});if(t.status===null)return`failed to run "sh -n" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`sh -n exited with ${t.status}`},"runSyntaxCheck"),rt=P(e=>{const t=w("node",["--check",e],{encoding:"utf8"});if(t.status===null)return`failed to run "node --check" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`node --check exited with ${t.status}`},"runNodeCheck"),it=P((e,t)=>{const s=[],n=l(e,t),r=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(r.status===0){const o=r.stdout.trim(),a=`${t}/_`;o&&o!==a&&s.push({kind:"warning",message:`core.hooksPath is "${o}" — expected "${a}". Re-run \`vis hook install\` to fix.`})}else s.push({kind:"warning",message:"core.hooksPath is not set — run `vis hook install`."});if(y(l(n,"_"))||s.push({kind:"error",message:`Dispatcher directory ${t}/_ is missing. Run \`vis hook install\`.`}),!y(n))return s.push({kind:"error",message:`Hooks directory ${t}/ is missing.`}),{issues:s,ok:!1};let i=!1;for(const o of V(n)){if(o.startsWith(".")||o==="_")continue;if(!st.has(o)){s.push({kind:"warning",message:`Unknown hook "${o}" — not a standard git hook.`,path:l(t,o)});continue}const a=l(n,o);if(!C(a).isFile())continue;const c=C(a).mode&511;(c&64)===0&&s.push({kind:"warning",message:`Script is not owner-executable (mode ${c.toString(8)}).`,path:l(t,o)});const f=nt(a);f&&s.push({kind:"error",message:`Shell syntax error: ${f}`,path:l(t,o)}),A(a).includes(`/.builtins/${E}`)&&(i=!0)}if(i){const o=l(n,".builtins",E);if(y(o)){const a=rt(o);a&&s.push({kind:"error",message:`prek-runner.mjs has a syntax error: ${a}`,path:l(t,".builtins",E)})}else s.push({kind:"error",message:`Hook scripts reference ${t}/.builtins/${E} but the file is missing. Re-run \`vis hook migrate\`.`})}return{issues:s,ok:!s.some(o=>o.kind==="error")}},"validateHooks"),ot=P((e,t)=>{if(e.issues.length===0)return[`Hook directory ${t}/ looks good.`];const s=[];for(const n of e.issues){const r=n.kind==="error"?"ERROR":"WARN ",i=n.path?` (${n.path})`:"";s.push(`${r} ${n.message}${i}`)}return s.push("",e.ok?"No errors — warnings only.":`${e.issues.filter(n=>n.kind==="error").length} error(s).`),s},"formatValidationResult"),at=P((e,t)=>{const s=it(j(),e),n=ot(s,e);for(const r of n)r.startsWith("ERROR")||r.startsWith("WARN")?t.warn(r):t.info(r);if(!s.ok)throw new Error("Hook validation failed")},"runValidate");var lt=Object.defineProperty,m=$((e,t)=>lt(e,"name",{value:t,configurable:!0}),"i");const _=m(e=>e.hooksDir??J,"resolveHooksDirectory"),q=m(e=>new Promise(t=>{const s=oe({input:process.stdin,output:process.stdout});s.question(`${e} (y/N) `,n=>{s.close();const r=n.trim().toLowerCase();t(r==="y"||r==="yes")})}),"confirmPrompt"),ct=m(async(e,t,s)=>{const n=j(),r=U(n),i=L(n);if(r&&i)throw new Error(`Found both husky (${r}/) and prek (${i}). Remove or migrate one before running \`vis hook install\`.`);if(r){if(t.info(`Existing husky installation found at ${r}/`),await q("Would you like to migrate your husky hooks to vis?")){const a=Y(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.message);return}t.info("Aborting install. Remove husky first or run 'vis hook migrate' to migrate.");return}if(i){if(t.info(`Existing prek configuration found at ${i}`),await q("Would you like to migrate your prek hooks to vis?")){const a=Q(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.message);return}t.info("Aborting install. Remove the prek config first or run 'vis hook migrate' to migrate.");return}t.info(`Installing git hooks in ${e}/...`);const o=K(e);if(o.message){if(o.isError)throw new Error(o.message);t.info(o.message);return}y(l(n,e,"pre-commit"))||S(l(n,e,"pre-commit"),`#!/usr/bin/env sh
|
|
14
|
+
`,{mode:493}),t.info("Git hooks installed successfully.")},"executeInstall"),ft=m((e,t,s,n)=>{const r=j(),i=U(r),o=L(r);if(i&&o)throw new Error(`Found both husky (${i}/) and prek (${o}). Migrate one at a time — rename or remove one before retrying.`);if(!i&&!o)throw new Error("No husky (.husky/) or prek (.pre-commit-config.yaml / prek.toml) configuration found to migrate.");t&&s.info("(dry-run) no files will be written");const a=i?Y(r,e,s,{dryRun:t,useEditorconfig:n}):Q(r,e,s,{dryRun:t,useEditorconfig:n});if(a.isError)throw new Error(a.message);a.message&&s.info(a.message)},"executeMigrate"),W="# vis:secrets-hook",ut=`#!/usr/bin/env sh
|
|
15
|
+
${W}
|
|
16
|
+
# Scan staged files for secrets before each commit. Remove this block or the whole file to disable.
|
|
17
|
+
pnpm exec vis secrets --staged --quiet || exit 1
|
|
18
|
+
`,dt=m((e,t,s)=>{if(e!=="secrets")throw new Error(`Unknown hook add target "${String(e)}". Currently supported: "secrets".`);const n=j(),r=l(n,t,"pre-commit");if(!y(l(n,t)))throw new Error(`Hooks directory ${t}/ does not exist. Run \`vis hook install\` first.`);if(y(r)){const i=A(r);if(i.includes(W)){s.info(`Secrets hook already present in ${r}.`);return}if(/\bvis secrets\b/.test(i)){s.warn(`Found a \`vis secrets\` invocation in ${r} without the managed marker — leaving it untouched.`);return}const o=`${i.trimEnd()}
|
|
19
|
+
|
|
20
|
+
${W}
|
|
21
|
+
pnpm exec vis secrets --staged --quiet || exit 1
|
|
22
|
+
`;S(r,o),ie(r,493),s.info(`Appended secrets scan to ${r}.`);return}S(r,ut,{mode:493}),s.info(`Created ${r} with a secrets-scan pre-commit check.`)},"executeAdd"),pt=m((e,t)=>{t.info("Removing git hooks...");const s=et(e);if(s.message){if(s.isError)throw new Error(s.message);t.info(s.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),gt=m(async({logger:e,options:t,visConfig:s})=>{await ct(_(t),e,s?.editorconfig??!0)},"hookInstallImpl"),ht=m(({logger:e,options:t})=>{pt(_(t),e)},"hookUninstallImpl"),mt=m(({logger:e,options:t,visConfig:s})=>{ft(_(t),!!t.dryRun,e,s?.editorconfig??!0)},"hookMigrateImpl"),kt=m(({logger:e,options:t})=>{we(_(t),e)},"hookListImpl"),yt=m(({logger:e,options:t})=>{at(_(t),e)},"hookValidateImpl"),bt=m(({argument:e,logger:t,options:s})=>{Xe(_(s),{allFiles:!!s.allFiles,fromRef:s.fromRef,lastCommit:!!s.lastCommit,stage:e[0],toRef:s.toRef},t)},"hookRunImpl"),wt=m(({argument:e,logger:t,options:s})=>{dt(e[0],_(s),t)},"hookAddImpl"),_t=gt,Ft=ht,jt=mt,At=kt,Mt=yt,Ot=bt,It=wt;export{It as hookAddExecute,_t as hookInstallExecute,At as hookListExecute,jt as hookMigrateExecute,Ot as hookRunExecute,Ft as hookUninstallExecute,Mt as hookValidateExecute};
|