codebase-snapshot 0.9.16 → 0.9.18
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 +136 -0
- package/README.md +4 -4
- package/SECURITY.md +18 -6
- package/dist/bin.js +2024 -622
- package/dist/{chunk-WIL536QD.js → chunk-XAW5GY6X.js} +98 -25
- package/dist/{chunk-6TRFLA7N.js → chunk-ZXWAVHSZ.js} +1758 -444
- package/dist/cli.cjs +2006 -608
- package/dist/cli.d.cts +1 -11
- package/dist/cli.d.ts +1 -11
- package/dist/cli.js +17 -6
- package/dist/index.cjs +1752 -438
- package/dist/index.d.cts +106 -9
- package/dist/index.d.ts +106 -9
- package/dist/index.js +1 -1
- package/dist/mcp.cjs +1761 -341
- package/dist/mcp.d.cts +7 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.js +2 -2
- package/dist/{types-DIX6zWSt.d.cts → types-KbJvBjmV.d.cts} +46 -1
- package/dist/{types-DIX6zWSt.d.ts → types-KbJvBjmV.d.ts} +46 -1
- package/docs/cli.md +20 -13
- package/docs/configuration.md +16 -1
- package/docs/mcp.md +17 -7
- package/docs/output.md +3 -3
- package/docs/vs-gitingest.md +6 -2
- package/docs/vs-repomix.md +9 -5
- package/package.json +16 -18
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as crypto2 from 'crypto';
|
|
2
2
|
import { createHash } from 'crypto';
|
|
3
|
+
import { Worker } from 'worker_threads';
|
|
3
4
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
4
|
-
import * as
|
|
5
|
+
import * as fs15 from 'fs';
|
|
5
6
|
import * as os from 'os';
|
|
6
7
|
import * as path16 from 'path';
|
|
7
8
|
import ts from 'typescript';
|
|
@@ -12,7 +13,6 @@ import { execFileSync } from 'child_process';
|
|
|
12
13
|
import * as http from 'http';
|
|
13
14
|
import * as https from 'https';
|
|
14
15
|
import * as readline from 'readline';
|
|
15
|
-
import { Worker } from 'worker_threads';
|
|
16
16
|
|
|
17
17
|
// src/index.ts
|
|
18
18
|
var hookStdoutScope = new AsyncLocalStorage();
|
|
@@ -620,9 +620,9 @@ var rubyProfile = {
|
|
|
620
620
|
eachLine(content, (line) => {
|
|
621
621
|
const trimmed = line.trim();
|
|
622
622
|
if (!trimmed || trimmed.startsWith("#")) return;
|
|
623
|
-
const
|
|
624
|
-
if (
|
|
625
|
-
summary.imports.push(`./${
|
|
623
|
+
const relative10 = REQUIRE_RELATIVE.exec(trimmed);
|
|
624
|
+
if (relative10) {
|
|
625
|
+
summary.imports.push(`./${relative10[1]}`);
|
|
626
626
|
return;
|
|
627
627
|
}
|
|
628
628
|
const required = REQUIRE.exec(trimmed);
|
|
@@ -722,6 +722,16 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
|
|
|
722
722
|
"HEAD",
|
|
723
723
|
"OPTIONS"
|
|
724
724
|
]);
|
|
725
|
+
var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
|
|
726
|
+
var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
|
|
727
|
+
"get",
|
|
728
|
+
"post",
|
|
729
|
+
"put",
|
|
730
|
+
"delete",
|
|
731
|
+
"patch",
|
|
732
|
+
"head",
|
|
733
|
+
"options"
|
|
734
|
+
]);
|
|
725
735
|
function bindingNames(name, into) {
|
|
726
736
|
if (ts.isIdentifier(name)) {
|
|
727
737
|
into.push(name.text);
|
|
@@ -732,6 +742,53 @@ function bindingNames(name, into) {
|
|
|
732
742
|
bindingNames(element.name, into);
|
|
733
743
|
}
|
|
734
744
|
}
|
|
745
|
+
function objectLiteralNames(node) {
|
|
746
|
+
const names = [];
|
|
747
|
+
for (const property of node.properties) {
|
|
748
|
+
if (ts.isShorthandPropertyAssignment(property)) {
|
|
749
|
+
names.push(property.name.text);
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
753
|
+
const name = property.name;
|
|
754
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
|
|
755
|
+
names.push(name.text);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return names;
|
|
759
|
+
}
|
|
760
|
+
function cjsExportedNames(expression) {
|
|
761
|
+
const left = expression.left;
|
|
762
|
+
if (!ts.isPropertyAccessExpression(left)) return null;
|
|
763
|
+
const isModuleExports = left.name.text === "exports" && ts.isIdentifier(left.expression) && left.expression.text === "module";
|
|
764
|
+
if (isModuleExports) {
|
|
765
|
+
const right = expression.right;
|
|
766
|
+
if (ts.isObjectLiteralExpression(right)) return objectLiteralNames(right);
|
|
767
|
+
if (ts.isIdentifier(right)) return [right.text];
|
|
768
|
+
return [];
|
|
769
|
+
}
|
|
770
|
+
if (ts.isIdentifier(left.expression) && left.expression.text === "exports") {
|
|
771
|
+
return [left.name.text];
|
|
772
|
+
}
|
|
773
|
+
const parent = left.expression;
|
|
774
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts.isIdentifier(parent.expression) && parent.expression.text === "module") {
|
|
775
|
+
return [left.name.text];
|
|
776
|
+
}
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
function countSyntacticErrors(fileName, content) {
|
|
780
|
+
const result = ts.transpileModule(content, {
|
|
781
|
+
fileName,
|
|
782
|
+
compilerOptions: {
|
|
783
|
+
target: ts.ScriptTarget.Latest,
|
|
784
|
+
module: ts.ModuleKind.ESNext
|
|
785
|
+
},
|
|
786
|
+
reportDiagnostics: true
|
|
787
|
+
});
|
|
788
|
+
return (result.diagnostics ?? []).filter(
|
|
789
|
+
(diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error
|
|
790
|
+
).length;
|
|
791
|
+
}
|
|
735
792
|
function summarizeTypeScriptSource(relativePath, content) {
|
|
736
793
|
const summary = {
|
|
737
794
|
directives: [],
|
|
@@ -749,16 +806,17 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
749
806
|
routeHandlers: []
|
|
750
807
|
};
|
|
751
808
|
const lowerPath = relativePath.toLowerCase();
|
|
752
|
-
const
|
|
809
|
+
const scriptKind = /.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
|
|
753
810
|
const sourceFile = ts.createSourceFile(
|
|
754
811
|
relativePath,
|
|
755
812
|
content,
|
|
756
813
|
ts.ScriptTarget.Latest,
|
|
757
814
|
/* setParentNodes */
|
|
758
815
|
false,
|
|
759
|
-
|
|
816
|
+
scriptKind
|
|
760
817
|
);
|
|
761
|
-
const
|
|
818
|
+
const parsedDiagnostics = sourceFile.parseDiagnostics;
|
|
819
|
+
const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
|
|
762
820
|
if (parseErrors > 0) summary.parseErrors = parseErrors;
|
|
763
821
|
for (const statement of sourceFile.statements) {
|
|
764
822
|
if (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) {
|
|
@@ -815,6 +873,7 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
815
873
|
if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
|
|
816
874
|
if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
|
|
817
875
|
};
|
|
876
|
+
const cjsExports = [];
|
|
818
877
|
const stack = [sourceFile];
|
|
819
878
|
while (stack.length > 0) {
|
|
820
879
|
const node = stack.pop();
|
|
@@ -831,6 +890,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
831
890
|
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
|
|
832
891
|
if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
|
|
833
892
|
}
|
|
893
|
+
const callee = node.expression;
|
|
894
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
|
|
895
|
+
summary.routeHandlers.push(callee.name.text.toUpperCase());
|
|
896
|
+
}
|
|
834
897
|
}
|
|
835
898
|
if (ts.isExportDeclaration(node)) {
|
|
836
899
|
if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
@@ -848,6 +911,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
848
911
|
}
|
|
849
912
|
}
|
|
850
913
|
}
|
|
914
|
+
if (ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
915
|
+
const cjsNames = cjsExportedNames(node.expression);
|
|
916
|
+
if (cjsNames !== null) cjsExports.push(...cjsNames);
|
|
917
|
+
}
|
|
851
918
|
if (ts.isExportAssignment(node)) {
|
|
852
919
|
summary.exports.push("default");
|
|
853
920
|
if (rendersJsx(node.expression)) summary.reactComponents.push("default");
|
|
@@ -911,6 +978,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
911
978
|
stack.push(children[index]);
|
|
912
979
|
}
|
|
913
980
|
}
|
|
981
|
+
if (cjsExports.length > 0) {
|
|
982
|
+
summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
|
|
983
|
+
summary.exports.push(...cjsExports);
|
|
984
|
+
}
|
|
914
985
|
const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
915
986
|
summary.directives = dedupeSorted2(summary.directives);
|
|
916
987
|
summary.imports = dedupeSorted2(summary.imports);
|
|
@@ -1366,13 +1437,13 @@ function isBinaryFile(absolutePath) {
|
|
|
1366
1437
|
if (isBinaryExtension(absolutePath)) return true;
|
|
1367
1438
|
let fd;
|
|
1368
1439
|
try {
|
|
1369
|
-
fd =
|
|
1440
|
+
fd = fs15.openSync(absolutePath, "r");
|
|
1370
1441
|
const buffer = Buffer.alloc(CHUNK);
|
|
1371
1442
|
let sample;
|
|
1372
1443
|
let position = 0;
|
|
1373
1444
|
while (position < BINARY_SCAN_BYTES) {
|
|
1374
1445
|
const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
|
|
1375
|
-
const bytesRead =
|
|
1446
|
+
const bytesRead = fs15.readSync(fd, buffer, 0, wanted, position);
|
|
1376
1447
|
if (bytesRead === 0) return false;
|
|
1377
1448
|
const chunk = buffer.subarray(0, bytesRead);
|
|
1378
1449
|
if (sample === void 0) {
|
|
@@ -1390,7 +1461,7 @@ function isBinaryFile(absolutePath) {
|
|
|
1390
1461
|
} finally {
|
|
1391
1462
|
if (fd !== void 0) {
|
|
1392
1463
|
try {
|
|
1393
|
-
|
|
1464
|
+
fs15.closeSync(fd);
|
|
1394
1465
|
} catch {
|
|
1395
1466
|
}
|
|
1396
1467
|
}
|
|
@@ -1412,9 +1483,9 @@ function importsOfText(relativePath, text2) {
|
|
|
1412
1483
|
function importsOfFile(relativePath, absolutePath) {
|
|
1413
1484
|
let buffer;
|
|
1414
1485
|
try {
|
|
1415
|
-
const stats =
|
|
1486
|
+
const stats = fs15.statSync(absolutePath);
|
|
1416
1487
|
if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
|
|
1417
|
-
buffer =
|
|
1488
|
+
buffer = fs15.readFileSync(absolutePath);
|
|
1418
1489
|
} catch {
|
|
1419
1490
|
return [];
|
|
1420
1491
|
}
|
|
@@ -1706,9 +1777,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
|
|
|
1706
1777
|
]);
|
|
1707
1778
|
function readSmallFile(fullPath) {
|
|
1708
1779
|
try {
|
|
1709
|
-
const stats =
|
|
1780
|
+
const stats = fs15.statSync(fullPath);
|
|
1710
1781
|
if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
|
|
1711
|
-
return
|
|
1782
|
+
return fs15.readFileSync(fullPath, "utf8");
|
|
1712
1783
|
} catch {
|
|
1713
1784
|
return null;
|
|
1714
1785
|
}
|
|
@@ -1774,7 +1845,7 @@ function pnpmWorkspacePatterns(raw) {
|
|
|
1774
1845
|
function childDirectories(cwd, parent) {
|
|
1775
1846
|
let entries;
|
|
1776
1847
|
try {
|
|
1777
|
-
entries =
|
|
1848
|
+
entries = fs15.readdirSync(path16.join(cwd, parent), { withFileTypes: true });
|
|
1778
1849
|
} catch {
|
|
1779
1850
|
return [];
|
|
1780
1851
|
}
|
|
@@ -1809,10 +1880,10 @@ function workspacePackageDirs(cwd, patterns) {
|
|
|
1809
1880
|
function scanWorkspacePackages(cwd, patterns) {
|
|
1810
1881
|
const files = /* @__PURE__ */ new Set();
|
|
1811
1882
|
const dependencies = /* @__PURE__ */ new Set();
|
|
1812
|
-
for (const
|
|
1813
|
-
const full = path16.join(cwd,
|
|
1883
|
+
for (const relative10 of workspacePackageDirs(cwd, patterns)) {
|
|
1884
|
+
const full = path16.join(cwd, relative10);
|
|
1814
1885
|
try {
|
|
1815
|
-
for (const entry of
|
|
1886
|
+
for (const entry of fs15.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
|
|
1816
1887
|
} catch {
|
|
1817
1888
|
}
|
|
1818
1889
|
const raw = readSmallFile(path16.join(full, "package.json"));
|
|
@@ -1825,7 +1896,7 @@ function scanWorkspacePackages(cwd, patterns) {
|
|
|
1825
1896
|
var SNAPSHOT_MARKER = ".codebase-snapshot";
|
|
1826
1897
|
function isToolOwnedDirectory(dir) {
|
|
1827
1898
|
try {
|
|
1828
|
-
return
|
|
1899
|
+
return fs15.statSync(dir).isDirectory() && fs15.existsSync(path16.join(dir, SNAPSHOT_MARKER));
|
|
1829
1900
|
} catch {
|
|
1830
1901
|
return false;
|
|
1831
1902
|
}
|
|
@@ -1840,7 +1911,7 @@ function countMarkdownFiles(cwd) {
|
|
|
1840
1911
|
directoriesSeen += 1;
|
|
1841
1912
|
let entries;
|
|
1842
1913
|
try {
|
|
1843
|
-
entries =
|
|
1914
|
+
entries = fs15.readdirSync(current.dir, { withFileTypes: true });
|
|
1844
1915
|
} catch {
|
|
1845
1916
|
continue;
|
|
1846
1917
|
}
|
|
@@ -1862,7 +1933,7 @@ function buildPresetContext(cwd) {
|
|
|
1862
1933
|
const files = /* @__PURE__ */ new Set();
|
|
1863
1934
|
const dirs = /* @__PURE__ */ new Set();
|
|
1864
1935
|
try {
|
|
1865
|
-
for (const entry of
|
|
1936
|
+
for (const entry of fs15.readdirSync(cwd, { withFileTypes: true })) {
|
|
1866
1937
|
if (entry.isDirectory()) dirs.add(entry.name);
|
|
1867
1938
|
else if (entry.isFile()) files.add(entry.name);
|
|
1868
1939
|
}
|
|
@@ -2737,7 +2808,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
|
|
|
2737
2808
|
var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
|
|
2738
2809
|
var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
|
|
2739
2810
|
var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
|
|
2740
|
-
|
|
2811
|
+
function quotedValueFor(delimiterGroup) {
|
|
2812
|
+
return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
|
|
2813
|
+
}
|
|
2814
|
+
var QUOTED_VALUE = quotedValueFor(1);
|
|
2741
2815
|
var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
|
|
2742
2816
|
var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
|
|
2743
2817
|
var DEFAULT_SECRET_PATTERNS = [
|
|
@@ -2891,7 +2965,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
2891
2965
|
// consumes the flag so the match is the credential alone.
|
|
2892
2966
|
// - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
|
|
2893
2967
|
rule: "uri-credentials",
|
|
2894
|
-
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[
|
|
2968
|
+
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[A-Za-z0-9._~-][A-Za-z0-9._~-]{0,127}:[^\s"'%$()+]{1,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
|
|
2895
2969
|
},
|
|
2896
2970
|
{
|
|
2897
2971
|
// The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
|
|
@@ -3003,7 +3077,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3003
3077
|
// rendering of textual userinfo mixes cases, while the prose the earlier rules were
|
|
3004
3078
|
// protecting (`Bearer authentication`) is a lowercase word.
|
|
3005
3079
|
rule: "authorization-header",
|
|
3006
|
-
pattern: /(?<=
|
|
3080
|
+
pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
|
|
3007
3081
|
},
|
|
3008
3082
|
{
|
|
3009
3083
|
// Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
|
|
@@ -3030,7 +3104,9 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3030
3104
|
// between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
|
|
3031
3105
|
rule: "interpolation-fallback-secret",
|
|
3032
3106
|
pattern: new RegExp(
|
|
3033
|
-
|
|
3107
|
+
// The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
|
|
3108
|
+
// and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
|
|
3109
|
+
`(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
|
|
3034
3110
|
"i"
|
|
3035
3111
|
),
|
|
3036
3112
|
valueGroup: 1
|
|
@@ -3079,19 +3155,15 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3079
3155
|
if (pattern instanceof RegExp) {
|
|
3080
3156
|
const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
|
|
3081
3157
|
if (valueGroup !== void 0) flags.add("d");
|
|
3082
|
-
return
|
|
3083
|
-
rule,
|
|
3084
|
-
pattern: new RegExp(pattern.source, [...flags].join("")),
|
|
3085
|
-
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3086
|
-
};
|
|
3158
|
+
return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
|
|
3087
3159
|
}
|
|
3088
3160
|
if (typeof pattern === "string") {
|
|
3089
3161
|
try {
|
|
3090
|
-
return
|
|
3162
|
+
return checkedPattern(
|
|
3091
3163
|
rule,
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3164
|
+
new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
|
|
3165
|
+
valueGroup
|
|
3166
|
+
);
|
|
3095
3167
|
} catch (err) {
|
|
3096
3168
|
throw new Error(
|
|
3097
3169
|
`Invalid regular expression for secret rule "${rule}": ${err.message}`
|
|
@@ -3102,6 +3174,19 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3102
3174
|
`Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
|
|
3103
3175
|
);
|
|
3104
3176
|
}
|
|
3177
|
+
function checkedPattern(rule, compiled, valueGroup) {
|
|
3178
|
+
const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
|
|
3179
|
+
if (stateless.test("")) {
|
|
3180
|
+
throw new Error(
|
|
3181
|
+
`Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
|
|
3182
|
+
);
|
|
3183
|
+
}
|
|
3184
|
+
return {
|
|
3185
|
+
rule,
|
|
3186
|
+
pattern: compiled,
|
|
3187
|
+
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3105
3190
|
function compileSecretRules(rules) {
|
|
3106
3191
|
if (!Array.isArray(rules)) {
|
|
3107
3192
|
throw new Error(
|
|
@@ -3158,6 +3243,193 @@ function toGlobal(rule) {
|
|
|
3158
3243
|
}
|
|
3159
3244
|
var LINE_BREAK = /(\r\n|\n|\r)/;
|
|
3160
3245
|
var LINE_TERMINATOR = /\r\n|\n|\r/g;
|
|
3246
|
+
function isOpeningQuote(line, index) {
|
|
3247
|
+
const code = line.charCodeAt(index);
|
|
3248
|
+
if (code === 96) return true;
|
|
3249
|
+
if (code !== 34 && code !== 39) return false;
|
|
3250
|
+
return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
|
|
3251
|
+
}
|
|
3252
|
+
function quoteStates(line) {
|
|
3253
|
+
const states = new Uint8Array(line.length + 1);
|
|
3254
|
+
let quote = 0;
|
|
3255
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3256
|
+
states[index] = quote;
|
|
3257
|
+
const code = line.charCodeAt(index);
|
|
3258
|
+
if (quote === 0) {
|
|
3259
|
+
if (isOpeningQuote(line, index)) quote = code;
|
|
3260
|
+
} else if (code === 92) {
|
|
3261
|
+
if (index + 1 < line.length) {
|
|
3262
|
+
index += 1;
|
|
3263
|
+
states[index] = quote;
|
|
3264
|
+
}
|
|
3265
|
+
} else if (code === quote) {
|
|
3266
|
+
quote = 0;
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
states[line.length] = quote;
|
|
3270
|
+
return states;
|
|
3271
|
+
}
|
|
3272
|
+
function quoteStateFor(line, context) {
|
|
3273
|
+
if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
|
|
3274
|
+
return context.quoteAt;
|
|
3275
|
+
}
|
|
3276
|
+
function quoteStateAfter(text2, quote, end = text2.length) {
|
|
3277
|
+
for (let index = 0; index < end; index += 1) {
|
|
3278
|
+
const code = text2.charCodeAt(index);
|
|
3279
|
+
if (quote === 0) {
|
|
3280
|
+
if (isOpeningQuote(text2, index)) quote = code;
|
|
3281
|
+
} else if (code === 92) {
|
|
3282
|
+
index += 1;
|
|
3283
|
+
} else if (code === quote) {
|
|
3284
|
+
quote = 0;
|
|
3285
|
+
}
|
|
3286
|
+
}
|
|
3287
|
+
return quote;
|
|
3288
|
+
}
|
|
3289
|
+
function commentStartFor(line, context) {
|
|
3290
|
+
if (context.commentStart !== void 0) return context.commentStart;
|
|
3291
|
+
const quotes = quoteStateFor(line, context);
|
|
3292
|
+
let start = line.length;
|
|
3293
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3294
|
+
if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
|
|
3295
|
+
if (index === 0 || /\s/.test(line[index - 1])) {
|
|
3296
|
+
start = index;
|
|
3297
|
+
break;
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
context.commentStart = start;
|
|
3301
|
+
return start;
|
|
3302
|
+
}
|
|
3303
|
+
function commandSeparatorsFor(line, context) {
|
|
3304
|
+
if (context.commandSeparators !== void 0) return context.commandSeparators;
|
|
3305
|
+
const quotes = quoteStateFor(line, context);
|
|
3306
|
+
const separators = [];
|
|
3307
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3308
|
+
if (quotes[index] !== 0) continue;
|
|
3309
|
+
const ch = line[index];
|
|
3310
|
+
const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
|
|
3311
|
+
if (ch === "&" || ch === "|") {
|
|
3312
|
+
if (line[index + 1] === ch) {
|
|
3313
|
+
const after = index + 2;
|
|
3314
|
+
const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
|
|
3315
|
+
if (doubleSpaced) separators.push(index);
|
|
3316
|
+
index += 1;
|
|
3317
|
+
} else if (spaced) {
|
|
3318
|
+
separators.push(index);
|
|
3319
|
+
}
|
|
3320
|
+
} else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
|
|
3321
|
+
separators.push(index);
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
context.commandSeparators = separators;
|
|
3325
|
+
return separators;
|
|
3326
|
+
}
|
|
3327
|
+
function lineValueEnd(line, start, context) {
|
|
3328
|
+
const comment = commentStartFor(line, context);
|
|
3329
|
+
let end = comment > start ? comment : line.length;
|
|
3330
|
+
for (const separator of commandSeparatorsFor(line, context)) {
|
|
3331
|
+
if (separator > start && separator < end) {
|
|
3332
|
+
end = separator;
|
|
3333
|
+
break;
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
while (end > start && /\s/.test(line[end - 1])) end -= 1;
|
|
3337
|
+
return end;
|
|
3338
|
+
}
|
|
3339
|
+
function hasStructuralQuote(line) {
|
|
3340
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3341
|
+
const ch = line[index];
|
|
3342
|
+
if (ch !== '"' && ch !== "'" && ch !== "`") continue;
|
|
3343
|
+
if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
|
|
3344
|
+
let backslashes = 0;
|
|
3345
|
+
for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
|
|
3346
|
+
if (backslashes % 2 === 1) continue;
|
|
3347
|
+
let before = index - 1;
|
|
3348
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3349
|
+
if (before < 0 || "+,=:([{".includes(line[before])) return true;
|
|
3350
|
+
}
|
|
3351
|
+
return false;
|
|
3352
|
+
}
|
|
3353
|
+
function maskRawPemLine(line) {
|
|
3354
|
+
if (line.trim() === "") return line;
|
|
3355
|
+
const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
|
|
3356
|
+
let rest = line.slice(leading.length);
|
|
3357
|
+
const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
|
|
3358
|
+
rest = rest.slice(0, rest.length - trailing.length);
|
|
3359
|
+
return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
|
|
3360
|
+
}
|
|
3361
|
+
function skeletonisePemLine(line, initialQuote) {
|
|
3362
|
+
const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
|
|
3363
|
+
const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
|
|
3364
|
+
if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
|
|
3365
|
+
let out = "";
|
|
3366
|
+
let quote = initialQuote;
|
|
3367
|
+
let masking = false;
|
|
3368
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3369
|
+
const code = line.charCodeAt(index);
|
|
3370
|
+
if (quote === 0) {
|
|
3371
|
+
if (isOpeningQuote(line, index)) {
|
|
3372
|
+
quote = code;
|
|
3373
|
+
masking = false;
|
|
3374
|
+
}
|
|
3375
|
+
out += line[index];
|
|
3376
|
+
continue;
|
|
3377
|
+
}
|
|
3378
|
+
if (code === 92) {
|
|
3379
|
+
masking = false;
|
|
3380
|
+
out += line[index];
|
|
3381
|
+
if (index + 1 < line.length) {
|
|
3382
|
+
out += line[index + 1];
|
|
3383
|
+
index += 1;
|
|
3384
|
+
}
|
|
3385
|
+
continue;
|
|
3386
|
+
}
|
|
3387
|
+
if (code === quote) {
|
|
3388
|
+
masking = false;
|
|
3389
|
+
quote = 0;
|
|
3390
|
+
out += line[index];
|
|
3391
|
+
continue;
|
|
3392
|
+
}
|
|
3393
|
+
if (!masking) {
|
|
3394
|
+
out += PEM_REDACTION_MARKER;
|
|
3395
|
+
masking = true;
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
return { text: out, quote };
|
|
3399
|
+
}
|
|
3400
|
+
function lineSpanAt(text2, start, end) {
|
|
3401
|
+
let lineStart = start;
|
|
3402
|
+
while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
|
|
3403
|
+
lineStart -= 1;
|
|
3404
|
+
}
|
|
3405
|
+
let lineEnd = end;
|
|
3406
|
+
while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
|
|
3407
|
+
if (lineEnd < text2.length) {
|
|
3408
|
+
lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
|
|
3409
|
+
}
|
|
3410
|
+
return { start: lineStart, end: lineEnd };
|
|
3411
|
+
}
|
|
3412
|
+
function redactPemSpan(text2, matchStart, matchEnd) {
|
|
3413
|
+
const span = lineSpanAt(text2, matchStart, matchEnd);
|
|
3414
|
+
const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
|
|
3415
|
+
let quote = quoteStateAfter(text2, 0, matchStart);
|
|
3416
|
+
let cursor = span.start;
|
|
3417
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3418
|
+
const line = segments[index];
|
|
3419
|
+
const lineStart = cursor;
|
|
3420
|
+
const lineEnd = lineStart + line.length;
|
|
3421
|
+
cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
|
|
3422
|
+
const from = Math.max(lineStart, matchStart);
|
|
3423
|
+
const to = Math.min(lineEnd, matchEnd);
|
|
3424
|
+
if (from >= to) continue;
|
|
3425
|
+
const localFrom = from - lineStart;
|
|
3426
|
+
const localTo = to - lineStart;
|
|
3427
|
+
const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
|
|
3428
|
+
segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
|
|
3429
|
+
quote = result.quote;
|
|
3430
|
+
}
|
|
3431
|
+
return { replacement: segments.join(""), start: span.start, end: span.end };
|
|
3432
|
+
}
|
|
3161
3433
|
var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
|
|
3162
3434
|
function compiledRuleFor(rule) {
|
|
3163
3435
|
let compiled = COMPILED_RULES.get(rule);
|
|
@@ -3172,22 +3444,30 @@ function compiledRuleFor(rule) {
|
|
|
3172
3444
|
return compiled;
|
|
3173
3445
|
}
|
|
3174
3446
|
function scanAndRedactSecrets(content, rules, filePath) {
|
|
3175
|
-
const
|
|
3447
|
+
const findingsByLine = /* @__PURE__ */ new Map();
|
|
3448
|
+
const recordFinding = (line, rulesForLine) => {
|
|
3449
|
+
let entry = findingsByLine.get(line);
|
|
3450
|
+
if (entry === void 0) {
|
|
3451
|
+
entry = /* @__PURE__ */ new Set();
|
|
3452
|
+
findingsByLine.set(line, entry);
|
|
3453
|
+
}
|
|
3454
|
+
for (const rule of rulesForLine) entry.add(rule);
|
|
3455
|
+
};
|
|
3176
3456
|
let redacted = content;
|
|
3177
3457
|
for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
|
|
3178
3458
|
blockPattern.lastIndex = 0;
|
|
3179
3459
|
let match;
|
|
3180
3460
|
while ((match = blockPattern.exec(redacted)) !== null) {
|
|
3181
3461
|
if (match[0].length === 0) {
|
|
3182
|
-
blockPattern.lastIndex
|
|
3462
|
+
blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
|
|
3183
3463
|
continue;
|
|
3184
3464
|
}
|
|
3185
|
-
const
|
|
3186
|
-
const line = (
|
|
3187
|
-
const
|
|
3188
|
-
|
|
3189
|
-
redacted =
|
|
3190
|
-
blockPattern.lastIndex =
|
|
3465
|
+
const matchEnd = match.index + match[0].length;
|
|
3466
|
+
const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
|
|
3467
|
+
const span = redactPemSpan(redacted, match.index, matchEnd);
|
|
3468
|
+
recordFinding(line, ["private-key-block"]);
|
|
3469
|
+
redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
|
|
3470
|
+
blockPattern.lastIndex = span.start + span.replacement.length;
|
|
3191
3471
|
}
|
|
3192
3472
|
}
|
|
3193
3473
|
const compiled = rules.map(compiledRuleFor);
|
|
@@ -3198,17 +3478,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3198
3478
|
if (line.length > 0) {
|
|
3199
3479
|
const spans = [];
|
|
3200
3480
|
const matchedRules = /* @__PURE__ */ new Set();
|
|
3481
|
+
const context = {};
|
|
3201
3482
|
for (const { rule, pattern, valueGroup } of compiled) {
|
|
3202
3483
|
pattern.lastIndex = 0;
|
|
3203
3484
|
let match;
|
|
3204
3485
|
while ((match = pattern.exec(line)) !== null) {
|
|
3205
3486
|
if (match[0].length === 0) {
|
|
3206
|
-
pattern.lastIndex
|
|
3487
|
+
pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
|
|
3207
3488
|
continue;
|
|
3208
3489
|
}
|
|
3209
3490
|
const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
|
|
3491
|
+
const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
|
|
3492
|
+
if (isPlaceholderValue(candidate)) continue;
|
|
3493
|
+
if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
|
|
3494
|
+
continue;
|
|
3495
|
+
}
|
|
3496
|
+
if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
|
|
3497
|
+
continue;
|
|
3498
|
+
}
|
|
3499
|
+
if (rule === "credential-assignment-weak" && group) {
|
|
3500
|
+
let before = match.index - 1;
|
|
3501
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3502
|
+
if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
|
|
3503
|
+
const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
|
|
3504
|
+
if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
|
|
3505
|
+
continue;
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3210
3508
|
if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
|
|
3211
|
-
if (
|
|
3509
|
+
if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
|
|
3510
|
+
continue;
|
|
3511
|
+
}
|
|
3512
|
+
if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
|
|
3212
3513
|
continue;
|
|
3213
3514
|
}
|
|
3214
3515
|
if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
|
|
@@ -3234,7 +3535,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3234
3535
|
if (wholeValue) {
|
|
3235
3536
|
spans.push({
|
|
3236
3537
|
start: group[0],
|
|
3237
|
-
|
|
3538
|
+
// A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
|
|
3539
|
+
// stop at the first one and emit the rest beside the marker. Stop at the end of
|
|
3540
|
+
// the value, a trailing comment, or a shell operator instead. The rule's own end
|
|
3541
|
+
// is not used: the colon form's value pattern includes the spaces before a
|
|
3542
|
+
// trailing `# comment`, and masking them welds the comment to the marker.
|
|
3543
|
+
end: lineValueEnd(line, group[0], context),
|
|
3238
3544
|
rule
|
|
3239
3545
|
});
|
|
3240
3546
|
matchedRules.add(rule);
|
|
@@ -3247,14 +3553,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3247
3553
|
matchedRules.add(rule);
|
|
3248
3554
|
}
|
|
3249
3555
|
}
|
|
3556
|
+
for (const span of concatenatedCredentialSpans(line)) {
|
|
3557
|
+
spans.push(span);
|
|
3558
|
+
matchedRules.add(span.rule);
|
|
3559
|
+
}
|
|
3250
3560
|
if (spans.length > 0) {
|
|
3251
|
-
|
|
3252
|
-
|
|
3561
|
+
const maskedLine = applySpans(line, spans);
|
|
3562
|
+
if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
|
|
3563
|
+
recordFinding(lineNumber, matchedRules);
|
|
3564
|
+
segments[index] = maskedLine;
|
|
3565
|
+
}
|
|
3253
3566
|
}
|
|
3254
3567
|
}
|
|
3255
3568
|
if (index + 1 < segments.length) lineNumber += 1;
|
|
3256
3569
|
}
|
|
3257
|
-
|
|
3570
|
+
let finalText = segments.join("");
|
|
3571
|
+
finalText = redactStructuredValues(finalText, filePath, recordFinding);
|
|
3572
|
+
finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
|
|
3573
|
+
const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
|
|
3574
|
+
rules: [...rulesForLine],
|
|
3575
|
+
line,
|
|
3576
|
+
path: filePath
|
|
3577
|
+
}));
|
|
3578
|
+
return { redacted: finalText, findings };
|
|
3579
|
+
}
|
|
3580
|
+
function advanceStringIndex(text2, index, unicode) {
|
|
3581
|
+
if (!unicode) return index + 1;
|
|
3582
|
+
const first = text2.charCodeAt(index);
|
|
3583
|
+
if (first >= 55296 && first <= 56319) {
|
|
3584
|
+
const second = text2.charCodeAt(index + 1);
|
|
3585
|
+
if (second >= 56320 && second <= 57343) return index + 2;
|
|
3586
|
+
}
|
|
3587
|
+
return index + 1;
|
|
3588
|
+
}
|
|
3589
|
+
var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
|
|
3590
|
+
var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
|
|
3591
|
+
function isStructuredFile(filePath) {
|
|
3592
|
+
if (filePath === void 0) return false;
|
|
3593
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3594
|
+
if (STRUCTURED_FILE.test(normalised)) return true;
|
|
3595
|
+
return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
|
|
3596
|
+
}
|
|
3597
|
+
function isDockerfile(filePath) {
|
|
3598
|
+
if (filePath === void 0) return false;
|
|
3599
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3600
|
+
return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
|
|
3601
|
+
normalised.slice(normalised.lastIndexOf("/") + 1)
|
|
3602
|
+
);
|
|
3603
|
+
}
|
|
3604
|
+
function maskLineContent(line) {
|
|
3605
|
+
if (line.trim() === "") return line;
|
|
3606
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3607
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3608
|
+
}
|
|
3609
|
+
function maskValueLine(line) {
|
|
3610
|
+
if (line.trim() === "") return line;
|
|
3611
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3612
|
+
const content = line.slice(indent.length);
|
|
3613
|
+
const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
|
|
3614
|
+
if (quoted !== null) {
|
|
3615
|
+
return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
|
|
3616
|
+
}
|
|
3617
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3618
|
+
}
|
|
3619
|
+
var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
|
|
3620
|
+
var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
|
|
3621
|
+
function redactStructuredValues(text2, filePath, recordFinding) {
|
|
3622
|
+
if (!isStructuredFile(filePath)) return text2;
|
|
3623
|
+
const segments = text2.split(LINE_BREAK);
|
|
3624
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3625
|
+
const line = segments[index];
|
|
3626
|
+
if (line === void 0 || line.length === 0) continue;
|
|
3627
|
+
const match = STRUCTURED_KEY.exec(line);
|
|
3628
|
+
if (match === null) continue;
|
|
3629
|
+
const key = match[2] ?? "";
|
|
3630
|
+
if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
|
|
3631
|
+
const baseIndent = (match[1] ?? "").length;
|
|
3632
|
+
const rest = (match[4] ?? "").trim();
|
|
3633
|
+
if (BLOCK_SCALAR.test(rest)) {
|
|
3634
|
+
let cursor2 = index + 2;
|
|
3635
|
+
let masked2 = false;
|
|
3636
|
+
while (cursor2 < segments.length) {
|
|
3637
|
+
const body = segments[cursor2] ?? "";
|
|
3638
|
+
if (body.trim() !== "") {
|
|
3639
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3640
|
+
if (indent <= baseIndent) break;
|
|
3641
|
+
segments[cursor2] = maskLineContent(body);
|
|
3642
|
+
masked2 = true;
|
|
3643
|
+
}
|
|
3644
|
+
cursor2 += 2;
|
|
3645
|
+
}
|
|
3646
|
+
if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
|
|
3647
|
+
continue;
|
|
3648
|
+
}
|
|
3649
|
+
if (rest !== "") continue;
|
|
3650
|
+
let cursor = index + 2;
|
|
3651
|
+
while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
|
|
3652
|
+
const firstValue = segments[cursor];
|
|
3653
|
+
if (firstValue === void 0) continue;
|
|
3654
|
+
const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
|
|
3655
|
+
if (valueIndent <= baseIndent) continue;
|
|
3656
|
+
let masked = false;
|
|
3657
|
+
while (cursor < segments.length) {
|
|
3658
|
+
const body = segments[cursor] ?? "";
|
|
3659
|
+
if (body.trim() !== "") {
|
|
3660
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3661
|
+
if (indent < valueIndent) break;
|
|
3662
|
+
segments[cursor] = maskValueLine(body);
|
|
3663
|
+
masked = true;
|
|
3664
|
+
}
|
|
3665
|
+
cursor += 2;
|
|
3666
|
+
}
|
|
3667
|
+
if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
|
|
3668
|
+
}
|
|
3669
|
+
return segments.join("");
|
|
3670
|
+
}
|
|
3671
|
+
var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
|
|
3672
|
+
function redactDockerfileEnv(text2, filePath, recordFinding) {
|
|
3673
|
+
if (!isDockerfile(filePath)) return text2;
|
|
3674
|
+
const segments = text2.split(LINE_BREAK);
|
|
3675
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3676
|
+
const line = segments[index];
|
|
3677
|
+
if (line === void 0) continue;
|
|
3678
|
+
const match = DOCKERFILE_ENV.exec(line);
|
|
3679
|
+
if (match === null) continue;
|
|
3680
|
+
if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
|
|
3681
|
+
const value = match[4] ?? "";
|
|
3682
|
+
if (value.startsWith("=")) continue;
|
|
3683
|
+
segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
|
|
3684
|
+
recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
|
|
3685
|
+
}
|
|
3686
|
+
return segments.join("");
|
|
3687
|
+
}
|
|
3688
|
+
var CONCATENATED_CREDENTIAL = new RegExp(
|
|
3689
|
+
"([A-Za-z0-9_$.-]{0,64}(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token))\\s*=\\s*(?<=[=:]\\s{0,8})([\"'`])\\s*\\+\\s*([\"'`])((?:(?!\\3)[^\\\\\\n]|\\\\.){1,512})\\3",
|
|
3690
|
+
"gid"
|
|
3691
|
+
);
|
|
3692
|
+
function concatenatedCredentialSpans(line) {
|
|
3693
|
+
const spans = [];
|
|
3694
|
+
CONCATENATED_CREDENTIAL.lastIndex = 0;
|
|
3695
|
+
let match;
|
|
3696
|
+
while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
|
|
3697
|
+
const group = match.indices?.[4];
|
|
3698
|
+
if (group !== void 0) {
|
|
3699
|
+
spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
return spans;
|
|
3258
3703
|
}
|
|
3259
3704
|
var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
|
|
3260
3705
|
var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
|
|
@@ -3272,13 +3717,20 @@ function expandOverToken(line, start, end) {
|
|
|
3272
3717
|
while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
|
|
3273
3718
|
return { start: left, end: right };
|
|
3274
3719
|
}
|
|
3275
|
-
function startsInsideStringLiteral(line, matchIndex, valueStart) {
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
if (before !== '"' && before !== "'" && before !== "`") return false;
|
|
3720
|
+
function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
|
|
3721
|
+
const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
|
|
3722
|
+
if (quote === 0) return false;
|
|
3723
|
+
if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
|
|
3280
3724
|
if (valueStart === void 0) return true;
|
|
3281
|
-
|
|
3725
|
+
for (let index = matchIndex; index < valueStart; index += 1) {
|
|
3726
|
+
const code = line.charCodeAt(index);
|
|
3727
|
+
if (code === 92) {
|
|
3728
|
+
index += 1;
|
|
3729
|
+
} else if (code === quote) {
|
|
3730
|
+
return true;
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
return false;
|
|
3282
3734
|
}
|
|
3283
3735
|
function isTemplateInterpolation(line, start, end) {
|
|
3284
3736
|
if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
|
|
@@ -3306,6 +3758,40 @@ function isSelfNamingConstant(line, start, end) {
|
|
|
3306
3758
|
}
|
|
3307
3759
|
return line.endsWith(value, index);
|
|
3308
3760
|
}
|
|
3761
|
+
var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
|
|
3762
|
+
function isSourceCodeFile(filePath) {
|
|
3763
|
+
return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
|
|
3764
|
+
}
|
|
3765
|
+
var PLACEHOLDER_PATTERNS = [
|
|
3766
|
+
/^<[^>]*>?$/,
|
|
3767
|
+
/^\.{3,}$/,
|
|
3768
|
+
/^(?:x{4,}|X{4,}|\*{3,})$/,
|
|
3769
|
+
/^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
|
|
3770
|
+
/^your[-_ ].*$/i,
|
|
3771
|
+
/^(?:example|sample)(?:[-_ ].*)?$/i
|
|
3772
|
+
];
|
|
3773
|
+
function isPlaceholderValue(value) {
|
|
3774
|
+
const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
|
|
3775
|
+
if (trimmed.length === 0) return false;
|
|
3776
|
+
if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
|
|
3777
|
+
return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
|
|
3778
|
+
}
|
|
3779
|
+
function quotesAreBalanced(text2) {
|
|
3780
|
+
let single = 0;
|
|
3781
|
+
let double = 0;
|
|
3782
|
+
let backtick = 0;
|
|
3783
|
+
for (let index = 0; index < text2.length; index += 1) {
|
|
3784
|
+
const char = text2[index];
|
|
3785
|
+
if (char === "\\") {
|
|
3786
|
+
index += 1;
|
|
3787
|
+
continue;
|
|
3788
|
+
}
|
|
3789
|
+
if (char === '"') double += 1;
|
|
3790
|
+
else if (char === "'") single += 1;
|
|
3791
|
+
else if (char === "`") backtick += 1;
|
|
3792
|
+
}
|
|
3793
|
+
return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
|
|
3794
|
+
}
|
|
3309
3795
|
function assignmentAround(line, valueStart) {
|
|
3310
3796
|
let index = valueStart;
|
|
3311
3797
|
while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
|
|
@@ -3375,6 +3861,16 @@ function applySpans(line, spans) {
|
|
|
3375
3861
|
return out;
|
|
3376
3862
|
}
|
|
3377
3863
|
|
|
3864
|
+
// src/version.ts
|
|
3865
|
+
var GENERATOR_NAME = "codebase-snapshot";
|
|
3866
|
+
var GENERATOR_VERSION = "0.9.18";
|
|
3867
|
+
var SCHEMA_VERSION = "3.0.0";
|
|
3868
|
+
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
3869
|
+
function isOurGeneratorName(name) {
|
|
3870
|
+
if (typeof name !== "string") return false;
|
|
3871
|
+
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
3872
|
+
}
|
|
3873
|
+
|
|
3378
3874
|
// src/scanner/files.ts
|
|
3379
3875
|
function isDiscoveryMode(value) {
|
|
3380
3876
|
return value === "auto" || value === "git" || value === "walk";
|
|
@@ -3384,7 +3880,7 @@ var PRESET_IGNORES = new Set(
|
|
|
3384
3880
|
);
|
|
3385
3881
|
function readLinkTarget(linkPath, fallback) {
|
|
3386
3882
|
try {
|
|
3387
|
-
return
|
|
3883
|
+
return fs15.readlinkSync(linkPath);
|
|
3388
3884
|
} catch {
|
|
3389
3885
|
return fallback;
|
|
3390
3886
|
}
|
|
@@ -3399,8 +3895,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
|
|
|
3399
3895
|
};
|
|
3400
3896
|
}
|
|
3401
3897
|
function isInside(root, candidate) {
|
|
3402
|
-
const
|
|
3403
|
-
return
|
|
3898
|
+
const relative10 = path16.relative(root, candidate);
|
|
3899
|
+
return relative10 === "" || !relative10.startsWith(`..${path16.sep}`) && relative10 !== ".." && !path16.isAbsolute(relative10);
|
|
3404
3900
|
}
|
|
3405
3901
|
var GIT_OUTPUT_LIMIT = 68157440;
|
|
3406
3902
|
function getGitInfo(cwd, fallbackBranch = "main") {
|
|
@@ -3461,10 +3957,10 @@ var DEFAULT_IGNORED_FILES = [
|
|
|
3461
3957
|
"bun.lockb",
|
|
3462
3958
|
"composer.lock"
|
|
3463
3959
|
];
|
|
3464
|
-
var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.vault-token|vault[-_]agent[-_]token|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
|
|
3465
|
-
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
|
|
3960
|
+
var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
|
|
3961
|
+
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
|
|
3466
3962
|
var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
|
|
3467
|
-
var TEMPLATE_SUFFIX =
|
|
3963
|
+
var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
|
|
3468
3964
|
var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
|
|
3469
3965
|
function normaliseName(name) {
|
|
3470
3966
|
let normalised = name.trim().replace(/[. ]+$/, "");
|
|
@@ -3480,12 +3976,16 @@ function isSensitivePath(relativePath) {
|
|
|
3480
3976
|
const posixPath = relativePath.replace(/\\/g, "/");
|
|
3481
3977
|
const raw = posixPath.split("/").pop() ?? posixPath;
|
|
3482
3978
|
const base = normaliseName(raw);
|
|
3483
|
-
if (
|
|
3484
|
-
const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
|
|
3485
|
-
if (matchesSensitiveList(posixPath, stripped)) return false;
|
|
3486
|
-
}
|
|
3979
|
+
if (templateOfCredentialFile(posixPath, base)) return false;
|
|
3487
3980
|
return matchesSensitiveList(posixPath, base);
|
|
3488
3981
|
}
|
|
3982
|
+
function templateOfCredentialFile(posixPath, base) {
|
|
3983
|
+
const match = TEMPLATE_SUFFIX.exec(base);
|
|
3984
|
+
if (match === null) return null;
|
|
3985
|
+
const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
|
|
3986
|
+
if (SENSITIVE_EXT.test(stripped)) return null;
|
|
3987
|
+
return matchesSensitiveList(posixPath, stripped) ? stripped : null;
|
|
3988
|
+
}
|
|
3489
3989
|
var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
|
|
3490
3990
|
var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
3491
3991
|
var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
@@ -3517,7 +4017,7 @@ function findSecretInPath(relativePath, extraRules) {
|
|
|
3517
4017
|
let match;
|
|
3518
4018
|
while ((match = scan.exec(posixPath)) !== null) {
|
|
3519
4019
|
if (match[0].length === 0) {
|
|
3520
|
-
scan.lastIndex
|
|
4020
|
+
scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
|
|
3521
4021
|
continue;
|
|
3522
4022
|
}
|
|
3523
4023
|
spans.push({ start: match.index, end: match.index + match[0].length });
|
|
@@ -3578,11 +4078,14 @@ function globBodyToRegExp(body, allowBraces) {
|
|
|
3578
4078
|
if (char === "*") {
|
|
3579
4079
|
if (body[i + 1] === "*") {
|
|
3580
4080
|
i += 1;
|
|
3581
|
-
|
|
4081
|
+
const startsSegment = i - 2 < 0 || body[i - 2] === "/";
|
|
4082
|
+
if (startsSegment && body[i + 1] === "/") {
|
|
3582
4083
|
i += 1;
|
|
3583
|
-
out += "(
|
|
3584
|
-
} else {
|
|
4084
|
+
out += "(?:[^/]+/)*";
|
|
4085
|
+
} else if (startsSegment && i + 1 === body.length) {
|
|
3585
4086
|
out += ".*";
|
|
4087
|
+
} else {
|
|
4088
|
+
out += "[^/]*";
|
|
3586
4089
|
}
|
|
3587
4090
|
} else {
|
|
3588
4091
|
out += "[^/]*";
|
|
@@ -3654,7 +4157,7 @@ function readGitignoreRules(dir) {
|
|
|
3654
4157
|
const gitignorePath2 = path16.join(dir, ".gitignore");
|
|
3655
4158
|
let raw;
|
|
3656
4159
|
try {
|
|
3657
|
-
raw =
|
|
4160
|
+
raw = fs15.readFileSync(gitignorePath2, "utf8");
|
|
3658
4161
|
} catch {
|
|
3659
4162
|
return [];
|
|
3660
4163
|
}
|
|
@@ -3827,10 +4330,49 @@ function listIgnoredPaths(cwd) {
|
|
|
3827
4330
|
}
|
|
3828
4331
|
function hasSnapshotMarker(target) {
|
|
3829
4332
|
try {
|
|
3830
|
-
return
|
|
4333
|
+
return fs15.statSync(target).isDirectory() && fs15.existsSync(path16.join(target, ".codebase-snapshot"));
|
|
4334
|
+
} catch {
|
|
4335
|
+
return false;
|
|
4336
|
+
}
|
|
4337
|
+
}
|
|
4338
|
+
var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
|
|
4339
|
+
function isToolOwnedDirectory2(dir) {
|
|
4340
|
+
let raw;
|
|
4341
|
+
try {
|
|
4342
|
+
raw = fs15.readFileSync(path16.join(dir, ".codebase-snapshot"), "utf8");
|
|
4343
|
+
} catch {
|
|
4344
|
+
return false;
|
|
4345
|
+
}
|
|
4346
|
+
let parsed;
|
|
4347
|
+
try {
|
|
4348
|
+
parsed = JSON.parse(raw);
|
|
4349
|
+
} catch {
|
|
4350
|
+
return false;
|
|
4351
|
+
}
|
|
4352
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
4353
|
+
const marker2 = parsed;
|
|
4354
|
+
if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
|
|
4355
|
+
return false;
|
|
4356
|
+
}
|
|
4357
|
+
const accounted = /* @__PURE__ */ new Set();
|
|
4358
|
+
for (const item of marker2.files) {
|
|
4359
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
|
|
4360
|
+
const entry = item.path;
|
|
4361
|
+
if (typeof entry !== "string" || entry.length === 0) return false;
|
|
4362
|
+
const parts = entry.split("/");
|
|
4363
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
4364
|
+
accounted.add(parts.slice(0, depth).join("/"));
|
|
4365
|
+
}
|
|
4366
|
+
}
|
|
4367
|
+
let entries;
|
|
4368
|
+
try {
|
|
4369
|
+
entries = fs15.readdirSync(dir);
|
|
3831
4370
|
} catch {
|
|
3832
4371
|
return false;
|
|
3833
4372
|
}
|
|
4373
|
+
return entries.every(
|
|
4374
|
+
(entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
|
|
4375
|
+
);
|
|
3834
4376
|
}
|
|
3835
4377
|
function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
3836
4378
|
const markers = /* @__PURE__ */ new Map();
|
|
@@ -3841,7 +4383,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
|
3841
4383
|
const prefix = parts.slice(0, depth).join("/");
|
|
3842
4384
|
let hasMarker = markers.get(prefix);
|
|
3843
4385
|
if (hasMarker === void 0) {
|
|
3844
|
-
hasMarker =
|
|
4386
|
+
hasMarker = isToolOwnedDirectory2(path16.join(cwd, prefix));
|
|
3845
4387
|
markers.set(prefix, hasMarker);
|
|
3846
4388
|
}
|
|
3847
4389
|
if (hasMarker) return true;
|
|
@@ -3856,7 +4398,7 @@ function makeLinkProbe() {
|
|
|
3856
4398
|
let known = cache.get(absolutePath);
|
|
3857
4399
|
if (known === void 0) {
|
|
3858
4400
|
try {
|
|
3859
|
-
known =
|
|
4401
|
+
known = fs15.lstatSync(absolutePath).isSymbolicLink();
|
|
3860
4402
|
} catch {
|
|
3861
4403
|
known = false;
|
|
3862
4404
|
}
|
|
@@ -3869,7 +4411,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3869
4411
|
const isLink = makeLinkProbe();
|
|
3870
4412
|
let rootReal = cwd;
|
|
3871
4413
|
try {
|
|
3872
|
-
rootReal =
|
|
4414
|
+
rootReal = fs15.realpathSync(cwd);
|
|
3873
4415
|
} catch {
|
|
3874
4416
|
}
|
|
3875
4417
|
const reported = /* @__PURE__ */ new Set();
|
|
@@ -3897,7 +4439,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3897
4439
|
const rawTarget = readLinkTarget(absolute, absolute);
|
|
3898
4440
|
let targetReal = null;
|
|
3899
4441
|
try {
|
|
3900
|
-
targetReal =
|
|
4442
|
+
targetReal = fs15.realpathSync(absolute);
|
|
3901
4443
|
} catch {
|
|
3902
4444
|
targetReal = null;
|
|
3903
4445
|
}
|
|
@@ -3915,7 +4457,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3915
4457
|
}
|
|
3916
4458
|
let stats = null;
|
|
3917
4459
|
try {
|
|
3918
|
-
stats =
|
|
4460
|
+
stats = fs15.statSync(absolute);
|
|
3919
4461
|
} catch {
|
|
3920
4462
|
stats = null;
|
|
3921
4463
|
}
|
|
@@ -4003,7 +4545,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4003
4545
|
"Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
|
|
4004
4546
|
);
|
|
4005
4547
|
}
|
|
4006
|
-
if (
|
|
4548
|
+
if (fs15.existsSync(path16.join(cwd, ".git"))) {
|
|
4007
4549
|
throw new Error(
|
|
4008
4550
|
"This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
|
|
4009
4551
|
);
|
|
@@ -4013,6 +4555,15 @@ function collectFiles(cwd, options = {}) {
|
|
|
4013
4555
|
for (const record of walked.skipped) skipped.push(record);
|
|
4014
4556
|
}
|
|
4015
4557
|
}
|
|
4558
|
+
const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
|
|
4559
|
+
if (extraPaths.length > 0) {
|
|
4560
|
+
const known = new Set(candidates);
|
|
4561
|
+
for (const extra of extraPaths) {
|
|
4562
|
+
if (extra.length === 0 || known.has(extra)) continue;
|
|
4563
|
+
known.add(extra);
|
|
4564
|
+
candidates.push(extra);
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4016
4567
|
const files = candidates.filter((file) => {
|
|
4017
4568
|
if (isToolOwned(file)) return false;
|
|
4018
4569
|
const ignored = defaultIgnoreReason(file, toolDirNames);
|
|
@@ -4062,7 +4613,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4062
4613
|
}
|
|
4063
4614
|
function rootRealFor(root) {
|
|
4064
4615
|
try {
|
|
4065
|
-
return
|
|
4616
|
+
return fs15.realpathSync(root);
|
|
4066
4617
|
} catch {
|
|
4067
4618
|
return root;
|
|
4068
4619
|
}
|
|
@@ -4082,7 +4633,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4082
4633
|
];
|
|
4083
4634
|
let entries;
|
|
4084
4635
|
try {
|
|
4085
|
-
entries =
|
|
4636
|
+
entries = fs15.readdirSync(current, { withFileTypes: true });
|
|
4086
4637
|
} catch {
|
|
4087
4638
|
results.skipped.push({
|
|
4088
4639
|
path: relativeToBase(current),
|
|
@@ -4138,14 +4689,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4138
4689
|
if (entry.isSymbolicLink()) {
|
|
4139
4690
|
let targetReal;
|
|
4140
4691
|
try {
|
|
4141
|
-
targetReal =
|
|
4692
|
+
targetReal = fs15.realpathSync(fullPath);
|
|
4142
4693
|
} catch {
|
|
4143
4694
|
results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
|
|
4144
4695
|
continue;
|
|
4145
4696
|
}
|
|
4146
4697
|
let stats;
|
|
4147
4698
|
try {
|
|
4148
|
-
stats =
|
|
4699
|
+
stats = fs15.statSync(fullPath);
|
|
4149
4700
|
} catch {
|
|
4150
4701
|
results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
|
|
4151
4702
|
continue;
|
|
@@ -4175,6 +4726,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4175
4726
|
});
|
|
4176
4727
|
continue;
|
|
4177
4728
|
}
|
|
4729
|
+
const targetRelative = path16.relative(rootReal, targetReal).split(path16.sep).join("/");
|
|
4730
|
+
if (isSensitivePath(targetRelative)) {
|
|
4731
|
+
results.skipped.push({
|
|
4732
|
+
path: relPath,
|
|
4733
|
+
reason: "sensitive-file",
|
|
4734
|
+
detail: "link target is a credential-bearing file; not followed"
|
|
4735
|
+
});
|
|
4736
|
+
continue;
|
|
4737
|
+
}
|
|
4178
4738
|
isDirectory = false;
|
|
4179
4739
|
isFile = true;
|
|
4180
4740
|
}
|
|
@@ -4223,12 +4783,19 @@ var CONFIG_FILENAMES = [
|
|
|
4223
4783
|
function findConfigFile(cwd) {
|
|
4224
4784
|
for (const filename of CONFIG_FILENAMES) {
|
|
4225
4785
|
const fullPath = path16.join(cwd, filename);
|
|
4226
|
-
|
|
4786
|
+
let stats = null;
|
|
4787
|
+
try {
|
|
4788
|
+
stats = fs15.statSync(fullPath);
|
|
4789
|
+
} catch {
|
|
4790
|
+
if (fs15.existsSync(fullPath)) return fullPath;
|
|
4791
|
+
continue;
|
|
4792
|
+
}
|
|
4793
|
+
if (stats.isFile()) return fullPath;
|
|
4227
4794
|
}
|
|
4228
4795
|
const pkgJsonPath = path16.join(cwd, "package.json");
|
|
4229
|
-
if (!
|
|
4796
|
+
if (!fs15.existsSync(pkgJsonPath)) return null;
|
|
4230
4797
|
try {
|
|
4231
|
-
const parsed = JSON.parse(stripJsonComments2(
|
|
4798
|
+
const parsed = JSON.parse(stripJsonComments2(fs15.readFileSync(pkgJsonPath, "utf8")));
|
|
4232
4799
|
const snapshot = parsed?.snapshot;
|
|
4233
4800
|
return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
|
|
4234
4801
|
} catch {
|
|
@@ -4489,17 +5056,34 @@ function readConfigExport(exported, file) {
|
|
|
4489
5056
|
assertKnownConfigKeys(exported, file);
|
|
4490
5057
|
return exported;
|
|
4491
5058
|
}
|
|
4492
|
-
var
|
|
5059
|
+
var lastModuleConfig = null;
|
|
5060
|
+
function moduleConfigKey(fullPath) {
|
|
5061
|
+
try {
|
|
5062
|
+
return createHash("sha256").update(fs15.readFileSync(fullPath)).digest("hex").slice(0, 24);
|
|
5063
|
+
} catch {
|
|
5064
|
+
try {
|
|
5065
|
+
const stats = fs15.statSync(fullPath);
|
|
5066
|
+
return `stat-${stats.mtimeMs}-${stats.size}`;
|
|
5067
|
+
} catch {
|
|
5068
|
+
return "unreadable";
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
}
|
|
4493
5072
|
async function importConfigModule(fullPath) {
|
|
5073
|
+
const key = moduleConfigKey(fullPath);
|
|
5074
|
+
if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
|
|
5075
|
+
return lastModuleConfig.exports;
|
|
5076
|
+
}
|
|
4494
5077
|
try {
|
|
4495
5078
|
const requireFromConfig = createRequire(fullPath);
|
|
4496
5079
|
delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
|
|
4497
5080
|
} catch {
|
|
4498
5081
|
}
|
|
4499
5082
|
const url = pathToFileURL(fullPath);
|
|
4500
|
-
|
|
4501
|
-
url.
|
|
4502
|
-
|
|
5083
|
+
url.searchParams.set("codebaseSnapshotLoad", key);
|
|
5084
|
+
const loaded = await import(url.href);
|
|
5085
|
+
lastModuleConfig = { path: fullPath, key, exports: loaded };
|
|
5086
|
+
return loaded;
|
|
4503
5087
|
}
|
|
4504
5088
|
function attachConfigDir(config, filePath) {
|
|
4505
5089
|
if (typeof config === "object" && config !== null) {
|
|
@@ -4511,15 +5095,25 @@ function attachConfigDir(config, filePath) {
|
|
|
4511
5095
|
}
|
|
4512
5096
|
return config;
|
|
4513
5097
|
}
|
|
4514
|
-
async function loadConfigFileDetailed(cwd) {
|
|
5098
|
+
async function loadConfigFileDetailed(cwd, options = {}) {
|
|
4515
5099
|
const warnings = [];
|
|
4516
5100
|
const errors = [];
|
|
5101
|
+
const configDirectories = [];
|
|
4517
5102
|
for (const filename of CONFIG_FILENAMES) {
|
|
4518
5103
|
const fullPath = path16.join(cwd, filename);
|
|
4519
|
-
|
|
5104
|
+
let candidateStats = null;
|
|
5105
|
+
try {
|
|
5106
|
+
candidateStats = fs15.statSync(fullPath);
|
|
5107
|
+
} catch {
|
|
5108
|
+
if (!fs15.existsSync(fullPath)) continue;
|
|
5109
|
+
}
|
|
5110
|
+
if (candidateStats !== null && !candidateStats.isFile()) {
|
|
5111
|
+
configDirectories.push(fullPath);
|
|
5112
|
+
continue;
|
|
5113
|
+
}
|
|
4520
5114
|
if (filename.endsWith(".json") || filename === ".snapshotrc") {
|
|
4521
5115
|
try {
|
|
4522
|
-
const config = parseJsonish(
|
|
5116
|
+
const config = parseJsonish(fs15.readFileSync(fullPath, "utf8"), fullPath);
|
|
4523
5117
|
if (config === null || typeof config !== "object" || Array.isArray(config)) {
|
|
4524
5118
|
throw new Error(
|
|
4525
5119
|
`${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
|
|
@@ -4535,6 +5129,12 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4535
5129
|
continue;
|
|
4536
5130
|
}
|
|
4537
5131
|
}
|
|
5132
|
+
if (options.allowExecutableConfig === false) {
|
|
5133
|
+
const message = `${fullPath} was not loaded: it is an executable config, and this server does not run repository code. Export the same settings from snapshot.config.json instead.`;
|
|
5134
|
+
warnings.push(message);
|
|
5135
|
+
errors.push(message);
|
|
5136
|
+
continue;
|
|
5137
|
+
}
|
|
4538
5138
|
if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
|
|
4539
5139
|
warnings.push(
|
|
4540
5140
|
`${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
|
|
@@ -4554,9 +5154,9 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4554
5154
|
}
|
|
4555
5155
|
}
|
|
4556
5156
|
const pkgJsonPath = path16.join(cwd, "package.json");
|
|
4557
|
-
if (
|
|
5157
|
+
if (fs15.existsSync(pkgJsonPath)) {
|
|
4558
5158
|
try {
|
|
4559
|
-
const parsed = parseJsonish(
|
|
5159
|
+
const parsed = parseJsonish(fs15.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
|
|
4560
5160
|
const snapshotKey = parsed.snapshot;
|
|
4561
5161
|
if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
|
|
4562
5162
|
assertKnownConfigKeys(
|
|
@@ -4582,6 +5182,11 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4582
5182
|
errors.push(message);
|
|
4583
5183
|
}
|
|
4584
5184
|
}
|
|
5185
|
+
if (configDirectories.length > 0) {
|
|
5186
|
+
warnings.push(
|
|
5187
|
+
`${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
|
|
5188
|
+
);
|
|
5189
|
+
}
|
|
4585
5190
|
return { config: null, file: null, warnings, errors };
|
|
4586
5191
|
}
|
|
4587
5192
|
async function loadConfigFile(cwd) {
|
|
@@ -4757,11 +5362,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
|
|
|
4757
5362
|
const patterns = [];
|
|
4758
5363
|
for (const dir of [outDir, tmpDir]) {
|
|
4759
5364
|
const absolute = path16.resolve(cwd, dir);
|
|
4760
|
-
const
|
|
4761
|
-
if (!
|
|
5365
|
+
const relative10 = path16.relative(cwd, absolute);
|
|
5366
|
+
if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
|
|
4762
5367
|
continue;
|
|
4763
5368
|
}
|
|
4764
|
-
patterns.push(`${
|
|
5369
|
+
patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
|
|
4765
5370
|
}
|
|
4766
5371
|
return patterns;
|
|
4767
5372
|
}
|
|
@@ -4892,10 +5497,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
|
|
|
4892
5497
|
}
|
|
4893
5498
|
const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
|
|
4894
5499
|
const resolved = path16.resolve(candidate);
|
|
4895
|
-
if (!
|
|
5500
|
+
if (!fs15.existsSync(resolved)) {
|
|
4896
5501
|
throw new Error(`Working directory does not exist: ${resolved}`);
|
|
4897
5502
|
}
|
|
4898
|
-
if (!
|
|
5503
|
+
if (!fs15.statSync(resolved).isDirectory()) {
|
|
4899
5504
|
throw new Error(`Working directory is not a directory: ${resolved}`);
|
|
4900
5505
|
}
|
|
4901
5506
|
return resolved;
|
|
@@ -5145,6 +5750,13 @@ function configDigest(config) {
|
|
|
5145
5750
|
// moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
|
|
5146
5751
|
// digest, so `validate` reported "valid and up to date" for a snapshot whose files
|
|
5147
5752
|
// had all been reclassified — and per-layer budgets applied to different files.
|
|
5753
|
+
// A function matcher's `String()` is its source, not its closure: two functions with the same
|
|
5754
|
+
// body but different captured values digest identically. That cannot be fixed by hashing, so
|
|
5755
|
+
// the digest records that executable matchers are present and `validate` says the digest does
|
|
5756
|
+
// not cover their closure, instead of claiming a equality it cannot prove.
|
|
5757
|
+
executableMatchers: [...config.layers, ...config.kinds].some(
|
|
5758
|
+
(rule) => typeof rule.match === "function"
|
|
5759
|
+
),
|
|
5148
5760
|
layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
|
|
5149
5761
|
kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
|
|
5150
5762
|
// How files are enumerated decides what is in the snapshot at all.
|
|
@@ -5201,8 +5813,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5201
5813
|
`**Generated:** ${manifest.generatedAt} `,
|
|
5202
5814
|
`**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
|
|
5203
5815
|
`**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
|
|
5204
|
-
`**
|
|
5205
|
-
`**
|
|
5816
|
+
`**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
|
|
5817
|
+
`**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
|
|
5818
|
+
`**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
|
|
5206
5819
|
// This counts the bytes that were *emitted* after redaction, not the bytes
|
|
5207
5820
|
// that were masked: calling it "redacted bytes" made a repository with zero
|
|
5208
5821
|
// secrets report a non-zero redacted-byte figure directly above "no secrets
|
|
@@ -5242,9 +5855,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5242
5855
|
const parseIssues = manifest.files.filter(
|
|
5243
5856
|
(file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
|
|
5244
5857
|
);
|
|
5858
|
+
const unparsedPreviews = manifest.files.filter(
|
|
5859
|
+
(file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
|
|
5860
|
+
).length;
|
|
5245
5861
|
lines.push("## 2. Parse & AST Diagnostics", "");
|
|
5246
5862
|
if (parseIssues.length === 0) {
|
|
5247
|
-
|
|
5863
|
+
if (unparsedPreviews > 0) {
|
|
5864
|
+
lines.push(
|
|
5865
|
+
`\u2705 No parse errors among the files that were parsed; ${formatNumber(unparsedPreviews)} file(s) were previewed or too large to parse and produced no structural summary.`,
|
|
5866
|
+
""
|
|
5867
|
+
);
|
|
5868
|
+
} else {
|
|
5869
|
+
lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
|
|
5870
|
+
}
|
|
5248
5871
|
} else {
|
|
5249
5872
|
lines.push(
|
|
5250
5873
|
`${parseIssues.length} file(s) produced an incomplete summary:`,
|
|
@@ -5444,9 +6067,9 @@ function truncateToBytes(content, maxBytes) {
|
|
|
5444
6067
|
if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
|
|
5445
6068
|
const buffer = Buffer.from(content, "utf8");
|
|
5446
6069
|
if (buffer.length <= maxBytes) return { content, isTruncated: false };
|
|
5447
|
-
let
|
|
5448
|
-
while (
|
|
5449
|
-
return { content:
|
|
6070
|
+
let end = maxBytes;
|
|
6071
|
+
while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
|
|
6072
|
+
return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
|
|
5450
6073
|
}
|
|
5451
6074
|
function truncatePreview(content, headLines, tailLines) {
|
|
5452
6075
|
const normalised = normaliseLineEndings(content);
|
|
@@ -5529,19 +6152,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5529
6152
|
for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
|
|
5530
6153
|
}
|
|
5531
6154
|
if (groups.length === 0) return [];
|
|
5532
|
-
const
|
|
6155
|
+
const assemblies = /* @__PURE__ */ new Map();
|
|
5533
6156
|
const widthOf = (total) => Math.max(3, String(total).length);
|
|
5534
|
-
const
|
|
5535
|
-
const cached = measurements.get(group);
|
|
6157
|
+
const assemble = (group, index, total) => {
|
|
5536
6158
|
const width = widthOf(total);
|
|
6159
|
+
const cached = assemblies.get(group);
|
|
5537
6160
|
if (cached !== void 0 && cached.index === index && cached.width === width) {
|
|
5538
|
-
return cached.
|
|
6161
|
+
return cached.value;
|
|
5539
6162
|
}
|
|
5540
|
-
const
|
|
5541
|
-
|
|
5542
|
-
|
|
5543
|
-
return size2;
|
|
6163
|
+
const value = assembleGroup(group, index, total, contentFingerprint);
|
|
6164
|
+
assemblies.set(group, { index, width, value });
|
|
6165
|
+
return value;
|
|
5544
6166
|
};
|
|
6167
|
+
const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
|
|
5545
6168
|
for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
|
|
5546
6169
|
const total = groups.length;
|
|
5547
6170
|
let oversized = -1;
|
|
@@ -5552,16 +6175,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5552
6175
|
break;
|
|
5553
6176
|
}
|
|
5554
6177
|
}
|
|
5555
|
-
if (oversized === -1) return renderGroups(groups, contentFingerprint);
|
|
6178
|
+
if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
|
|
5556
6179
|
const group = groups[oversized];
|
|
5557
6180
|
if (group.sections.length > 1) {
|
|
5558
6181
|
const moved = group.sections.pop();
|
|
5559
6182
|
groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
|
|
5560
|
-
|
|
6183
|
+
assemblies.delete(group);
|
|
5561
6184
|
continue;
|
|
5562
6185
|
}
|
|
5563
6186
|
const [section] = group.sections;
|
|
5564
|
-
if (section === void 0) return renderGroups(groups, contentFingerprint);
|
|
6187
|
+
if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
|
|
5565
6188
|
const overflow = measure(group, oversized, total) - group.budget;
|
|
5566
6189
|
const currentContent = section.file.content ?? "";
|
|
5567
6190
|
const shrinkTo = Math.max(
|
|
@@ -5578,10 +6201,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5578
6201
|
applyTruncatedContent(section.file, shrunk.content);
|
|
5579
6202
|
section.text = renderFileSection(section.file);
|
|
5580
6203
|
section.byteSize = Buffer.byteLength(section.text, "utf8");
|
|
5581
|
-
|
|
6204
|
+
assemblies.delete(group);
|
|
5582
6205
|
continue;
|
|
5583
6206
|
}
|
|
5584
|
-
const rendered = renderGroups(groups, contentFingerprint);
|
|
6207
|
+
const rendered = renderGroups(groups, contentFingerprint, assemble);
|
|
5585
6208
|
const marker2 = TRUNCATION_MARKER;
|
|
5586
6209
|
assertBudgetHoldsMarker(group.budget);
|
|
5587
6210
|
const target = Math.max(
|
|
@@ -5595,7 +6218,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5595
6218
|
);
|
|
5596
6219
|
return rendered;
|
|
5597
6220
|
}
|
|
5598
|
-
return renderGroups(groups, contentFingerprint).flatMap(
|
|
6221
|
+
return renderGroups(groups, contentFingerprint, assemble).flatMap(
|
|
5599
6222
|
(part) => enforceBudget([part], part.metadata.budgetBytes)
|
|
5600
6223
|
);
|
|
5601
6224
|
}
|
|
@@ -5633,8 +6256,8 @@ function renumberParts(parts, contentFingerprint) {
|
|
|
5633
6256
|
if (markerIndex === -1) {
|
|
5634
6257
|
throw new Error(`${part.filename} has no "## Contents" section to re-number.`);
|
|
5635
6258
|
}
|
|
5636
|
-
const layerCounts =
|
|
5637
|
-
const kindCounts =
|
|
6259
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6260
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5638
6261
|
for (const file of included) {
|
|
5639
6262
|
layerCounts[file.layer] = (layerCounts[file.layer] || 0) + 1;
|
|
5640
6263
|
kindCounts[file.kind] = (kindCounts[file.kind] || 0) + 1;
|
|
@@ -5831,8 +6454,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5831
6454
|
for (const section of group.sections) {
|
|
5832
6455
|
section.file.part = filename;
|
|
5833
6456
|
}
|
|
5834
|
-
const layerCounts =
|
|
5835
|
-
const kindCounts =
|
|
6457
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6458
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5836
6459
|
for (const section of group.sections) {
|
|
5837
6460
|
layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
|
|
5838
6461
|
kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
|
|
@@ -5867,15 +6490,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5867
6490
|
const estimatedTokens = estimateTokens(assembled);
|
|
5868
6491
|
return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
|
|
5869
6492
|
}
|
|
5870
|
-
function renderGroups(groups, contentFingerprint) {
|
|
6493
|
+
function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
|
|
5871
6494
|
const total = groups.length;
|
|
5872
6495
|
return groups.map((group, index) => {
|
|
5873
|
-
const { filename, content, estimatedTokens } =
|
|
5874
|
-
group,
|
|
5875
|
-
index,
|
|
5876
|
-
total,
|
|
5877
|
-
contentFingerprint
|
|
5878
|
-
);
|
|
6496
|
+
const { filename, content, estimatedTokens } = assemble(group, index, total);
|
|
5879
6497
|
const byteSize = Buffer.byteLength(content, "utf8");
|
|
5880
6498
|
const sha256 = crypto2.createHash("sha256").update(content).digest("hex");
|
|
5881
6499
|
const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
|
|
@@ -6092,9 +6710,10 @@ function generateReadme(manifest, artifacts) {
|
|
|
6092
6710
|
`- **Schema Version:** \`${manifest.schemaVersion}\``,
|
|
6093
6711
|
`- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
|
|
6094
6712
|
`- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
|
|
6095
|
-
`- **
|
|
6096
|
-
`- **
|
|
6097
|
-
`- **
|
|
6713
|
+
`- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
|
|
6714
|
+
`- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
|
|
6715
|
+
`- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6716
|
+
`- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6098
6717
|
`- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
|
|
6099
6718
|
`- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
|
|
6100
6719
|
"",
|
|
@@ -6226,7 +6845,18 @@ function gitPaths(cwd, args) {
|
|
|
6226
6845
|
`Could not list changed files (git ${args.join(" ")}): ${reason}. A changed-files snapshot needs a git working tree and a ref that exists; run \`codebase-snapshot generate\` without --changed-since to scan everything.`
|
|
6227
6846
|
);
|
|
6228
6847
|
}
|
|
6229
|
-
return output.split("\0").
|
|
6848
|
+
return output.split("\0").filter((entry) => entry.length > 0);
|
|
6849
|
+
}
|
|
6850
|
+
function readStagedBlob(cwd, relativePath) {
|
|
6851
|
+
try {
|
|
6852
|
+
return execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
|
|
6853
|
+
cwd,
|
|
6854
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
6855
|
+
maxBuffer: 512 * 1024 * 1024
|
|
6856
|
+
});
|
|
6857
|
+
} catch {
|
|
6858
|
+
return null;
|
|
6859
|
+
}
|
|
6230
6860
|
}
|
|
6231
6861
|
function assertUsableRef(ref) {
|
|
6232
6862
|
if (ref.startsWith("-")) {
|
|
@@ -6237,6 +6867,8 @@ function assertUsableRef(ref) {
|
|
|
6237
6867
|
}
|
|
6238
6868
|
function resolveChangedScope(cwd, request) {
|
|
6239
6869
|
const paths = /* @__PURE__ */ new Set();
|
|
6870
|
+
const stagedPaths = /* @__PURE__ */ new Set();
|
|
6871
|
+
const deletedPaths = /* @__PURE__ */ new Set();
|
|
6240
6872
|
const descriptions = [];
|
|
6241
6873
|
if (request.changedSince !== void 0) {
|
|
6242
6874
|
assertUsableRef(request.changedSince);
|
|
@@ -6245,7 +6877,17 @@ function resolveChangedScope(cwd, request) {
|
|
|
6245
6877
|
"--name-only",
|
|
6246
6878
|
"-z",
|
|
6247
6879
|
"--relative",
|
|
6248
|
-
request.changedSince
|
|
6880
|
+
`${request.changedSince}...HEAD`,
|
|
6881
|
+
"--"
|
|
6882
|
+
])) {
|
|
6883
|
+
paths.add(path17);
|
|
6884
|
+
}
|
|
6885
|
+
for (const path17 of gitPaths(cwd, [
|
|
6886
|
+
"diff",
|
|
6887
|
+
"--name-only",
|
|
6888
|
+
"-z",
|
|
6889
|
+
"--relative",
|
|
6890
|
+
"HEAD",
|
|
6249
6891
|
"--"
|
|
6250
6892
|
])) {
|
|
6251
6893
|
paths.add(path17);
|
|
@@ -6265,10 +6907,22 @@ function resolveChangedScope(cwd, request) {
|
|
|
6265
6907
|
"--"
|
|
6266
6908
|
])) {
|
|
6267
6909
|
paths.add(path17);
|
|
6910
|
+
stagedPaths.add(path17);
|
|
6911
|
+
}
|
|
6912
|
+
for (const path17 of gitPaths(cwd, [
|
|
6913
|
+
"diff",
|
|
6914
|
+
"--cached",
|
|
6915
|
+
"--name-only",
|
|
6916
|
+
"-z",
|
|
6917
|
+
"--relative",
|
|
6918
|
+
"--diff-filter=D",
|
|
6919
|
+
"--"
|
|
6920
|
+
])) {
|
|
6921
|
+
deletedPaths.add(path17);
|
|
6268
6922
|
}
|
|
6269
6923
|
descriptions.push("staged");
|
|
6270
6924
|
}
|
|
6271
|
-
return { paths, detail: descriptions.join(" and ") };
|
|
6925
|
+
return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
|
|
6272
6926
|
}
|
|
6273
6927
|
var RELATIVE_SPECIFIER = /^\.{1,2}\//;
|
|
6274
6928
|
var IMPORT_CANDIDATE_SUFFIXES = [
|
|
@@ -6299,34 +6953,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
|
|
|
6299
6953
|
var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
|
|
6300
6954
|
var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
|
|
6301
6955
|
var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
|
|
6302
|
-
|
|
6956
|
+
var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
|
|
6957
|
+
var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
|
|
6958
|
+
function tsconfigPathsFor(cwd) {
|
|
6959
|
+
const configPath = path16.join(cwd, "tsconfig.json");
|
|
6960
|
+
let stats;
|
|
6961
|
+
try {
|
|
6962
|
+
stats = fs15.statSync(configPath);
|
|
6963
|
+
} catch (err) {
|
|
6964
|
+
if (err.code === "ENOENT") return null;
|
|
6965
|
+
return null;
|
|
6966
|
+
}
|
|
6967
|
+
const key = `${stats.mtimeMs}:${stats.size}`;
|
|
6968
|
+
const cached = TSCONFIG_CACHE.get(configPath);
|
|
6969
|
+
if (cached !== void 0 && cached.key === key) return cached.value;
|
|
6970
|
+
let value = null;
|
|
6971
|
+
try {
|
|
6972
|
+
const read = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
6973
|
+
if (read.error === void 0) {
|
|
6974
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, cwd, void 0, configPath);
|
|
6975
|
+
const options = parsed.options;
|
|
6976
|
+
const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
|
|
6977
|
+
const rules = [];
|
|
6978
|
+
if (options.paths !== void 0) {
|
|
6979
|
+
for (const [pattern, targets] of Object.entries(options.paths)) {
|
|
6980
|
+
if (!Array.isArray(targets)) continue;
|
|
6981
|
+
rules.push({
|
|
6982
|
+
pattern,
|
|
6983
|
+
targets: targets.map((target) => String(target).replace(/\\/g, "/"))
|
|
6984
|
+
});
|
|
6985
|
+
}
|
|
6986
|
+
}
|
|
6987
|
+
if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
|
|
6988
|
+
}
|
|
6989
|
+
} catch (err) {
|
|
6990
|
+
value = null;
|
|
6991
|
+
}
|
|
6992
|
+
TSCONFIG_CACHE.set(configPath, { key, value });
|
|
6993
|
+
return value;
|
|
6994
|
+
}
|
|
6995
|
+
function repositoryRelative(cwd, target) {
|
|
6996
|
+
const relative10 = path16.relative(cwd, target).replace(/\\/g, "/");
|
|
6997
|
+
return relative10.length === 0 || !relative10.startsWith("..") && !path16.isAbsolute(relative10) ? relative10 : null;
|
|
6998
|
+
}
|
|
6999
|
+
function rememberFirst(map, key, value) {
|
|
7000
|
+
if (!map.has(key)) map.set(key, value);
|
|
7001
|
+
}
|
|
7002
|
+
function buildImportResolver(files, options = {}) {
|
|
6303
7003
|
const byPath = /* @__PURE__ */ new Map();
|
|
6304
7004
|
const byPathFolded = /* @__PURE__ */ new Map();
|
|
6305
7005
|
const byStem = /* @__PURE__ */ new Map();
|
|
6306
7006
|
const byStemFolded = /* @__PURE__ */ new Map();
|
|
6307
|
-
const
|
|
6308
|
-
|
|
6309
|
-
|
|
6310
|
-
|
|
6311
|
-
|
|
6312
|
-
remember(byPath, relativePath, relativePath);
|
|
6313
|
-
remember(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7007
|
+
const register = (relativePath) => {
|
|
7008
|
+
rememberFirst(byPath, relativePath, relativePath);
|
|
7009
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7010
|
+
rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7011
|
+
}
|
|
6314
7012
|
const extension = path16.posix.extname(relativePath);
|
|
6315
|
-
if (!SOURCE_EXTENSIONS.has(extension))
|
|
7013
|
+
if (!SOURCE_EXTENSIONS.has(extension)) return;
|
|
6316
7014
|
const stem = relativePath.slice(0, -extension.length);
|
|
6317
|
-
|
|
6318
|
-
|
|
7015
|
+
rememberFirst(byStem, stem, relativePath);
|
|
7016
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7017
|
+
rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
|
|
7018
|
+
}
|
|
6319
7019
|
if (path16.posix.basename(stem) === "index") {
|
|
6320
7020
|
const directory = path16.posix.dirname(stem);
|
|
6321
|
-
|
|
6322
|
-
|
|
7021
|
+
rememberFirst(byStem, directory, relativePath);
|
|
7022
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7023
|
+
rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
|
|
7024
|
+
}
|
|
7025
|
+
}
|
|
7026
|
+
};
|
|
7027
|
+
for (const file of files) register(file.relativePath);
|
|
7028
|
+
if (options.extraPaths !== void 0) {
|
|
7029
|
+
for (const extra of options.extraPaths) {
|
|
7030
|
+
if (!byPath.has(extra)) register(extra);
|
|
6323
7031
|
}
|
|
6324
7032
|
}
|
|
6325
|
-
return { byPath, byPathFolded, byStem, byStemFolded };
|
|
7033
|
+
return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
|
|
6326
7034
|
}
|
|
6327
7035
|
function resolveSpecifier(fromFile, specifier, resolver) {
|
|
6328
7036
|
const extension = path16.posix.extname(fromFile).toLowerCase();
|
|
6329
|
-
const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
|
|
7037
|
+
const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
6330
7038
|
const firstOf = (candidates) => {
|
|
6331
7039
|
for (const candidate of candidates) {
|
|
6332
7040
|
const hit = exact(candidate);
|
|
@@ -6334,6 +7042,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6334
7042
|
}
|
|
6335
7043
|
return null;
|
|
6336
7044
|
};
|
|
7045
|
+
const lookupPath = (joined2) => {
|
|
7046
|
+
const direct = exact(joined2);
|
|
7047
|
+
if (direct) return direct;
|
|
7048
|
+
for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
|
|
7049
|
+
const hit = exact(`${joined2}${suffix}`);
|
|
7050
|
+
if (hit) return hit;
|
|
7051
|
+
}
|
|
7052
|
+
const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
|
|
7053
|
+
const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
7054
|
+
return byStem(joined2) ?? byStem(stem);
|
|
7055
|
+
};
|
|
6337
7056
|
if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
|
|
6338
7057
|
const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
|
|
6339
7058
|
const rest = specifier.slice(dots).replace(/\./g, "/");
|
|
@@ -6360,20 +7079,44 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6360
7079
|
);
|
|
6361
7080
|
return firstOf([joined2, `${joined2}.dart`]);
|
|
6362
7081
|
}
|
|
6363
|
-
if (!RELATIVE_SPECIFIER.test(specifier))
|
|
7082
|
+
if (!RELATIVE_SPECIFIER.test(specifier)) {
|
|
7083
|
+
return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
|
|
7084
|
+
}
|
|
6364
7085
|
const joined = path16.posix.normalize(
|
|
6365
7086
|
path16.posix.join(path16.posix.dirname(fromFile), specifier)
|
|
6366
7087
|
);
|
|
6367
|
-
|
|
6368
|
-
|
|
6369
|
-
|
|
6370
|
-
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
6374
|
-
|
|
6375
|
-
|
|
6376
|
-
|
|
7088
|
+
return lookupPath(joined);
|
|
7089
|
+
}
|
|
7090
|
+
function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
|
|
7091
|
+
const config = resolver.tsconfig;
|
|
7092
|
+
if (!config) return null;
|
|
7093
|
+
for (const rule of config.paths) {
|
|
7094
|
+
const star = rule.pattern.indexOf("*");
|
|
7095
|
+
let captured;
|
|
7096
|
+
if (star === -1) {
|
|
7097
|
+
captured = specifier === rule.pattern ? "" : null;
|
|
7098
|
+
} else {
|
|
7099
|
+
const prefix = rule.pattern.slice(0, star);
|
|
7100
|
+
const suffix = rule.pattern.slice(star + 1);
|
|
7101
|
+
if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
|
|
7102
|
+
captured = null;
|
|
7103
|
+
} else {
|
|
7104
|
+
captured = specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
7105
|
+
}
|
|
7106
|
+
}
|
|
7107
|
+
if (captured === null) continue;
|
|
7108
|
+
for (const target of rule.targets) {
|
|
7109
|
+
const substituted = target.split("*").join(captured);
|
|
7110
|
+
const base = config.baseUrl === null ? substituted : path16.posix.join(config.baseUrl, substituted);
|
|
7111
|
+
const hit = lookupPath(path16.posix.normalize(base));
|
|
7112
|
+
if (hit) return hit;
|
|
7113
|
+
}
|
|
7114
|
+
}
|
|
7115
|
+
if (config.baseUrl !== null) {
|
|
7116
|
+
return lookupPath(path16.posix.normalize(path16.posix.join(config.baseUrl, specifier)));
|
|
7117
|
+
}
|
|
7118
|
+
return null;
|
|
7119
|
+
}
|
|
6377
7120
|
function importsChangedFile(importerPath, imports, changedPaths, resolver) {
|
|
6378
7121
|
for (const specifier of imports) {
|
|
6379
7122
|
const resolved = resolveSpecifier(importerPath, specifier, resolver);
|
|
@@ -6461,7 +7204,7 @@ function findStagingDirectory(config) {
|
|
|
6461
7204
|
const tmpDir = path16.resolve(config.cwd, config.tmpDir);
|
|
6462
7205
|
let entries;
|
|
6463
7206
|
try {
|
|
6464
|
-
entries =
|
|
7207
|
+
entries = fs15.readdirSync(tmpDir);
|
|
6465
7208
|
} catch {
|
|
6466
7209
|
return null;
|
|
6467
7210
|
}
|
|
@@ -6474,8 +7217,8 @@ function describeMissingManifest(config, manifestPath) {
|
|
|
6474
7217
|
const markerPath = path16.join(outDir, ".codebase-snapshot");
|
|
6475
7218
|
let marker2 = null;
|
|
6476
7219
|
try {
|
|
6477
|
-
if (
|
|
6478
|
-
const parsed = JSON.parse(
|
|
7220
|
+
if (fs15.existsSync(markerPath)) {
|
|
7221
|
+
const parsed = JSON.parse(fs15.readFileSync(markerPath, "utf8"));
|
|
6479
7222
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
6480
7223
|
marker2 = parsed;
|
|
6481
7224
|
}
|
|
@@ -6512,11 +7255,11 @@ function sha256Hex(buffer) {
|
|
|
6512
7255
|
function wouldNowBeIncluded(cwd, relativePath) {
|
|
6513
7256
|
const absolutePath = path16.join(cwd, relativePath);
|
|
6514
7257
|
try {
|
|
6515
|
-
const stats =
|
|
7258
|
+
const stats = fs15.statSync(absolutePath);
|
|
6516
7259
|
if (!stats.isFile()) return false;
|
|
6517
7260
|
if (isBinaryExtension(absolutePath)) return false;
|
|
6518
7261
|
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
|
|
6519
|
-
return !decodeText(
|
|
7262
|
+
return !decodeText(fs15.readFileSync(absolutePath)).binary;
|
|
6520
7263
|
} catch {
|
|
6521
7264
|
return false;
|
|
6522
7265
|
}
|
|
@@ -6547,14 +7290,71 @@ function describeManifestShapeProblem(value) {
|
|
|
6547
7290
|
if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
|
|
6548
7291
|
return 'missing "totals" object';
|
|
6549
7292
|
}
|
|
7293
|
+
const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
|
|
7294
|
+
if (currentSchema) {
|
|
7295
|
+
const generator = candidate.generator;
|
|
7296
|
+
if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
|
|
7297
|
+
return 'missing "generator" object';
|
|
7298
|
+
}
|
|
7299
|
+
const generatorFields = generator;
|
|
7300
|
+
if (!isOurGeneratorName(generatorFields.name)) {
|
|
7301
|
+
return "`generator.name` is not this generator";
|
|
7302
|
+
}
|
|
7303
|
+
if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
|
|
7304
|
+
return "`generator.version` must be a non-empty string";
|
|
7305
|
+
}
|
|
7306
|
+
const git = candidate.git;
|
|
7307
|
+
if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
|
|
7308
|
+
const gitFields = git;
|
|
7309
|
+
if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
|
|
7310
|
+
if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
|
|
7311
|
+
if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
|
|
7312
|
+
const config = candidate.config;
|
|
7313
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
7314
|
+
return 'missing "config" object';
|
|
7315
|
+
}
|
|
7316
|
+
const budgets = candidate.budgets;
|
|
7317
|
+
if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
|
|
7318
|
+
return 'missing "budgets" object';
|
|
7319
|
+
}
|
|
7320
|
+
for (const key of ["maxPartBytes", "largeFileBytes"]) {
|
|
7321
|
+
const value2 = budgets[key];
|
|
7322
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7323
|
+
return `\`budgets.${key}\` must be a non-negative integer`;
|
|
7324
|
+
}
|
|
7325
|
+
}
|
|
7326
|
+
if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
|
|
7327
|
+
return 'missing "indexes" object';
|
|
7328
|
+
}
|
|
7329
|
+
if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
|
|
7330
|
+
return 'missing "kinds" object';
|
|
7331
|
+
}
|
|
7332
|
+
}
|
|
6550
7333
|
if (!Array.isArray(candidate.files)) return 'missing "files" array';
|
|
6551
7334
|
for (const entry of candidate.files) {
|
|
6552
7335
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6553
7336
|
return 'a "files" entry is not an object';
|
|
6554
7337
|
}
|
|
6555
|
-
|
|
7338
|
+
const fields = entry;
|
|
7339
|
+
if (typeof fields.relativePath !== "string") {
|
|
6556
7340
|
return 'a "files" entry has no "relativePath"';
|
|
6557
7341
|
}
|
|
7342
|
+
if (!currentSchema) continue;
|
|
7343
|
+
if (typeof fields.part !== "string" || fields.part.length === 0) {
|
|
7344
|
+
return 'a "files" entry records no "part"';
|
|
7345
|
+
}
|
|
7346
|
+
if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
|
|
7347
|
+
return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
|
|
7348
|
+
}
|
|
7349
|
+
for (const key of ["sizeBytes", "lines"]) {
|
|
7350
|
+
const value2 = fields[key];
|
|
7351
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7352
|
+
return `a "files" entry "${key}" must be a non-negative integer`;
|
|
7353
|
+
}
|
|
7354
|
+
}
|
|
7355
|
+
if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
|
|
7356
|
+
return 'a "files" entry has an unknown "inclusionMode"';
|
|
7357
|
+
}
|
|
6558
7358
|
}
|
|
6559
7359
|
if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
|
|
6560
7360
|
if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
|
|
@@ -6562,13 +7362,28 @@ function describeManifestShapeProblem(value) {
|
|
|
6562
7362
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6563
7363
|
return 'a "parts" entry is not an object';
|
|
6564
7364
|
}
|
|
6565
|
-
const
|
|
7365
|
+
const fields = entry;
|
|
7366
|
+
const filename = fields.filename;
|
|
6566
7367
|
if (typeof filename !== "string" || filename.trim() === "") {
|
|
6567
7368
|
return 'a "parts" entry has no "filename"';
|
|
6568
7369
|
}
|
|
6569
7370
|
if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16.isAbsolute(filename)) {
|
|
6570
7371
|
return 'a "parts" entry "filename" must be a bare filename inside parts/';
|
|
6571
7372
|
}
|
|
7373
|
+
if (currentSchema) {
|
|
7374
|
+
if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
|
|
7375
|
+
return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
|
|
7376
|
+
}
|
|
7377
|
+
if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
|
|
7378
|
+
return 'a "parts" entry "byteSize" must be a non-negative integer';
|
|
7379
|
+
}
|
|
7380
|
+
if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
|
|
7381
|
+
return 'a "parts" entry "index" must be a positive integer';
|
|
7382
|
+
}
|
|
7383
|
+
if (!Array.isArray(fields.includedFiles)) {
|
|
7384
|
+
return 'a "parts" entry has no "includedFiles" array';
|
|
7385
|
+
}
|
|
7386
|
+
}
|
|
6572
7387
|
}
|
|
6573
7388
|
if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
|
|
6574
7389
|
return 'missing "layers" object';
|
|
@@ -6579,7 +7394,7 @@ function validateSnapshot(configInput) {
|
|
|
6579
7394
|
assertUsableConfigInput(configInput);
|
|
6580
7395
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
|
|
6581
7396
|
const manifestPath = path16.resolve(config.cwd, config.outDir, "manifest.json");
|
|
6582
|
-
if (!
|
|
7397
|
+
if (!fs15.existsSync(manifestPath)) {
|
|
6583
7398
|
return {
|
|
6584
7399
|
valid: false,
|
|
6585
7400
|
manifestPresent: false,
|
|
@@ -6590,7 +7405,7 @@ function validateSnapshot(configInput) {
|
|
|
6590
7405
|
}
|
|
6591
7406
|
let manifest;
|
|
6592
7407
|
try {
|
|
6593
|
-
manifest = JSON.parse(
|
|
7408
|
+
manifest = JSON.parse(fs15.readFileSync(manifestPath, "utf8"));
|
|
6594
7409
|
} catch (err) {
|
|
6595
7410
|
return {
|
|
6596
7411
|
valid: false,
|
|
@@ -6613,6 +7428,19 @@ function validateSnapshot(configInput) {
|
|
|
6613
7428
|
const drift = emptyDrift();
|
|
6614
7429
|
const warnings = [];
|
|
6615
7430
|
const snapshotDir = path16.resolve(config.cwd, config.outDir);
|
|
7431
|
+
const unreadableSkips = manifest.skipped.filter(
|
|
7432
|
+
(entry) => entry.reason === "missing" || entry.reason === "read-error"
|
|
7433
|
+
);
|
|
7434
|
+
if (unreadableSkips.length > 0) {
|
|
7435
|
+
warnings.push(
|
|
7436
|
+
`${unreadableSkips.length} path(s) could not be read when this snapshot was generated (see manifest.skipped[] with reason "missing" or "read-error"); they are not in the snapshot.`
|
|
7437
|
+
);
|
|
7438
|
+
}
|
|
7439
|
+
if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
|
|
7440
|
+
warnings.push(
|
|
7441
|
+
"The configuration uses executable (function) matchers; the recorded digest covers their source text, not the values they capture, so it cannot prove their classification is unchanged."
|
|
7442
|
+
);
|
|
7443
|
+
}
|
|
6616
7444
|
const manifestFileMap = /* @__PURE__ */ new Map();
|
|
6617
7445
|
for (const file of manifest.files) {
|
|
6618
7446
|
if (file && typeof file.relativePath === "string") {
|
|
@@ -6675,7 +7503,7 @@ function validateSnapshot(configInput) {
|
|
|
6675
7503
|
// snapshot was reported as drifting.
|
|
6676
7504
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
6677
7505
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
6678
|
-
).filter((
|
|
7506
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
|
|
6679
7507
|
});
|
|
6680
7508
|
for (const diskFile of collection.files) {
|
|
6681
7509
|
const snapshotHash = manifestFileMap.get(diskFile);
|
|
@@ -6700,7 +7528,7 @@ function validateSnapshot(configInput) {
|
|
|
6700
7528
|
}
|
|
6701
7529
|
let diskHash;
|
|
6702
7530
|
try {
|
|
6703
|
-
diskHash = sha256Hex(
|
|
7531
|
+
diskHash = sha256Hex(fs15.readFileSync(path16.join(config.cwd, diskFile)));
|
|
6704
7532
|
} catch (err) {
|
|
6705
7533
|
if (err.code === "ENOENT") {
|
|
6706
7534
|
drift.missingOnDisk.push(diskFile);
|
|
@@ -6724,7 +7552,7 @@ function validateSnapshot(configInput) {
|
|
|
6724
7552
|
}
|
|
6725
7553
|
let statFailure = null;
|
|
6726
7554
|
try {
|
|
6727
|
-
|
|
7555
|
+
fs15.statSync(confined);
|
|
6728
7556
|
} catch (err) {
|
|
6729
7557
|
statFailure = err;
|
|
6730
7558
|
}
|
|
@@ -6759,7 +7587,7 @@ function validateSnapshot(configInput) {
|
|
|
6759
7587
|
}
|
|
6760
7588
|
let buffer;
|
|
6761
7589
|
try {
|
|
6762
|
-
buffer =
|
|
7590
|
+
buffer = fs15.readFileSync(partPath);
|
|
6763
7591
|
} catch {
|
|
6764
7592
|
drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
|
|
6765
7593
|
continue;
|
|
@@ -6781,22 +7609,83 @@ function validateSnapshot(configInput) {
|
|
|
6781
7609
|
});
|
|
6782
7610
|
}
|
|
6783
7611
|
}
|
|
6784
|
-
const
|
|
6785
|
-
|
|
6786
|
-
|
|
6787
|
-
)
|
|
6788
|
-
|
|
6789
|
-
|
|
6790
|
-
|
|
6791
|
-
|
|
6792
|
-
|
|
7612
|
+
const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7613
|
+
const includedByPart = /* @__PURE__ */ new Map();
|
|
7614
|
+
const partIndexes = /* @__PURE__ */ new Set();
|
|
7615
|
+
for (const part of manifest.parts) {
|
|
7616
|
+
if (includedByPart.has(part.filename)) {
|
|
7617
|
+
drift.partIssues.push({
|
|
7618
|
+
part: maskDriftPath(part.filename),
|
|
7619
|
+
issue: "appears more than once in parts[]"
|
|
7620
|
+
});
|
|
7621
|
+
}
|
|
7622
|
+
if (typeof part.index === "number") {
|
|
7623
|
+
if (partIndexes.has(part.index)) {
|
|
7624
|
+
drift.partIssues.push({
|
|
7625
|
+
part: maskDriftPath(part.filename),
|
|
7626
|
+
issue: `reuses part index ${part.index}`
|
|
7627
|
+
});
|
|
7628
|
+
}
|
|
7629
|
+
partIndexes.add(part.index);
|
|
7630
|
+
}
|
|
7631
|
+
const listed = /* @__PURE__ */ new Set();
|
|
7632
|
+
for (const included of part.includedFiles ?? []) {
|
|
7633
|
+
if (typeof included?.relativePath !== "string") continue;
|
|
7634
|
+
if (listed.has(included.relativePath)) {
|
|
7635
|
+
drift.partIssues.push({
|
|
7636
|
+
part: maskDriftPath(part.filename),
|
|
7637
|
+
issue: `lists ${maskDriftPath(included.relativePath)} twice`
|
|
7638
|
+
});
|
|
7639
|
+
}
|
|
7640
|
+
listed.add(included.relativePath);
|
|
7641
|
+
}
|
|
7642
|
+
includedByPart.set(part.filename, listed);
|
|
7643
|
+
if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
|
|
7644
|
+
drift.partIssues.push({
|
|
7645
|
+
part: maskDriftPath(part.filename),
|
|
7646
|
+
issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
|
|
7647
|
+
});
|
|
7648
|
+
}
|
|
6793
7649
|
}
|
|
7650
|
+
const filePaths = /* @__PURE__ */ new Set();
|
|
6794
7651
|
for (const file of manifest.files) {
|
|
6795
|
-
if (
|
|
7652
|
+
if (filePaths.has(file.relativePath)) {
|
|
7653
|
+
drift.partIssues.push({
|
|
7654
|
+
part: "(files)",
|
|
7655
|
+
issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
|
|
7656
|
+
});
|
|
7657
|
+
continue;
|
|
7658
|
+
}
|
|
7659
|
+
filePaths.add(file.relativePath);
|
|
7660
|
+
if (typeof file.part !== "string" || file.part.length === 0) {
|
|
7661
|
+
drift.partIssues.push({
|
|
7662
|
+
part: "(files)",
|
|
7663
|
+
issue: `${maskDriftPath(file.relativePath)} records no part`
|
|
7664
|
+
});
|
|
7665
|
+
continue;
|
|
7666
|
+
}
|
|
7667
|
+
if (!partNames.has(file.part)) {
|
|
6796
7668
|
drift.partIssues.push({
|
|
6797
|
-
part: file.part,
|
|
6798
|
-
issue: `${file.relativePath} points at a part that is not in the manifest`
|
|
7669
|
+
part: maskDriftPath(file.part),
|
|
7670
|
+
issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
|
|
6799
7671
|
});
|
|
7672
|
+
continue;
|
|
7673
|
+
}
|
|
7674
|
+
if (!includedByPart.get(file.part)?.has(file.relativePath)) {
|
|
7675
|
+
drift.partIssues.push({
|
|
7676
|
+
part: maskDriftPath(file.part),
|
|
7677
|
+
issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
|
|
7678
|
+
});
|
|
7679
|
+
}
|
|
7680
|
+
}
|
|
7681
|
+
for (const [partName, listed] of includedByPart) {
|
|
7682
|
+
for (const relativePath of listed) {
|
|
7683
|
+
if (!filePaths.has(relativePath)) {
|
|
7684
|
+
drift.partIssues.push({
|
|
7685
|
+
part: maskDriftPath(partName),
|
|
7686
|
+
issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
|
|
7687
|
+
});
|
|
7688
|
+
}
|
|
6800
7689
|
}
|
|
6801
7690
|
}
|
|
6802
7691
|
const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
@@ -6954,6 +7843,13 @@ function validateSnapshot(configInput) {
|
|
|
6954
7843
|
0
|
|
6955
7844
|
);
|
|
6956
7845
|
expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
|
|
7846
|
+
if (manifest.files.every((file) => typeof file?.lines === "number")) {
|
|
7847
|
+
expectEqual(
|
|
7848
|
+
"counts.totalLines",
|
|
7849
|
+
counts.totalLines,
|
|
7850
|
+
manifest.files.reduce((total, file) => total + file.lines, 0)
|
|
7851
|
+
);
|
|
7852
|
+
}
|
|
6957
7853
|
expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
|
|
6958
7854
|
expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
|
|
6959
7855
|
expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
|
|
@@ -6977,6 +7873,37 @@ function validateSnapshot(configInput) {
|
|
|
6977
7873
|
`totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
|
|
6978
7874
|
);
|
|
6979
7875
|
}
|
|
7876
|
+
const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
|
|
7877
|
+
if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
|
|
7878
|
+
const settingsLine = `settings:${recordedSettingsDigest}`;
|
|
7879
|
+
const currentDefinition = sha256Hex(
|
|
7880
|
+
Buffer.from(
|
|
7881
|
+
[
|
|
7882
|
+
...manifest.files.map(
|
|
7883
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
7884
|
+
),
|
|
7885
|
+
settingsLine
|
|
7886
|
+
].join("\n"),
|
|
7887
|
+
"utf8"
|
|
7888
|
+
)
|
|
7889
|
+
);
|
|
7890
|
+
const legacyDefinition = sha256Hex(
|
|
7891
|
+
Buffer.from(
|
|
7892
|
+
[
|
|
7893
|
+
...manifest.files.map(
|
|
7894
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
|
|
7895
|
+
),
|
|
7896
|
+
settingsLine
|
|
7897
|
+
].join("\n"),
|
|
7898
|
+
"utf8"
|
|
7899
|
+
)
|
|
7900
|
+
);
|
|
7901
|
+
if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
|
|
7902
|
+
totalsMismatches.push(
|
|
7903
|
+
"fingerprint: does not match the files and settings recorded in this manifest"
|
|
7904
|
+
);
|
|
7905
|
+
}
|
|
7906
|
+
}
|
|
6980
7907
|
if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
|
|
6981
7908
|
totalsMismatches.push(
|
|
6982
7909
|
`budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
|
|
@@ -7004,26 +7931,49 @@ function validateSnapshot(configInput) {
|
|
|
7004
7931
|
drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
|
|
7005
7932
|
}
|
|
7006
7933
|
}
|
|
7007
|
-
|
|
7934
|
+
const declaredArtifacts = [
|
|
7935
|
+
["README.md", manifest.artifacts?.readme],
|
|
7936
|
+
["reports/navigation.md", manifest.artifacts?.navigation],
|
|
7937
|
+
["reports/project-tree.md", manifest.artifacts?.projectTree],
|
|
7938
|
+
["reports/audit.md", manifest.artifacts?.audit],
|
|
7008
7939
|
["full-codebase.json", manifest.artifacts?.fullJson],
|
|
7009
7940
|
["full-codebase.md", manifest.artifacts?.fullMarkdown]
|
|
7010
|
-
]
|
|
7941
|
+
];
|
|
7942
|
+
for (const [key, artifact] of declaredArtifacts) {
|
|
7011
7943
|
if (!artifact) continue;
|
|
7012
|
-
const artifactPath = path16.join(snapshotDir, key);
|
|
7944
|
+
const artifactPath = path16.join(snapshotDir, ...key.split("/"));
|
|
7945
|
+
let buffer;
|
|
7013
7946
|
try {
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7017
|
-
}
|
|
7947
|
+
if (!fs15.statSync(artifactPath).isFile()) throw new Error("not a regular file");
|
|
7948
|
+
buffer = fs15.readFileSync(artifactPath);
|
|
7018
7949
|
} catch {
|
|
7019
7950
|
drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
|
|
7951
|
+
continue;
|
|
7952
|
+
}
|
|
7953
|
+
if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
|
|
7954
|
+
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7955
|
+
continue;
|
|
7956
|
+
}
|
|
7957
|
+
if (key === "reports/navigation.md") {
|
|
7958
|
+
for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
|
|
7959
|
+
const target = match[1].split("#")[0];
|
|
7960
|
+
if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
|
|
7961
|
+
const resolved = path16.resolve(snapshotDir, "reports", target);
|
|
7962
|
+
const relative10 = path16.relative(snapshotDir, resolved);
|
|
7963
|
+
if (relative10.startsWith("..") || path16.isAbsolute(relative10) || !fs15.existsSync(resolved)) {
|
|
7964
|
+
drift.partIssues.push({
|
|
7965
|
+
part: key,
|
|
7966
|
+
issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
|
|
7967
|
+
});
|
|
7968
|
+
}
|
|
7969
|
+
}
|
|
7020
7970
|
}
|
|
7021
7971
|
}
|
|
7022
7972
|
const sarifArtifact = manifest.artifacts?.sarif;
|
|
7023
7973
|
if (sarifArtifact) {
|
|
7024
7974
|
const sarifKey = "reports/audit.sarif";
|
|
7025
7975
|
try {
|
|
7026
|
-
const buffer =
|
|
7976
|
+
const buffer = fs15.readFileSync(path16.join(snapshotDir, "reports", "audit.sarif"));
|
|
7027
7977
|
if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
|
|
7028
7978
|
drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
|
|
7029
7979
|
}
|
|
@@ -7032,8 +7982,11 @@ function validateSnapshot(configInput) {
|
|
|
7032
7982
|
}
|
|
7033
7983
|
}
|
|
7034
7984
|
if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
|
|
7985
|
+
const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7986
|
+
const generatedOn = maskBranch(manifest.git.branch);
|
|
7987
|
+
const configuredAs = maskBranch(config.branch);
|
|
7035
7988
|
warnings.push(
|
|
7036
|
-
`Snapshot was generated on branch "${
|
|
7989
|
+
`Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
|
|
7037
7990
|
);
|
|
7038
7991
|
}
|
|
7039
7992
|
const errors = [];
|
|
@@ -7090,17 +8043,9 @@ function validateSnapshot(configInput) {
|
|
|
7090
8043
|
warnings
|
|
7091
8044
|
};
|
|
7092
8045
|
}
|
|
7093
|
-
|
|
7094
|
-
// src/version.ts
|
|
7095
|
-
var GENERATOR_NAME = "codebase-snapshot";
|
|
7096
|
-
var GENERATOR_VERSION = "0.9.16";
|
|
7097
|
-
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
7098
|
-
function isOurGeneratorName(name) {
|
|
7099
|
-
if (typeof name !== "string") return false;
|
|
7100
|
-
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
7101
|
-
}
|
|
7102
8046
|
var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
|
|
7103
8047
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
8048
|
+
var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
7104
8049
|
var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
7105
8050
|
var REQUEST_TIMEOUT_MS = 1200;
|
|
7106
8051
|
function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
|
|
@@ -7169,23 +8114,24 @@ function shouldCheck(argv, env) {
|
|
|
7169
8114
|
for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
|
|
7170
8115
|
if (args.includes(skip)) return false;
|
|
7171
8116
|
}
|
|
8117
|
+
let format = null;
|
|
7172
8118
|
for (let index = 0; index < args.length; index += 1) {
|
|
7173
8119
|
const argument = args[index];
|
|
8120
|
+
if (argument === "--") break;
|
|
7174
8121
|
if (argument === "--format") {
|
|
7175
|
-
|
|
7176
|
-
|
|
7177
|
-
|
|
7178
|
-
if (argument.startsWith("--format=")) {
|
|
7179
|
-
if (argument.slice("--format=".length) === "json") return false;
|
|
7180
|
-
break;
|
|
8122
|
+
format = args[index + 1] ?? null;
|
|
8123
|
+
index += 1;
|
|
8124
|
+
continue;
|
|
7181
8125
|
}
|
|
8126
|
+
if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
|
|
7182
8127
|
}
|
|
8128
|
+
if (format === "json") return false;
|
|
7183
8129
|
return true;
|
|
7184
8130
|
}
|
|
7185
8131
|
function readCache(file) {
|
|
7186
8132
|
let raw;
|
|
7187
8133
|
try {
|
|
7188
|
-
raw =
|
|
8134
|
+
raw = fs15.readFileSync(file, "utf8");
|
|
7189
8135
|
} catch {
|
|
7190
8136
|
return null;
|
|
7191
8137
|
}
|
|
@@ -7202,21 +8148,21 @@ function readCache(file) {
|
|
|
7202
8148
|
}
|
|
7203
8149
|
function writeCache(file, entry) {
|
|
7204
8150
|
try {
|
|
7205
|
-
|
|
7206
|
-
|
|
8151
|
+
fs15.mkdirSync(path16.dirname(file), { recursive: true });
|
|
8152
|
+
fs15.writeFileSync(file, `${JSON.stringify(entry)}
|
|
7207
8153
|
`, "utf8");
|
|
7208
8154
|
} catch {
|
|
7209
8155
|
}
|
|
7210
8156
|
}
|
|
7211
8157
|
function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
7212
|
-
return new Promise((
|
|
8158
|
+
return new Promise((resolve7) => {
|
|
7213
8159
|
let settled = false;
|
|
7214
8160
|
let request = null;
|
|
7215
8161
|
const finish = (value) => {
|
|
7216
8162
|
if (settled) return;
|
|
7217
8163
|
settled = true;
|
|
7218
8164
|
clearTimeout(deadline);
|
|
7219
|
-
|
|
8165
|
+
resolve7(value);
|
|
7220
8166
|
};
|
|
7221
8167
|
const deadline = setTimeout(() => {
|
|
7222
8168
|
request?.destroy();
|
|
@@ -7274,7 +8220,8 @@ async function checkForUpdate(options) {
|
|
|
7274
8220
|
needsFetch = age >= FAILURE_INTERVAL_MS;
|
|
7275
8221
|
} else {
|
|
7276
8222
|
latest = cached.latest;
|
|
7277
|
-
|
|
8223
|
+
const interval = isNewer(cached.latest, options.current) ? CHECK_INTERVAL_MS : UP_TO_DATE_INTERVAL_MS;
|
|
8224
|
+
needsFetch = age >= interval;
|
|
7278
8225
|
}
|
|
7279
8226
|
}
|
|
7280
8227
|
if (needsFetch) {
|
|
@@ -7303,23 +8250,23 @@ function describeMatcher(matcher) {
|
|
|
7303
8250
|
function normalizeTarget(cwd, target) {
|
|
7304
8251
|
const resolvedCwd = path16.resolve(cwd);
|
|
7305
8252
|
const absolute = path16.resolve(resolvedCwd, target);
|
|
7306
|
-
const
|
|
7307
|
-
if (
|
|
8253
|
+
const relative10 = path16.relative(resolvedCwd, absolute);
|
|
8254
|
+
if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
|
|
7308
8255
|
return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
|
|
7309
8256
|
}
|
|
7310
|
-
return { relative:
|
|
8257
|
+
return { relative: relative10.split(path16.sep).join("/"), outsideRoot: false };
|
|
7311
8258
|
}
|
|
7312
8259
|
function findRuleMatch(rules, relativePath) {
|
|
7313
8260
|
return rules.find(
|
|
7314
8261
|
(rule) => matchRule(relativePath, rule.match)
|
|
7315
8262
|
);
|
|
7316
8263
|
}
|
|
7317
|
-
function findRecordedAncestor(skipped,
|
|
8264
|
+
function findRecordedAncestor(skipped, relative10, maskedPath2) {
|
|
7318
8265
|
let nearest;
|
|
7319
8266
|
for (const record of skipped) {
|
|
7320
8267
|
const ancestorPath = record.path;
|
|
7321
8268
|
if (ancestorPath.length === 0) continue;
|
|
7322
|
-
const isAncestor =
|
|
8269
|
+
const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
|
|
7323
8270
|
if (!isAncestor) continue;
|
|
7324
8271
|
if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
|
|
7325
8272
|
}
|
|
@@ -7328,15 +8275,15 @@ function findRecordedAncestor(skipped, relative8, maskedPath2) {
|
|
|
7328
8275
|
function readManifest2(config) {
|
|
7329
8276
|
const manifestPath = path16.resolve(config.cwd, config.outDir, "manifest.json");
|
|
7330
8277
|
try {
|
|
7331
|
-
return JSON.parse(
|
|
8278
|
+
return JSON.parse(fs15.readFileSync(manifestPath, "utf8"));
|
|
7332
8279
|
} catch {
|
|
7333
8280
|
return null;
|
|
7334
8281
|
}
|
|
7335
8282
|
}
|
|
7336
8283
|
function explainPath(config, target) {
|
|
7337
8284
|
const normalized = normalizeTarget(config.cwd, target);
|
|
7338
|
-
const
|
|
7339
|
-
const maskedPath2 = findSecretInPath(
|
|
8285
|
+
const relative10 = normalized.relative;
|
|
8286
|
+
const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
|
|
7340
8287
|
if (normalized.outsideRoot) {
|
|
7341
8288
|
return {
|
|
7342
8289
|
path: maskedPath2,
|
|
@@ -7346,10 +8293,10 @@ function explainPath(config, target) {
|
|
|
7346
8293
|
detail: "path resolves outside the configured repository root and was not inspected"
|
|
7347
8294
|
};
|
|
7348
8295
|
}
|
|
7349
|
-
const absolute = path16.join(config.cwd,
|
|
8296
|
+
const absolute = path16.join(config.cwd, relative10);
|
|
7350
8297
|
const result = {
|
|
7351
8298
|
path: maskedPath2,
|
|
7352
|
-
exists:
|
|
8299
|
+
exists: fs15.existsSync(absolute),
|
|
7353
8300
|
included: false
|
|
7354
8301
|
};
|
|
7355
8302
|
const collection = collectFiles(config.cwd, {
|
|
@@ -7364,11 +8311,11 @@ function explainPath(config, target) {
|
|
|
7364
8311
|
// that is only missing because the walker dropped the tool's own output directory.
|
|
7365
8312
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
7366
8313
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
7367
|
-
).filter((
|
|
8314
|
+
).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
|
|
7368
8315
|
});
|
|
7369
|
-
if (!collection.files.includes(
|
|
8316
|
+
if (!collection.files.includes(relative10)) {
|
|
7370
8317
|
const record = collection.skipped.find(
|
|
7371
|
-
(entry2) => entry2.path ===
|
|
8318
|
+
(entry2) => entry2.path === relative10 || entry2.path === maskedPath2
|
|
7372
8319
|
);
|
|
7373
8320
|
if (record) {
|
|
7374
8321
|
result.reason = record.reason;
|
|
@@ -7377,7 +8324,7 @@ function explainPath(config, target) {
|
|
|
7377
8324
|
result.reason = "missing";
|
|
7378
8325
|
result.detail = "no such file or directory, relative to the configured cwd";
|
|
7379
8326
|
} else {
|
|
7380
|
-
const ancestor = findRecordedAncestor(collection.skipped,
|
|
8327
|
+
const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
|
|
7381
8328
|
if (ancestor) {
|
|
7382
8329
|
result.reason = ancestor.reason;
|
|
7383
8330
|
result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
|
|
@@ -7397,11 +8344,11 @@ function explainPath(config, target) {
|
|
|
7397
8344
|
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
7398
8345
|
...config.staged === true ? { staged: true } : {}
|
|
7399
8346
|
});
|
|
7400
|
-
inScope = scope.paths.has(
|
|
8347
|
+
inScope = scope.paths.has(relative10);
|
|
7401
8348
|
if (!inScope && config.withDependents === true) {
|
|
7402
8349
|
inScope = importsChangedFile(
|
|
7403
|
-
|
|
7404
|
-
importsOfFile(
|
|
8350
|
+
relative10,
|
|
8351
|
+
importsOfFile(relative10, absolute),
|
|
7405
8352
|
scope.paths,
|
|
7406
8353
|
buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
|
|
7407
8354
|
);
|
|
@@ -7428,7 +8375,7 @@ function explainPath(config, target) {
|
|
|
7428
8375
|
}
|
|
7429
8376
|
let sizeOnDisk = null;
|
|
7430
8377
|
try {
|
|
7431
|
-
sizeOnDisk =
|
|
8378
|
+
sizeOnDisk = fs15.statSync(absolute).size;
|
|
7432
8379
|
} catch {
|
|
7433
8380
|
sizeOnDisk = null;
|
|
7434
8381
|
}
|
|
@@ -7438,8 +8385,16 @@ function explainPath(config, target) {
|
|
|
7438
8385
|
result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
|
|
7439
8386
|
return result;
|
|
7440
8387
|
}
|
|
7441
|
-
if (
|
|
7442
|
-
|
|
8388
|
+
if (fs15.existsSync(absolute) && fs15.statSync(absolute).isFile()) {
|
|
8389
|
+
let buffer;
|
|
8390
|
+
try {
|
|
8391
|
+
buffer = fs15.readFileSync(absolute);
|
|
8392
|
+
} catch (err) {
|
|
8393
|
+
result.included = false;
|
|
8394
|
+
result.reason = "read-error";
|
|
8395
|
+
result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
|
|
8396
|
+
return result;
|
|
8397
|
+
}
|
|
7443
8398
|
const decoded = decodeText(buffer);
|
|
7444
8399
|
if (decoded.binary) {
|
|
7445
8400
|
result.included = false;
|
|
@@ -7451,21 +8406,30 @@ function explainPath(config, target) {
|
|
|
7451
8406
|
result.bytes = buffer.length;
|
|
7452
8407
|
result.lines = countLines(text2);
|
|
7453
8408
|
if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
|
|
7454
|
-
const { findings } = scanAndRedactSecrets(text2, config.secretRules,
|
|
8409
|
+
const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative10);
|
|
7455
8410
|
result.secretCount = findings.length;
|
|
7456
8411
|
result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
|
|
8412
|
+
let inclusionMode = "full";
|
|
8413
|
+
if (config.skeleton === true && isSkeletonizable(relative10)) {
|
|
8414
|
+
const skeleton = skeletonizeTypeScript(text2, relative10);
|
|
8415
|
+
if (skeleton.collapsed > 0) inclusionMode = "signatures";
|
|
8416
|
+
}
|
|
8417
|
+
if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
|
|
8418
|
+
const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
|
|
8419
|
+
inclusionMode = preview.isTruncated ? "preview" : "full";
|
|
8420
|
+
}
|
|
8421
|
+
result.inclusionMode = inclusionMode;
|
|
7457
8422
|
}
|
|
7458
|
-
result.layer = classifyLayer(
|
|
7459
|
-
result.kind = classifyKind(
|
|
7460
|
-
result.language = detectLanguage(
|
|
7461
|
-
const layerRule = findRuleMatch(config.layers,
|
|
8423
|
+
result.layer = classifyLayer(relative10, config.layers);
|
|
8424
|
+
result.kind = classifyKind(relative10, config.kinds);
|
|
8425
|
+
result.language = detectLanguage(relative10);
|
|
8426
|
+
const layerRule = findRuleMatch(config.layers, relative10);
|
|
7462
8427
|
if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
|
|
7463
|
-
const kindRule = findRuleMatch(config.kinds,
|
|
8428
|
+
const kindRule = findRuleMatch(config.kinds, relative10);
|
|
7464
8429
|
if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
|
|
7465
8430
|
const manifest = readManifest2(config);
|
|
7466
|
-
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath ===
|
|
8431
|
+
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
|
|
7467
8432
|
result.part = entry?.part ?? null;
|
|
7468
|
-
result.inclusionMode = entry?.inclusionMode;
|
|
7469
8433
|
return result;
|
|
7470
8434
|
}
|
|
7471
8435
|
function renderExplainText(result) {
|
|
@@ -7694,14 +8658,14 @@ function compareManifests(before, after) {
|
|
|
7694
8658
|
function loadManifest(target) {
|
|
7695
8659
|
let isDirectory;
|
|
7696
8660
|
try {
|
|
7697
|
-
isDirectory =
|
|
8661
|
+
isDirectory = fs15.statSync(target).isDirectory();
|
|
7698
8662
|
} catch {
|
|
7699
8663
|
throw new Error(`No snapshot found at ${target}: the path does not exist.`);
|
|
7700
8664
|
}
|
|
7701
8665
|
const manifestPath = isDirectory ? path16.join(target, "manifest.json") : target;
|
|
7702
8666
|
let raw;
|
|
7703
8667
|
try {
|
|
7704
|
-
raw =
|
|
8668
|
+
raw = fs15.readFileSync(manifestPath, "utf8");
|
|
7705
8669
|
} catch {
|
|
7706
8670
|
throw new Error(`Could not read a manifest at ${manifestPath}.`);
|
|
7707
8671
|
}
|
|
@@ -7755,18 +8719,70 @@ function renderDiffText(diff) {
|
|
|
7755
8719
|
}
|
|
7756
8720
|
return lines.join("\n");
|
|
7757
8721
|
}
|
|
8722
|
+
function decodeGitignore(buffer) {
|
|
8723
|
+
const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
|
|
8724
|
+
if (startsWith(239, 187, 191)) {
|
|
8725
|
+
const body = buffer.subarray(3);
|
|
8726
|
+
const text3 = body.toString("utf8");
|
|
8727
|
+
if (!Buffer.from(text3, "utf8").equals(body)) return null;
|
|
8728
|
+
return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
|
|
8729
|
+
}
|
|
8730
|
+
if (startsWith(255, 254)) {
|
|
8731
|
+
const body = buffer.subarray(2);
|
|
8732
|
+
if (body.length % 2 !== 0) return null;
|
|
8733
|
+
const text3 = body.toString("utf16le");
|
|
8734
|
+
if (!Buffer.from(text3, "utf16le").equals(body)) return null;
|
|
8735
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
|
|
8736
|
+
}
|
|
8737
|
+
if (startsWith(254, 255)) {
|
|
8738
|
+
const body = buffer.subarray(2);
|
|
8739
|
+
if (body.length % 2 !== 0) return null;
|
|
8740
|
+
const swapped = Buffer.from(body);
|
|
8741
|
+
swapped.swap16();
|
|
8742
|
+
const text3 = swapped.toString("utf16le");
|
|
8743
|
+
if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
|
|
8744
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
|
|
8745
|
+
}
|
|
8746
|
+
const text2 = buffer.toString("utf8");
|
|
8747
|
+
if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
|
|
8748
|
+
return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
|
|
8749
|
+
}
|
|
8750
|
+
function encodeGitignore(decoded, text2) {
|
|
8751
|
+
if (decoded.encoding === "utf8") {
|
|
8752
|
+
return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
|
|
8753
|
+
}
|
|
8754
|
+
const littleEndian = Buffer.from(text2, "utf16le");
|
|
8755
|
+
if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
|
|
8756
|
+
const bigEndian = Buffer.from(littleEndian);
|
|
8757
|
+
bigEndian.swap16();
|
|
8758
|
+
return Buffer.concat([decoded.bom, bigEndian]);
|
|
8759
|
+
}
|
|
8760
|
+
function canonicalIgnorePattern(line) {
|
|
8761
|
+
const trimmed = line.trim();
|
|
8762
|
+
if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
|
|
8763
|
+
const negated = trimmed.startsWith("!");
|
|
8764
|
+
const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
|
|
8765
|
+
return `${negated ? "!" : ""}${body}`;
|
|
8766
|
+
}
|
|
7758
8767
|
function appendGitignoreEntries(cwd, entries) {
|
|
7759
8768
|
const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
|
|
7760
8769
|
if (wanted.length === 0) return { added: [], note: null };
|
|
7761
8770
|
const ignorePath = path16.join(cwd, ".gitignore");
|
|
7762
8771
|
const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
|
|
7763
|
-
let
|
|
8772
|
+
let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
|
|
7764
8773
|
try {
|
|
7765
|
-
if (
|
|
7766
|
-
if (
|
|
8774
|
+
if (fs15.existsSync(ignorePath)) {
|
|
8775
|
+
if (fs15.statSync(ignorePath).isDirectory()) {
|
|
7767
8776
|
return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
|
|
7768
8777
|
}
|
|
7769
|
-
|
|
8778
|
+
const read = decodeGitignore(fs15.readFileSync(ignorePath));
|
|
8779
|
+
if (read === null) {
|
|
8780
|
+
return {
|
|
8781
|
+
added: [],
|
|
8782
|
+
note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
|
|
8783
|
+
};
|
|
8784
|
+
}
|
|
8785
|
+
decoded = read;
|
|
7770
8786
|
}
|
|
7771
8787
|
} catch (err) {
|
|
7772
8788
|
return {
|
|
@@ -7774,13 +8790,17 @@ function appendGitignoreEntries(cwd, entries) {
|
|
|
7774
8790
|
note: `${ignorePath} could not be read (${err.message}). ${manual}`
|
|
7775
8791
|
};
|
|
7776
8792
|
}
|
|
7777
|
-
const
|
|
7778
|
-
const
|
|
8793
|
+
const existing = decoded.text;
|
|
8794
|
+
const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
|
|
8795
|
+
const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
|
|
7779
8796
|
if (added.length === 0) return { added: [], note: null };
|
|
7780
|
-
const
|
|
8797
|
+
const newline = existing.includes("\r\n") ? "\r\n" : "\n";
|
|
8798
|
+
const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
|
|
7781
8799
|
try {
|
|
7782
|
-
|
|
7783
|
-
|
|
8800
|
+
fs15.writeFileSync(
|
|
8801
|
+
ignorePath,
|
|
8802
|
+
encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
|
|
8803
|
+
);
|
|
7784
8804
|
} catch (err) {
|
|
7785
8805
|
return { added: [], note: `${err.message}. ${manual}` };
|
|
7786
8806
|
}
|
|
@@ -8098,7 +9118,7 @@ function keyReader(input) {
|
|
|
8098
9118
|
next() {
|
|
8099
9119
|
const queued = queue.shift();
|
|
8100
9120
|
if (queued) return Promise.resolve(queued);
|
|
8101
|
-
return new Promise((
|
|
9121
|
+
return new Promise((resolve7) => waiters.push(resolve7));
|
|
8102
9122
|
},
|
|
8103
9123
|
close() {
|
|
8104
9124
|
input.off("keypress", onKey);
|
|
@@ -8324,7 +9344,7 @@ function parsePackageJson(raw) {
|
|
|
8324
9344
|
}
|
|
8325
9345
|
function readPackageJson(cwd) {
|
|
8326
9346
|
try {
|
|
8327
|
-
return parsePackageJson(
|
|
9347
|
+
return parsePackageJson(fs15.readFileSync(path16.join(cwd, "package.json"), "utf8"));
|
|
8328
9348
|
} catch {
|
|
8329
9349
|
return null;
|
|
8330
9350
|
}
|
|
@@ -8361,7 +9381,7 @@ function artifactAnswers(options) {
|
|
|
8361
9381
|
}
|
|
8362
9382
|
function topLevelDirs(cwd) {
|
|
8363
9383
|
try {
|
|
8364
|
-
return
|
|
9384
|
+
return fs15.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
|
|
8365
9385
|
} catch {
|
|
8366
9386
|
return [];
|
|
8367
9387
|
}
|
|
@@ -8374,10 +9394,38 @@ function describeJsonValue(value) {
|
|
|
8374
9394
|
}
|
|
8375
9395
|
function writeFileOrExplain(target, content) {
|
|
8376
9396
|
try {
|
|
8377
|
-
|
|
9397
|
+
let stats = null;
|
|
9398
|
+
try {
|
|
9399
|
+
stats = fs15.lstatSync(target);
|
|
9400
|
+
} catch {
|
|
9401
|
+
stats = null;
|
|
9402
|
+
}
|
|
9403
|
+
if (stats !== null && stats.isSymbolicLink()) {
|
|
9404
|
+
throw new Error(
|
|
9405
|
+
`Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
|
|
9406
|
+
);
|
|
9407
|
+
}
|
|
9408
|
+
if (stats !== null && !stats.isFile()) {
|
|
9409
|
+
throw new Error(
|
|
9410
|
+
`Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
|
|
9411
|
+
);
|
|
9412
|
+
}
|
|
9413
|
+
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
9414
|
+
fs15.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
|
|
9415
|
+
try {
|
|
9416
|
+
fs15.renameSync(temporary, target);
|
|
9417
|
+
} catch (err) {
|
|
9418
|
+
try {
|
|
9419
|
+
fs15.unlinkSync(temporary);
|
|
9420
|
+
} catch {
|
|
9421
|
+
}
|
|
9422
|
+
throw err;
|
|
9423
|
+
}
|
|
8378
9424
|
} catch (err) {
|
|
9425
|
+
const message = err.message;
|
|
9426
|
+
if (message.startsWith(`Cannot write ${target}:`)) throw err;
|
|
8379
9427
|
const code = err.code;
|
|
8380
|
-
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" :
|
|
9428
|
+
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
|
|
8381
9429
|
throw new Error(`Cannot write ${target}: ${reason}`);
|
|
8382
9430
|
}
|
|
8383
9431
|
}
|
|
@@ -8421,14 +9469,14 @@ function updatePackageJson(cwd, notes) {
|
|
|
8421
9469
|
scripts: [],
|
|
8422
9470
|
dependency: { name: GENERATOR_NAME, range: null, added: false }
|
|
8423
9471
|
};
|
|
8424
|
-
if (!
|
|
9472
|
+
if (!fs15.existsSync(packagePath)) {
|
|
8425
9473
|
notes.push("No package.json found, so npm scripts and the devDependency were not added.");
|
|
8426
9474
|
return unchanged;
|
|
8427
9475
|
}
|
|
8428
9476
|
let raw;
|
|
8429
9477
|
let parsed;
|
|
8430
9478
|
try {
|
|
8431
|
-
raw =
|
|
9479
|
+
raw = fs15.readFileSync(packagePath, "utf8");
|
|
8432
9480
|
parsed = parsePackageJson(raw);
|
|
8433
9481
|
} catch {
|
|
8434
9482
|
notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
|
|
@@ -8499,7 +9547,7 @@ function updatePackageJson(cwd, notes) {
|
|
|
8499
9547
|
writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
|
|
8500
9548
|
return { scripts: added, dependency };
|
|
8501
9549
|
}
|
|
8502
|
-
var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
|
|
9550
|
+
var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
|
|
8503
9551
|
function resolvePresetChoice(detectedName, presetName) {
|
|
8504
9552
|
return {
|
|
8505
9553
|
value: presetName,
|
|
@@ -8737,7 +9785,7 @@ async function runInit(options) {
|
|
|
8737
9785
|
const configText = renderConfig(answers);
|
|
8738
9786
|
const preferredName = chooseConfigFileName(options.cwd);
|
|
8739
9787
|
const presentConfigs = CONFIG_CANDIDATES.filter(
|
|
8740
|
-
(name) =>
|
|
9788
|
+
(name) => fs15.existsSync(path16.join(options.cwd, name))
|
|
8741
9789
|
);
|
|
8742
9790
|
const present = presentConfigs[0] ?? null;
|
|
8743
9791
|
if (presentConfigs.length > 1) {
|
|
@@ -8780,7 +9828,7 @@ async function runInit(options) {
|
|
|
8780
9828
|
'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
|
|
8781
9829
|
);
|
|
8782
9830
|
}
|
|
8783
|
-
if (
|
|
9831
|
+
if (fs15.existsSync(configPath) && !options.force && !reused) {
|
|
8784
9832
|
throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
|
|
8785
9833
|
}
|
|
8786
9834
|
if (!reused) writeFileOrExplain(configPath, configText);
|
|
@@ -8803,10 +9851,10 @@ async function runInit(options) {
|
|
|
8803
9851
|
};
|
|
8804
9852
|
}
|
|
8805
9853
|
function describeTarget(cwd) {
|
|
8806
|
-
const
|
|
8807
|
-
if (
|
|
8808
|
-
if (
|
|
8809
|
-
return
|
|
9854
|
+
const relative10 = path16.relative(process.cwd(), cwd);
|
|
9855
|
+
if (relative10 === "") return "this directory";
|
|
9856
|
+
if (relative10.startsWith("..") || path16.isAbsolute(relative10)) return cwd;
|
|
9857
|
+
return relative10;
|
|
8810
9858
|
}
|
|
8811
9859
|
function firstRunMessage(reason, cwd) {
|
|
8812
9860
|
const where = describeTarget(cwd);
|
|
@@ -8829,7 +9877,7 @@ function planFirstRun(facts) {
|
|
|
8829
9877
|
var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
|
|
8830
9878
|
function isEffectivelyEmpty(cwd) {
|
|
8831
9879
|
try {
|
|
8832
|
-
return
|
|
9880
|
+
return fs15.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
|
|
8833
9881
|
} catch {
|
|
8834
9882
|
return false;
|
|
8835
9883
|
}
|
|
@@ -8837,7 +9885,7 @@ function isEffectivelyEmpty(cwd) {
|
|
|
8837
9885
|
function hasPriorSnapshot(cwd, outDir) {
|
|
8838
9886
|
let parsed;
|
|
8839
9887
|
try {
|
|
8840
|
-
parsed = JSON.parse(
|
|
9888
|
+
parsed = JSON.parse(fs15.readFileSync(path16.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
|
|
8841
9889
|
} catch {
|
|
8842
9890
|
return false;
|
|
8843
9891
|
}
|
|
@@ -8863,9 +9911,17 @@ set -e
|
|
|
8863
9911
|
SNAPSHOT_DIR="${dir}"
|
|
8864
9912
|
|
|
8865
9913
|
if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
|
|
8866
|
-
|
|
8867
|
-
|
|
8868
|
-
|
|
9914
|
+
# Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
|
|
9915
|
+
# renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
|
|
9916
|
+
# failure mode a commit gate must not have. The opt-out is explicit and documented.
|
|
9917
|
+
if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
|
|
9918
|
+
echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
|
|
9919
|
+
exit 0
|
|
9920
|
+
fi
|
|
9921
|
+
echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
|
|
9922
|
+
echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
|
|
9923
|
+
echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
|
|
9924
|
+
exit 1
|
|
8869
9925
|
fi
|
|
8870
9926
|
|
|
8871
9927
|
if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
|
|
@@ -8880,26 +9936,69 @@ function gitDirectory(cwd) {
|
|
|
8880
9936
|
const dotGit = path16.join(cwd, ".git");
|
|
8881
9937
|
let stats;
|
|
8882
9938
|
try {
|
|
8883
|
-
stats =
|
|
9939
|
+
stats = fs15.statSync(dotGit);
|
|
8884
9940
|
} catch {
|
|
8885
9941
|
return null;
|
|
8886
9942
|
}
|
|
8887
9943
|
if (stats.isDirectory()) return dotGit;
|
|
8888
9944
|
if (!stats.isFile()) return null;
|
|
8889
9945
|
try {
|
|
8890
|
-
const contents =
|
|
9946
|
+
const contents = fs15.readFileSync(dotGit, "utf8");
|
|
8891
9947
|
const match = /^gitdir:\s*(.+)$/m.exec(contents);
|
|
8892
9948
|
if (!match) return null;
|
|
8893
9949
|
const target = match[1];
|
|
8894
9950
|
const resolved = path16.isAbsolute(target.trim()) ? target.trim() : path16.join(cwd, target.trim());
|
|
8895
|
-
|
|
9951
|
+
if (!fs15.statSync(resolved).isDirectory()) return null;
|
|
9952
|
+
if (isInside2(path16.resolve(cwd), path16.resolve(resolved))) return resolved;
|
|
9953
|
+
return isRegisteredWorktree(path16.resolve(resolved), cwd) ? resolved : null;
|
|
9954
|
+
} catch {
|
|
9955
|
+
return null;
|
|
9956
|
+
}
|
|
9957
|
+
}
|
|
9958
|
+
function isInside2(parent, child) {
|
|
9959
|
+
const relative10 = path16.relative(parent, child);
|
|
9960
|
+
return relative10 === "" || !relative10.startsWith("..") && !path16.isAbsolute(relative10);
|
|
9961
|
+
}
|
|
9962
|
+
function isRegisteredWorktree(gitDir, cwd) {
|
|
9963
|
+
try {
|
|
9964
|
+
const back = fs15.readFileSync(path16.join(gitDir, "gitdir"), "utf8").trim();
|
|
9965
|
+
return path16.resolve(gitDir, back) === path16.join(path16.resolve(cwd), ".git");
|
|
9966
|
+
} catch {
|
|
9967
|
+
return false;
|
|
9968
|
+
}
|
|
9969
|
+
}
|
|
9970
|
+
function gitOutput(cwd, args) {
|
|
9971
|
+
try {
|
|
9972
|
+
const output = childProcess.execFileSync("git", args, {
|
|
9973
|
+
cwd,
|
|
9974
|
+
encoding: "utf8",
|
|
9975
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
9976
|
+
});
|
|
9977
|
+
const trimmed = output.trim();
|
|
9978
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
8896
9979
|
} catch {
|
|
8897
9980
|
return null;
|
|
8898
9981
|
}
|
|
8899
9982
|
}
|
|
9983
|
+
function configuredHooksDirectory(cwd) {
|
|
9984
|
+
const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
|
|
9985
|
+
if (hooks === null) return null;
|
|
9986
|
+
const resolved = path16.resolve(cwd, hooks);
|
|
9987
|
+
const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
|
|
9988
|
+
const commonDir = common === null ? null : path16.resolve(cwd, common);
|
|
9989
|
+
if (isInside2(path16.resolve(cwd), resolved)) return { dir: resolved };
|
|
9990
|
+
if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
|
|
9991
|
+
return {
|
|
9992
|
+
refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
|
|
9993
|
+
};
|
|
9994
|
+
}
|
|
8900
9995
|
function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
8901
|
-
const
|
|
8902
|
-
if (
|
|
9996
|
+
const configured = configuredHooksDirectory(cwd);
|
|
9997
|
+
if (configured !== null && "refusal" in configured) {
|
|
9998
|
+
return { path: null, written: false, notes: [configured.refusal] };
|
|
9999
|
+
}
|
|
10000
|
+
const gitDir = configured === null ? gitDirectory(cwd) : null;
|
|
10001
|
+
if (configured === null && gitDir === null) {
|
|
8903
10002
|
return {
|
|
8904
10003
|
path: null,
|
|
8905
10004
|
written: false,
|
|
@@ -8908,10 +10007,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8908
10007
|
]
|
|
8909
10008
|
};
|
|
8910
10009
|
}
|
|
8911
|
-
const hooksDir = path16.join(gitDir, "hooks");
|
|
10010
|
+
const hooksDir = configured === null ? path16.join(gitDir, "hooks") : configured.dir;
|
|
8912
10011
|
const hookPath = path16.join(hooksDir, "pre-commit");
|
|
8913
10012
|
try {
|
|
8914
|
-
|
|
10013
|
+
fs15.mkdirSync(hooksDir, { recursive: true });
|
|
8915
10014
|
} catch (err) {
|
|
8916
10015
|
return {
|
|
8917
10016
|
path: hookPath,
|
|
@@ -8921,7 +10020,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8921
10020
|
}
|
|
8922
10021
|
let existing = null;
|
|
8923
10022
|
try {
|
|
8924
|
-
existing =
|
|
10023
|
+
existing = fs15.readFileSync(hookPath, "utf8");
|
|
8925
10024
|
} catch {
|
|
8926
10025
|
existing = null;
|
|
8927
10026
|
}
|
|
@@ -8936,8 +10035,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8936
10035
|
};
|
|
8937
10036
|
}
|
|
8938
10037
|
try {
|
|
8939
|
-
|
|
8940
|
-
|
|
10038
|
+
fs15.writeFileSync(hookPath, hookScript(outDir), "utf8");
|
|
10039
|
+
fs15.chmodSync(hookPath, 493);
|
|
8941
10040
|
} catch (err) {
|
|
8942
10041
|
return {
|
|
8943
10042
|
path: hookPath,
|
|
@@ -8994,14 +10093,14 @@ const { parentPort, workerData } = require("node:worker_threads");
|
|
|
8994
10093
|
})();
|
|
8995
10094
|
`;
|
|
8996
10095
|
function generateInWorker(cwd, cliOptions) {
|
|
8997
|
-
return new Promise((
|
|
10096
|
+
return new Promise((resolve7) => {
|
|
8998
10097
|
let settled = false;
|
|
8999
10098
|
let worker = null;
|
|
9000
10099
|
const finish = (result) => {
|
|
9001
10100
|
if (settled) return;
|
|
9002
10101
|
settled = true;
|
|
9003
10102
|
if (worker !== null) void worker.terminate();
|
|
9004
|
-
|
|
10103
|
+
resolve7(result);
|
|
9005
10104
|
};
|
|
9006
10105
|
const isCjs = typeof __dirname !== "undefined";
|
|
9007
10106
|
const directory = isCjs ? __dirname : path16.dirname(fileURLToPath(import.meta.url));
|
|
@@ -9034,7 +10133,6 @@ function generateInWorker(cwd, cliOptions) {
|
|
|
9034
10133
|
}
|
|
9035
10134
|
|
|
9036
10135
|
// src/index.ts
|
|
9037
|
-
var SCHEMA_VERSION = "3.0.0";
|
|
9038
10136
|
var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
|
|
9039
10137
|
var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
|
|
9040
10138
|
var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
@@ -9042,12 +10140,21 @@ var fileDerivationBytes = 0;
|
|
|
9042
10140
|
function takeDerivation(path17, hash, settings) {
|
|
9043
10141
|
const cached = FILE_DERIVATIONS.get(path17);
|
|
9044
10142
|
if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
|
|
10143
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10144
|
+
FILE_DERIVATIONS.set(path17, cached);
|
|
9045
10145
|
return cached;
|
|
9046
10146
|
}
|
|
9047
10147
|
function rememberDerivation(path17, hash, settings, derivation) {
|
|
9048
10148
|
const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
|
|
9049
10149
|
const bytes = bodyBytes * 2 + 512;
|
|
9050
10150
|
if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
|
|
10151
|
+
const previous = FILE_DERIVATIONS.get(path17);
|
|
10152
|
+
if (previous !== void 0) {
|
|
10153
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10154
|
+
fileDerivationBytes -= previous.bytes;
|
|
10155
|
+
} else {
|
|
10156
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10157
|
+
}
|
|
9051
10158
|
while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
|
|
9052
10159
|
const oldest = FILE_DERIVATIONS.keys().next();
|
|
9053
10160
|
if (oldest.done === true) break;
|
|
@@ -9068,11 +10175,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9068
10175
|
const lineCount = countLines(rawContent);
|
|
9069
10176
|
const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
|
|
9070
10177
|
const isLarge = sizeBytes > config.largeFileBytes;
|
|
10178
|
+
const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
|
|
9071
10179
|
let finalContent = redacted;
|
|
9072
10180
|
let isPreviewTruncated = false;
|
|
9073
10181
|
let includedLines = lineCount;
|
|
9074
10182
|
let inclusionMode = "full";
|
|
9075
|
-
if (config.skeleton === true && isSkeletonizable(relativePath)) {
|
|
10183
|
+
if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
|
|
9076
10184
|
const skeleton = skeletonizeTypeScript(redacted, relativePath);
|
|
9077
10185
|
if (skeleton.collapsed > 0) {
|
|
9078
10186
|
finalContent = skeleton.text;
|
|
@@ -9092,7 +10200,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9092
10200
|
let summarySkip = null;
|
|
9093
10201
|
let summaryWarning = null;
|
|
9094
10202
|
let dependentImports = null;
|
|
9095
|
-
if (
|
|
10203
|
+
if (oversizeForSummary) {
|
|
9096
10204
|
summarySkip = "oversize";
|
|
9097
10205
|
dependentImports = [];
|
|
9098
10206
|
} else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
|
|
@@ -9179,8 +10287,8 @@ function retain(items, keep) {
|
|
|
9179
10287
|
}
|
|
9180
10288
|
items.length = write;
|
|
9181
10289
|
}
|
|
9182
|
-
function buildIndexes(files) {
|
|
9183
|
-
const resolver = buildImportResolver(files);
|
|
10290
|
+
function buildIndexes(files, tsconfigPaths) {
|
|
10291
|
+
const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
|
|
9184
10292
|
const importerCounts = /* @__PURE__ */ new Map();
|
|
9185
10293
|
const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
|
|
9186
10294
|
const summary = file.summary;
|
|
@@ -9323,20 +10431,20 @@ function listEntries(dir) {
|
|
|
9323
10431
|
const walk = (absolute, prefix) => {
|
|
9324
10432
|
let children;
|
|
9325
10433
|
try {
|
|
9326
|
-
children =
|
|
10434
|
+
children = fs15.readdirSync(absolute, { withFileTypes: true });
|
|
9327
10435
|
} catch {
|
|
9328
10436
|
return;
|
|
9329
10437
|
}
|
|
9330
10438
|
for (const child of children) {
|
|
9331
|
-
const
|
|
9332
|
-
entries.push(
|
|
9333
|
-
if (child.isDirectory()) walk(path16.join(absolute, child.name),
|
|
10439
|
+
const relative10 = prefix === "" ? child.name : `${prefix}/${child.name}`;
|
|
10440
|
+
entries.push(relative10);
|
|
10441
|
+
if (child.isDirectory()) walk(path16.join(absolute, child.name), relative10);
|
|
9334
10442
|
}
|
|
9335
10443
|
};
|
|
9336
10444
|
walk(dir, "");
|
|
9337
10445
|
return entries.sort();
|
|
9338
10446
|
}
|
|
9339
|
-
function markerInventory(dir) {
|
|
10447
|
+
function markerInventory(dir, written) {
|
|
9340
10448
|
const entries = listEntries(dir);
|
|
9341
10449
|
const files = [];
|
|
9342
10450
|
for (const entry of entries) {
|
|
@@ -9345,14 +10453,19 @@ function markerInventory(dir) {
|
|
|
9345
10453
|
const full = path16.join(dir, ...entry.split("/"));
|
|
9346
10454
|
let stats;
|
|
9347
10455
|
try {
|
|
9348
|
-
stats =
|
|
10456
|
+
stats = fs15.lstatSync(full);
|
|
9349
10457
|
} catch {
|
|
9350
10458
|
continue;
|
|
9351
10459
|
}
|
|
9352
10460
|
if (!stats.isFile()) continue;
|
|
10461
|
+
const recorded = written?.get(entry);
|
|
10462
|
+
if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
|
|
10463
|
+
files.push(recorded.digest);
|
|
10464
|
+
continue;
|
|
10465
|
+
}
|
|
9353
10466
|
let digest;
|
|
9354
10467
|
try {
|
|
9355
|
-
digest = sha256Hex2(
|
|
10468
|
+
digest = sha256Hex2(fs15.readFileSync(full));
|
|
9356
10469
|
} catch {
|
|
9357
10470
|
continue;
|
|
9358
10471
|
}
|
|
@@ -9360,8 +10473,8 @@ function markerInventory(dir) {
|
|
|
9360
10473
|
}
|
|
9361
10474
|
return { entries, files };
|
|
9362
10475
|
}
|
|
9363
|
-
function markerPayload(dir, state, id, createdAt) {
|
|
9364
|
-
const { entries, files } = markerInventory(dir);
|
|
10476
|
+
function markerPayload(dir, state, id, createdAt, written) {
|
|
10477
|
+
const { entries, files } = markerInventory(dir, written);
|
|
9365
10478
|
const marker2 = {
|
|
9366
10479
|
generator: GENERATOR_NAME,
|
|
9367
10480
|
version: GENERATOR_VERSION,
|
|
@@ -9374,13 +10487,13 @@ function markerPayload(dir, state, id, createdAt) {
|
|
|
9374
10487
|
files
|
|
9375
10488
|
};
|
|
9376
10489
|
const manifestPath = path16.join(dir, "manifest.json");
|
|
9377
|
-
if (
|
|
9378
|
-
marker2.manifestSha256 = sha256Hex2(
|
|
10490
|
+
if (fs15.existsSync(manifestPath)) {
|
|
10491
|
+
marker2.manifestSha256 = sha256Hex2(fs15.readFileSync(manifestPath));
|
|
9379
10492
|
}
|
|
9380
10493
|
return marker2;
|
|
9381
10494
|
}
|
|
9382
10495
|
function writeOwnershipMarker(dir, marker2) {
|
|
9383
|
-
|
|
10496
|
+
fs15.writeFileSync(
|
|
9384
10497
|
path16.join(dir, OWNERSHIP_MARKER),
|
|
9385
10498
|
`${JSON.stringify(marker2, null, 2)}
|
|
9386
10499
|
`,
|
|
@@ -9394,12 +10507,12 @@ function markerBelongsTo(dir, id) {
|
|
|
9394
10507
|
}
|
|
9395
10508
|
function readOwnershipMarker(dir) {
|
|
9396
10509
|
const markerPath = path16.join(dir, OWNERSHIP_MARKER);
|
|
9397
|
-
if (!
|
|
10510
|
+
if (!fs15.existsSync(markerPath)) {
|
|
9398
10511
|
return { marker: null, problem: "it holds no .codebase-snapshot marker" };
|
|
9399
10512
|
}
|
|
9400
10513
|
let raw;
|
|
9401
10514
|
try {
|
|
9402
|
-
raw =
|
|
10515
|
+
raw = fs15.readFileSync(markerPath, "utf8");
|
|
9403
10516
|
} catch {
|
|
9404
10517
|
return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
|
|
9405
10518
|
}
|
|
@@ -9502,7 +10615,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9502
10615
|
const full = path16.join(dir, ...entry.split("/"));
|
|
9503
10616
|
let stats;
|
|
9504
10617
|
try {
|
|
9505
|
-
stats =
|
|
10618
|
+
stats = fs15.lstatSync(full);
|
|
9506
10619
|
} catch {
|
|
9507
10620
|
return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
|
|
9508
10621
|
}
|
|
@@ -9527,7 +10640,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9527
10640
|
}
|
|
9528
10641
|
let digest;
|
|
9529
10642
|
try {
|
|
9530
|
-
digest = sha256Hex2(
|
|
10643
|
+
digest = sha256Hex2(fs15.readFileSync(full));
|
|
9531
10644
|
} catch {
|
|
9532
10645
|
return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
|
|
9533
10646
|
}
|
|
@@ -9549,11 +10662,11 @@ function assessSnapshotDirectory(dir) {
|
|
|
9549
10662
|
};
|
|
9550
10663
|
}
|
|
9551
10664
|
const manifestPath = path16.join(dir, "manifest.json");
|
|
9552
|
-
const hasManifest =
|
|
10665
|
+
const hasManifest = fs15.existsSync(manifestPath);
|
|
9553
10666
|
if (hasManifest) {
|
|
9554
10667
|
let raw;
|
|
9555
10668
|
try {
|
|
9556
|
-
raw =
|
|
10669
|
+
raw = fs15.readFileSync(manifestPath, "utf8");
|
|
9557
10670
|
} catch {
|
|
9558
10671
|
return {
|
|
9559
10672
|
owned: false,
|
|
@@ -9648,7 +10761,7 @@ function containsNoFiles(dir) {
|
|
|
9648
10761
|
const current = pending.pop();
|
|
9649
10762
|
let entries;
|
|
9650
10763
|
try {
|
|
9651
|
-
entries =
|
|
10764
|
+
entries = fs15.readdirSync(current, { withFileTypes: true });
|
|
9652
10765
|
} catch {
|
|
9653
10766
|
return false;
|
|
9654
10767
|
}
|
|
@@ -9663,13 +10776,13 @@ function containsNoFiles(dir) {
|
|
|
9663
10776
|
return true;
|
|
9664
10777
|
}
|
|
9665
10778
|
function assertReplaceable(target, label, secretRules) {
|
|
9666
|
-
if (!
|
|
9667
|
-
if (!
|
|
10779
|
+
if (!fs15.existsSync(target)) return;
|
|
10780
|
+
if (!fs15.statSync(target).isDirectory()) {
|
|
9668
10781
|
throw new Error(
|
|
9669
10782
|
`Refusing to write into ${label} ${target}: it exists but is not a directory.`
|
|
9670
10783
|
);
|
|
9671
10784
|
}
|
|
9672
|
-
const entries =
|
|
10785
|
+
const entries = fs15.readdirSync(target);
|
|
9673
10786
|
if (entries.length === 0) return;
|
|
9674
10787
|
if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
|
|
9675
10788
|
if (containsNoFiles(target)) return;
|
|
@@ -9689,18 +10802,18 @@ function assertReplaceable(target, label, secretRules) {
|
|
|
9689
10802
|
);
|
|
9690
10803
|
}
|
|
9691
10804
|
function assertStagingRootUsable(tmpDir, secretRules) {
|
|
9692
|
-
if (!
|
|
9693
|
-
if (!
|
|
10805
|
+
if (!fs15.existsSync(tmpDir)) return;
|
|
10806
|
+
if (!fs15.statSync(tmpDir).isDirectory()) {
|
|
9694
10807
|
throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
|
|
9695
10808
|
}
|
|
9696
|
-
const entries =
|
|
10809
|
+
const entries = fs15.readdirSync(tmpDir);
|
|
9697
10810
|
if (entries.length === 0) return;
|
|
9698
10811
|
const foreign = entries.filter((name) => {
|
|
9699
10812
|
const full = path16.join(tmpDir, name);
|
|
9700
10813
|
if (!name.startsWith(RUN_DIR_PREFIX)) return true;
|
|
9701
10814
|
let stats;
|
|
9702
10815
|
try {
|
|
9703
|
-
stats =
|
|
10816
|
+
stats = fs15.statSync(full);
|
|
9704
10817
|
} catch {
|
|
9705
10818
|
return true;
|
|
9706
10819
|
}
|
|
@@ -9708,7 +10821,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9708
10821
|
const { marker: marker2 } = readOwnershipMarker(full);
|
|
9709
10822
|
if (marker2) return false;
|
|
9710
10823
|
try {
|
|
9711
|
-
return
|
|
10824
|
+
return fs15.readdirSync(full).length > 0;
|
|
9712
10825
|
} catch {
|
|
9713
10826
|
return true;
|
|
9714
10827
|
}
|
|
@@ -9723,7 +10836,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9723
10836
|
function cleanStaleRunDirs(tmpDir) {
|
|
9724
10837
|
let entries;
|
|
9725
10838
|
try {
|
|
9726
|
-
entries =
|
|
10839
|
+
entries = fs15.readdirSync(tmpDir);
|
|
9727
10840
|
} catch {
|
|
9728
10841
|
return;
|
|
9729
10842
|
}
|
|
@@ -9737,58 +10850,101 @@ function cleanStaleRunDirs(tmpDir) {
|
|
|
9737
10850
|
const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
|
|
9738
10851
|
if (aged || abandoned) {
|
|
9739
10852
|
try {
|
|
9740
|
-
|
|
10853
|
+
fs15.rmSync(full, { recursive: true, force: true });
|
|
9741
10854
|
} catch {
|
|
9742
10855
|
}
|
|
9743
10856
|
}
|
|
9744
10857
|
continue;
|
|
9745
10858
|
}
|
|
9746
10859
|
try {
|
|
9747
|
-
if (
|
|
10860
|
+
if (fs15.readdirSync(full).length === 0) fs15.rmSync(full, { recursive: true, force: true });
|
|
9748
10861
|
} catch {
|
|
9749
10862
|
}
|
|
9750
10863
|
}
|
|
9751
10864
|
}
|
|
9752
10865
|
function removeIfEmpty(dir) {
|
|
9753
10866
|
try {
|
|
9754
|
-
if (
|
|
10867
|
+
if (fs15.readdirSync(dir).length === 0) fs15.rmSync(dir, { recursive: true, force: true });
|
|
9755
10868
|
} catch {
|
|
9756
10869
|
}
|
|
9757
10870
|
}
|
|
9758
10871
|
function ensureParentDirectory(target, label) {
|
|
9759
10872
|
const parent = path16.dirname(target);
|
|
9760
|
-
if (
|
|
10873
|
+
if (fs15.existsSync(parent) && !fs15.statSync(parent).isDirectory()) {
|
|
9761
10874
|
throw new Error(
|
|
9762
10875
|
`Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
|
|
9763
10876
|
);
|
|
9764
10877
|
}
|
|
9765
10878
|
try {
|
|
9766
|
-
|
|
10879
|
+
fs15.mkdirSync(parent, { recursive: true });
|
|
9767
10880
|
} catch (err) {
|
|
9768
10881
|
throw new Error(
|
|
9769
10882
|
`Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
|
|
9770
10883
|
);
|
|
9771
10884
|
}
|
|
9772
10885
|
}
|
|
10886
|
+
var LOCK_HEARTBEAT_MS = 5e3;
|
|
10887
|
+
var LOCK_STALE_HEARTBEAT_MS = 12e4;
|
|
10888
|
+
var LOCK_HEARTBEAT_SOURCE = `
|
|
10889
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
10890
|
+
const fs = require("node:fs");
|
|
10891
|
+
const { lockPath, intervalMs } = workerData;
|
|
10892
|
+
const timer = setInterval(() => {
|
|
10893
|
+
try {
|
|
10894
|
+
const now = new Date();
|
|
10895
|
+
fs.utimesSync(lockPath, now, now);
|
|
10896
|
+
} catch (err) {
|
|
10897
|
+
// The lock was reclaimed or removed; nothing left to keep alive.
|
|
10898
|
+
}
|
|
10899
|
+
}, intervalMs);
|
|
10900
|
+
timer.unref();
|
|
10901
|
+
if (parentPort) {
|
|
10902
|
+
parentPort.on("message", (message) => {
|
|
10903
|
+
if (message === "stop") {
|
|
10904
|
+
clearInterval(timer);
|
|
10905
|
+
process.exit(0);
|
|
10906
|
+
}
|
|
10907
|
+
});
|
|
10908
|
+
}
|
|
10909
|
+
`;
|
|
10910
|
+
function startLockHeartbeat(lockPath) {
|
|
10911
|
+
try {
|
|
10912
|
+
const worker = new Worker(LOCK_HEARTBEAT_SOURCE, {
|
|
10913
|
+
eval: true,
|
|
10914
|
+
workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
|
|
10915
|
+
});
|
|
10916
|
+
worker.unref();
|
|
10917
|
+
return () => {
|
|
10918
|
+
void worker.terminate().catch(() => void 0);
|
|
10919
|
+
};
|
|
10920
|
+
} catch {
|
|
10921
|
+
return () => void 0;
|
|
10922
|
+
}
|
|
10923
|
+
}
|
|
9773
10924
|
function acquireRunLock(stagingRoot) {
|
|
9774
10925
|
const lockPath = lockPathFor(stagingRoot);
|
|
9775
10926
|
const payload = `${JSON.stringify({
|
|
9776
10927
|
pid: process.pid,
|
|
9777
10928
|
stagingRoot,
|
|
10929
|
+
host: os.hostname(),
|
|
10930
|
+
runId: crypto2.randomUUID(),
|
|
10931
|
+
heartbeatMs: LOCK_HEARTBEAT_MS,
|
|
9778
10932
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
9779
10933
|
})}
|
|
9780
10934
|
`;
|
|
9781
10935
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9782
10936
|
try {
|
|
9783
|
-
const handle =
|
|
10937
|
+
const handle = fs15.openSync(lockPath, "wx");
|
|
9784
10938
|
try {
|
|
9785
|
-
|
|
10939
|
+
fs15.writeSync(handle, payload);
|
|
9786
10940
|
} finally {
|
|
9787
|
-
|
|
10941
|
+
fs15.closeSync(handle);
|
|
9788
10942
|
}
|
|
10943
|
+
const stopHeartbeat = startLockHeartbeat(lockPath);
|
|
9789
10944
|
return () => {
|
|
10945
|
+
stopHeartbeat();
|
|
9790
10946
|
try {
|
|
9791
|
-
|
|
10947
|
+
fs15.rmSync(lockPath, { force: true });
|
|
9792
10948
|
} catch {
|
|
9793
10949
|
}
|
|
9794
10950
|
};
|
|
@@ -9796,7 +10952,7 @@ function acquireRunLock(stagingRoot) {
|
|
|
9796
10952
|
if (err.code !== "EEXIST") throw err;
|
|
9797
10953
|
if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
|
|
9798
10954
|
throw new Error(
|
|
9799
|
-
`Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete
|
|
10955
|
+
`Another generate run is already using the staging directory ${stagingRoot} (lock ${lockPath}, heartbeat ${Math.round(lockHeartbeatAgeMs(lockPath) / 1e3)}s old). Wait for it to finish, or delete the lock if no other run is active.`
|
|
9800
10956
|
);
|
|
9801
10957
|
}
|
|
9802
10958
|
}
|
|
@@ -9813,7 +10969,7 @@ function canonicalLockTarget(targetPath) {
|
|
|
9813
10969
|
const tail = [];
|
|
9814
10970
|
for (; ; ) {
|
|
9815
10971
|
try {
|
|
9816
|
-
return path16.join(
|
|
10972
|
+
return path16.join(fs15.realpathSync(existing), ...tail);
|
|
9817
10973
|
} catch {
|
|
9818
10974
|
const parent = path16.dirname(existing);
|
|
9819
10975
|
if (parent === existing) return resolved;
|
|
@@ -9825,10 +10981,17 @@ function canonicalLockTarget(targetPath) {
|
|
|
9825
10981
|
function lockPathFor(stagingRoot) {
|
|
9826
10982
|
return path16.join(os.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
|
|
9827
10983
|
}
|
|
10984
|
+
function lockHeartbeatAgeMs(lockPath) {
|
|
10985
|
+
try {
|
|
10986
|
+
return Date.now() - fs15.statSync(lockPath).mtimeMs;
|
|
10987
|
+
} catch {
|
|
10988
|
+
return Number.POSITIVE_INFINITY;
|
|
10989
|
+
}
|
|
10990
|
+
}
|
|
9828
10991
|
function lockOwnerIsGone(lockPath) {
|
|
9829
10992
|
let raw;
|
|
9830
10993
|
try {
|
|
9831
|
-
raw =
|
|
10994
|
+
raw = fs15.readFileSync(lockPath, "utf8");
|
|
9832
10995
|
} catch {
|
|
9833
10996
|
return false;
|
|
9834
10997
|
}
|
|
@@ -9841,96 +11004,120 @@ function lockOwnerIsGone(lockPath) {
|
|
|
9841
11004
|
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
|
|
9842
11005
|
try {
|
|
9843
11006
|
process.kill(pid, 0);
|
|
9844
|
-
return
|
|
11007
|
+
return lockFileIsAncient(lockPath);
|
|
9845
11008
|
} catch (err) {
|
|
9846
|
-
|
|
11009
|
+
if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
|
|
11010
|
+
return true;
|
|
9847
11011
|
}
|
|
9848
11012
|
}
|
|
9849
11013
|
function reclaimStaleLock(lockPath) {
|
|
9850
11014
|
let before;
|
|
9851
11015
|
try {
|
|
9852
|
-
before =
|
|
11016
|
+
before = fs15.statSync(lockPath);
|
|
9853
11017
|
} catch {
|
|
9854
11018
|
return true;
|
|
9855
11019
|
}
|
|
9856
11020
|
if (!lockOwnerIsGone(lockPath)) return false;
|
|
9857
11021
|
try {
|
|
9858
|
-
const current =
|
|
11022
|
+
const current = fs15.statSync(lockPath);
|
|
9859
11023
|
const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
|
|
9860
11024
|
if (!sameFile) return false;
|
|
9861
|
-
|
|
11025
|
+
fs15.rmSync(lockPath, { force: true });
|
|
9862
11026
|
return true;
|
|
9863
11027
|
} catch {
|
|
9864
11028
|
return false;
|
|
9865
11029
|
}
|
|
9866
11030
|
}
|
|
9867
11031
|
function lockFileIsAncient(lockPath) {
|
|
9868
|
-
|
|
9869
|
-
return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
|
|
9870
|
-
} catch {
|
|
9871
|
-
return false;
|
|
9872
|
-
}
|
|
11032
|
+
return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
|
|
9873
11033
|
}
|
|
9874
11034
|
function writeManifestAtomically(manifestPath, manifest) {
|
|
9875
11035
|
const tempPath = `${manifestPath}.${process.pid}.tmp`;
|
|
9876
|
-
|
|
11036
|
+
fs15.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
|
|
9877
11037
|
try {
|
|
9878
|
-
|
|
11038
|
+
fs15.renameSync(tempPath, manifestPath);
|
|
9879
11039
|
} catch (err) {
|
|
9880
11040
|
try {
|
|
9881
|
-
|
|
11041
|
+
fs15.rmSync(tempPath, { force: true });
|
|
9882
11042
|
} catch {
|
|
9883
11043
|
}
|
|
9884
11044
|
throw err;
|
|
9885
11045
|
}
|
|
9886
11046
|
}
|
|
9887
|
-
function swapIntoPlace(stagingDir, outDir) {
|
|
11047
|
+
function swapIntoPlace(stagingDir, outDir, beforeSwap) {
|
|
9888
11048
|
ensureParentDirectory(outDir, "outDir");
|
|
9889
11049
|
const deadline = Date.now() + 3e3;
|
|
9890
|
-
|
|
11050
|
+
let delay = 25;
|
|
11051
|
+
for (; ; ) {
|
|
9891
11052
|
try {
|
|
9892
|
-
swapOnce(stagingDir, outDir);
|
|
11053
|
+
swapOnce(stagingDir, outDir, beforeSwap);
|
|
9893
11054
|
return;
|
|
9894
11055
|
} catch (err) {
|
|
9895
11056
|
const code = err.code;
|
|
9896
|
-
const
|
|
9897
|
-
|
|
9898
|
-
|
|
11057
|
+
const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
|
|
11058
|
+
const remaining = deadline - Date.now();
|
|
11059
|
+
if (!retryable || remaining <= 0) throw err;
|
|
11060
|
+
sleepSync(Math.min(delay, remaining));
|
|
11061
|
+
delay = Math.min(delay * 2, 400);
|
|
9899
11062
|
}
|
|
9900
11063
|
}
|
|
9901
11064
|
}
|
|
9902
|
-
function
|
|
11065
|
+
function recoverInterruptedPublish(outDir) {
|
|
11066
|
+
if (fs15.existsSync(outDir)) return;
|
|
11067
|
+
const parent = path16.dirname(outDir);
|
|
11068
|
+
const base = path16.basename(outDir);
|
|
11069
|
+
let backups;
|
|
11070
|
+
try {
|
|
11071
|
+
backups = fs15.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
|
|
11072
|
+
} catch {
|
|
11073
|
+
return;
|
|
11074
|
+
}
|
|
11075
|
+
if (backups.length !== 1) return;
|
|
11076
|
+
const backupDir = path16.join(parent, backups[0]);
|
|
11077
|
+
const { marker: marker2, problem } = readOwnershipMarker(backupDir);
|
|
11078
|
+
if (problem !== null || marker2 === null || marker2.state !== "complete") return;
|
|
11079
|
+
try {
|
|
11080
|
+
fs15.renameSync(backupDir, outDir);
|
|
11081
|
+
process.stderr.write(
|
|
11082
|
+
`\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
|
|
11083
|
+
`
|
|
11084
|
+
);
|
|
11085
|
+
} catch {
|
|
11086
|
+
}
|
|
11087
|
+
}
|
|
11088
|
+
function swapOnce(stagingDir, outDir, beforeSwap) {
|
|
9903
11089
|
const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
|
|
9904
|
-
const hadPrevious =
|
|
9905
|
-
if (hadPrevious)
|
|
11090
|
+
const hadPrevious = fs15.existsSync(outDir);
|
|
11091
|
+
if (hadPrevious) beforeSwap?.();
|
|
11092
|
+
if (hadPrevious) fs15.renameSync(outDir, backupDir);
|
|
9906
11093
|
try {
|
|
9907
11094
|
try {
|
|
9908
|
-
|
|
11095
|
+
fs15.renameSync(stagingDir, outDir);
|
|
9909
11096
|
} catch (err) {
|
|
9910
11097
|
if (err.code !== "EXDEV") throw err;
|
|
9911
11098
|
const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
|
|
9912
11099
|
try {
|
|
9913
|
-
|
|
9914
|
-
|
|
9915
|
-
|
|
11100
|
+
fs15.cpSync(stagingDir, partialDir, { recursive: true });
|
|
11101
|
+
fs15.renameSync(partialDir, outDir);
|
|
11102
|
+
fs15.rmSync(stagingDir, { recursive: true, force: true });
|
|
9916
11103
|
} catch (copyErr) {
|
|
9917
11104
|
try {
|
|
9918
|
-
|
|
11105
|
+
fs15.rmSync(partialDir, { recursive: true, force: true });
|
|
9919
11106
|
} catch {
|
|
9920
11107
|
}
|
|
9921
11108
|
throw copyErr;
|
|
9922
11109
|
}
|
|
9923
11110
|
}
|
|
9924
11111
|
} catch (err) {
|
|
9925
|
-
if (hadPrevious &&
|
|
9926
|
-
if (
|
|
9927
|
-
|
|
11112
|
+
if (hadPrevious && fs15.existsSync(backupDir)) {
|
|
11113
|
+
if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
|
|
11114
|
+
fs15.renameSync(backupDir, outDir);
|
|
9928
11115
|
}
|
|
9929
11116
|
throw err;
|
|
9930
11117
|
}
|
|
9931
11118
|
if (hadPrevious) {
|
|
9932
11119
|
try {
|
|
9933
|
-
|
|
11120
|
+
fs15.rmSync(backupDir, { recursive: true, force: true });
|
|
9934
11121
|
} catch (err) {
|
|
9935
11122
|
process.stderr.write(
|
|
9936
11123
|
`\u26A0 The previous snapshot could not be removed from ${backupDir} (${err.message}). The new snapshot is in place; delete that directory by hand when convenient.
|
|
@@ -10007,6 +11194,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10007
11194
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
|
|
10008
11195
|
const dryRun = options?.dryRun ?? false;
|
|
10009
11196
|
const gitInfo = getGitInfo(config.cwd, config.branch);
|
|
11197
|
+
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
11198
|
+
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
11199
|
+
...config.staged === true ? { staged: true } : {}
|
|
11200
|
+
}) : null;
|
|
11201
|
+
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
11202
|
+
const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
|
|
11203
|
+
const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
|
|
10010
11204
|
const collection = collectFiles(config.cwd, {
|
|
10011
11205
|
includePatterns: config.include,
|
|
10012
11206
|
excludePatterns: [...config.excludePatterns, ...config.presetExclude],
|
|
@@ -10018,13 +11212,11 @@ function generateSnapshot(configInput, options) {
|
|
|
10018
11212
|
// output — but only at these exact paths, not at every directory that shares the name.
|
|
10019
11213
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
10020
11214
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
10021
|
-
).filter((
|
|
11215
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith("..")),
|
|
11216
|
+
// A staged path can be absent from the working tree while its index blob exists. Discovery
|
|
11217
|
+
// lists the working tree, so those paths would never reach the scan at all.
|
|
11218
|
+
...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
|
|
10022
11219
|
});
|
|
10023
|
-
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
10024
|
-
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
10025
|
-
...config.staged === true ? { staged: true } : {}
|
|
10026
|
-
}) : null;
|
|
10027
|
-
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
10028
11220
|
const unchangedPaths = [];
|
|
10029
11221
|
const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
|
|
10030
11222
|
if (changedPaths.has(relativePath)) return true;
|
|
@@ -10046,45 +11238,92 @@ function generateSnapshot(configInput, options) {
|
|
|
10046
11238
|
const oversizeSummaryPaths = [];
|
|
10047
11239
|
const previewSummaryPaths = [];
|
|
10048
11240
|
const skippedSummaryImports = /* @__PURE__ */ new Map();
|
|
10049
|
-
const layerCounts =
|
|
10050
|
-
const kindCounts =
|
|
11241
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
11242
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
10051
11243
|
let totalLines = 0;
|
|
10052
11244
|
let totalSizeBytes = 0;
|
|
10053
11245
|
let largeFileCount = 0;
|
|
10054
11246
|
for (const relativePath of candidateFiles) {
|
|
10055
11247
|
const absolutePath = path16.join(config.cwd, relativePath);
|
|
10056
|
-
|
|
10057
|
-
|
|
10058
|
-
|
|
10059
|
-
|
|
10060
|
-
|
|
10061
|
-
|
|
10062
|
-
|
|
11248
|
+
const fromIndex = stagedPaths.has(relativePath);
|
|
11249
|
+
let buffer;
|
|
11250
|
+
let sizeBytes;
|
|
11251
|
+
if (fromIndex && stagedDeletedPaths.has(relativePath)) {
|
|
11252
|
+
skipped.push({
|
|
11253
|
+
path: relativePath,
|
|
11254
|
+
reason: "deleted",
|
|
11255
|
+
detail: "staged for deletion; it is not part of the next commit"
|
|
11256
|
+
});
|
|
11257
|
+
continue;
|
|
11258
|
+
}
|
|
11259
|
+
if (fromIndex) {
|
|
11260
|
+
const staged = readStagedBlob(config.cwd, relativePath);
|
|
11261
|
+
if (staged === null) {
|
|
11262
|
+
skipped.push({
|
|
11263
|
+
path: relativePath,
|
|
11264
|
+
reason: "deleted",
|
|
11265
|
+
detail: "staged path has no blob in the index; it is not part of the next commit"
|
|
11266
|
+
});
|
|
11267
|
+
continue;
|
|
11268
|
+
}
|
|
11269
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11270
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
|
|
11271
|
+
continue;
|
|
11272
|
+
}
|
|
11273
|
+
buffer = staged;
|
|
11274
|
+
sizeBytes = staged.length;
|
|
11275
|
+
} else {
|
|
11276
|
+
let stats;
|
|
11277
|
+
try {
|
|
11278
|
+
stats = fs15.statSync(absolutePath);
|
|
11279
|
+
if (!stats.isFile()) {
|
|
11280
|
+
const nestedRepository = stats.isDirectory() && fs15.existsSync(path16.join(absolutePath, ".git"));
|
|
11281
|
+
skipped.push(
|
|
11282
|
+
nestedRepository ? {
|
|
11283
|
+
path: relativePath,
|
|
11284
|
+
reason: "nested-repository",
|
|
11285
|
+
detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
|
|
11286
|
+
} : { path: relativePath, reason: "not-file" }
|
|
11287
|
+
);
|
|
11288
|
+
continue;
|
|
11289
|
+
}
|
|
11290
|
+
} catch (err) {
|
|
11291
|
+
const code = err.code;
|
|
11292
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
11293
|
+
skipped.push({
|
|
10063
11294
|
path: relativePath,
|
|
10064
|
-
reason: "
|
|
10065
|
-
detail: "
|
|
10066
|
-
}
|
|
10067
|
-
|
|
11295
|
+
reason: "missing",
|
|
11296
|
+
detail: "tracked but absent from disk (deleted without staging)"
|
|
11297
|
+
});
|
|
11298
|
+
} else {
|
|
11299
|
+
skipped.push({
|
|
11300
|
+
path: relativePath,
|
|
11301
|
+
reason: "read-error",
|
|
11302
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11303
|
+
});
|
|
11304
|
+
}
|
|
10068
11305
|
continue;
|
|
10069
11306
|
}
|
|
10070
|
-
|
|
10071
|
-
|
|
10072
|
-
|
|
10073
|
-
|
|
10074
|
-
|
|
10075
|
-
|
|
10076
|
-
|
|
10077
|
-
|
|
10078
|
-
|
|
10079
|
-
|
|
10080
|
-
|
|
10081
|
-
|
|
10082
|
-
|
|
10083
|
-
|
|
10084
|
-
|
|
10085
|
-
|
|
10086
|
-
|
|
10087
|
-
|
|
11307
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11308
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11309
|
+
continue;
|
|
11310
|
+
}
|
|
11311
|
+
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
|
|
11312
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11313
|
+
continue;
|
|
11314
|
+
}
|
|
11315
|
+
try {
|
|
11316
|
+
buffer = fs15.readFileSync(absolutePath);
|
|
11317
|
+
} catch (err) {
|
|
11318
|
+
const code = err.code;
|
|
11319
|
+
skipped.push({
|
|
11320
|
+
path: relativePath,
|
|
11321
|
+
reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
|
|
11322
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11323
|
+
});
|
|
11324
|
+
continue;
|
|
11325
|
+
}
|
|
11326
|
+
sizeBytes = stats.size;
|
|
10088
11327
|
}
|
|
10089
11328
|
let decoded;
|
|
10090
11329
|
try {
|
|
@@ -10093,7 +11332,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10093
11332
|
skipped.push({
|
|
10094
11333
|
path: relativePath,
|
|
10095
11334
|
reason: "read-error",
|
|
10096
|
-
detail: `Size: ${
|
|
11335
|
+
detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
|
|
10097
11336
|
/\s+/g,
|
|
10098
11337
|
" "
|
|
10099
11338
|
)
|
|
@@ -10104,13 +11343,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10104
11343
|
skipped.push({
|
|
10105
11344
|
path: relativePath,
|
|
10106
11345
|
reason: "binary",
|
|
10107
|
-
detail: `Size: ${
|
|
11346
|
+
detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
|
|
10108
11347
|
});
|
|
10109
11348
|
continue;
|
|
10110
11349
|
}
|
|
10111
11350
|
const hashSha256 = sha256Hex2(buffer);
|
|
10112
11351
|
const rawContent = decoded.text;
|
|
10113
|
-
totalSizeBytes +=
|
|
11352
|
+
totalSizeBytes += sizeBytes;
|
|
10114
11353
|
if (decoded.encoding !== "utf-8") {
|
|
10115
11354
|
encodingNotes.push({
|
|
10116
11355
|
path: relativePath,
|
|
@@ -10124,7 +11363,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10124
11363
|
bump(layerCounts, layer2);
|
|
10125
11364
|
bump(kindCounts, kind);
|
|
10126
11365
|
const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
|
|
10127
|
-
const fresh = deriveFile(relativePath, rawContent,
|
|
11366
|
+
const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
|
|
10128
11367
|
rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
|
|
10129
11368
|
return fresh;
|
|
10130
11369
|
})();
|
|
@@ -10145,7 +11384,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10145
11384
|
}
|
|
10146
11385
|
files.push({
|
|
10147
11386
|
relativePath,
|
|
10148
|
-
sizeBytes
|
|
11387
|
+
sizeBytes,
|
|
10149
11388
|
lines: lineCount,
|
|
10150
11389
|
hashSha256,
|
|
10151
11390
|
part: "",
|
|
@@ -10166,7 +11405,10 @@ function generateSnapshot(configInput, options) {
|
|
|
10166
11405
|
}
|
|
10167
11406
|
if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
|
|
10168
11407
|
const keep = new Set(changedPaths);
|
|
10169
|
-
const resolver = buildImportResolver(files
|
|
11408
|
+
const resolver = buildImportResolver(files, {
|
|
11409
|
+
extraPaths: changedPaths,
|
|
11410
|
+
tsconfig: tsconfigPathsFor(config.cwd)
|
|
11411
|
+
});
|
|
10170
11412
|
for (const file of files) {
|
|
10171
11413
|
const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
|
|
10172
11414
|
if (fileImports.length === 0) continue;
|
|
@@ -10260,7 +11502,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10260
11502
|
const fingerprint = sha256Hex2(
|
|
10261
11503
|
[
|
|
10262
11504
|
...files.map(
|
|
10263
|
-
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}
|
|
11505
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
10264
11506
|
),
|
|
10265
11507
|
`settings:${configDigest(config)}`
|
|
10266
11508
|
].join("\n")
|
|
@@ -10347,6 +11589,8 @@ function generateSnapshot(configInput, options) {
|
|
|
10347
11589
|
skippedFiles: skipped.length,
|
|
10348
11590
|
totalSourceBytes: totalSizeBytes,
|
|
10349
11591
|
totalContentBytes,
|
|
11592
|
+
sourceLines: totalLines,
|
|
11593
|
+
emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
|
|
10350
11594
|
// The parts are what a model is handed, so the estimate is over the parts rather than
|
|
10351
11595
|
// over the sources: previews and the byte budget both shrink the number.
|
|
10352
11596
|
estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
|
|
@@ -10365,7 +11609,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10365
11609
|
},
|
|
10366
11610
|
layers: layerCounts,
|
|
10367
11611
|
kinds: kindCounts,
|
|
10368
|
-
indexes: buildIndexes(files),
|
|
11612
|
+
indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
|
|
10369
11613
|
parts: parts.map((part) => part.metadata),
|
|
10370
11614
|
files: files.map((file) => {
|
|
10371
11615
|
const { content: _content, ...rest } = file;
|
|
@@ -10382,6 +11626,23 @@ function generateSnapshot(configInput, options) {
|
|
|
10382
11626
|
);
|
|
10383
11627
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10384
11628
|
}
|
|
11629
|
+
if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
|
|
11630
|
+
manifest.warnings.push(
|
|
11631
|
+
`${files.filter((file) => file.isPreviewTruncated).length} file(s) were previewed because largeFileBytes (${config.largeFileBytes} B) is not above maxPartBytes (${config.maxPartBytes} B). Raise largeFileBytes if a whole file is wanted.`
|
|
11632
|
+
);
|
|
11633
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11634
|
+
}
|
|
11635
|
+
if (config.maxPartTokens !== void 0) {
|
|
11636
|
+
const overTokenBudget = parts.filter(
|
|
11637
|
+
(part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
|
|
11638
|
+
);
|
|
11639
|
+
if (overTokenBudget.length > 0) {
|
|
11640
|
+
manifest.warnings.push(
|
|
11641
|
+
`${overTokenBudget.length} part(s) exceed the estimated token ceiling of ${config.maxPartTokens}: the partitioner enforces the equivalent byte budget (tokens \xD7 4), and estimatedTokens is an estimate, not a hard bound.`
|
|
11642
|
+
);
|
|
11643
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11644
|
+
}
|
|
11645
|
+
}
|
|
10385
11646
|
if (secretFindings.length > 0 && !config.artifacts.audit) {
|
|
10386
11647
|
manifest.warnings.push(
|
|
10387
11648
|
`${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
|
|
@@ -10410,6 +11671,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10410
11671
|
sha256: sha256Hex2(sarifText)
|
|
10411
11672
|
};
|
|
10412
11673
|
}
|
|
11674
|
+
const artifacts = config.artifacts;
|
|
11675
|
+
const artifactRecord = (text2) => ({
|
|
11676
|
+
byteSize: Buffer.byteLength(text2, "utf8"),
|
|
11677
|
+
sha256: sha256Hex2(text2)
|
|
11678
|
+
});
|
|
11679
|
+
const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
|
|
11680
|
+
if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
|
|
11681
|
+
const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
|
|
11682
|
+
if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
|
|
11683
|
+
const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
|
|
11684
|
+
if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
|
|
11685
|
+
if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
|
|
10413
11686
|
let monolithJson = null;
|
|
10414
11687
|
let monolithMarkdown = null;
|
|
10415
11688
|
if (config.includeMonolith) {
|
|
@@ -10424,26 +11697,33 @@ function generateSnapshot(configInput, options) {
|
|
|
10424
11697
|
includedLines: countLines(content)
|
|
10425
11698
|
};
|
|
10426
11699
|
});
|
|
10427
|
-
const
|
|
10428
|
-
const
|
|
10429
|
-
if (
|
|
11700
|
+
const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
|
|
11701
|
+
const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
|
|
11702
|
+
if (definitelyTooLarge) {
|
|
11703
|
+
const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
|
|
11704
|
+
manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
|
|
11705
|
+
manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
|
|
11706
|
+
}
|
|
11707
|
+
const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
|
|
11708
|
+
const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
|
|
11709
|
+
if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
|
|
10430
11710
|
monolithMarkdown = markdown;
|
|
10431
11711
|
manifest.artifacts.fullMarkdown = {
|
|
10432
11712
|
byteSize: markdownBytes,
|
|
10433
11713
|
sha256: sha256Hex2(markdown)
|
|
10434
11714
|
};
|
|
10435
|
-
} else {
|
|
11715
|
+
} else if (!definitelyTooLarge) {
|
|
10436
11716
|
manifest.warnings.push(
|
|
10437
11717
|
`full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10438
11718
|
);
|
|
10439
11719
|
}
|
|
10440
11720
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10441
|
-
const json = generateMonolithJson(manifest, fullFiles);
|
|
10442
|
-
const jsonBytes = Buffer.byteLength(json, "utf8");
|
|
10443
|
-
if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
|
|
11721
|
+
const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
|
|
11722
|
+
const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
|
|
11723
|
+
if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
|
|
10444
11724
|
monolithJson = json;
|
|
10445
11725
|
manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
|
|
10446
|
-
} else {
|
|
11726
|
+
} else if (!definitelyTooLarge) {
|
|
10447
11727
|
manifest.warnings.push(
|
|
10448
11728
|
`full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10449
11729
|
);
|
|
@@ -10451,7 +11731,6 @@ function generateSnapshot(configInput, options) {
|
|
|
10451
11731
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10452
11732
|
}
|
|
10453
11733
|
const { outDir, tmpDir } = resolveSafeOutputDirs(config);
|
|
10454
|
-
const { artifacts } = config;
|
|
10455
11734
|
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10456
11735
|
assertStagingRootUsable(tmpDir, config.secretRules);
|
|
10457
11736
|
if (dryRun) {
|
|
@@ -10468,15 +11747,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10468
11747
|
const releaseLock = () => {
|
|
10469
11748
|
for (const release of [...releases].reverse()) release();
|
|
10470
11749
|
};
|
|
11750
|
+
recoverInterruptedPublish(outDir);
|
|
11751
|
+
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10471
11752
|
let stagingDir = null;
|
|
11753
|
+
let releaseDeferred = false;
|
|
10472
11754
|
try {
|
|
10473
11755
|
ensureParentDirectory(outDir, "outDir");
|
|
10474
|
-
|
|
11756
|
+
fs15.mkdirSync(tmpDir, { recursive: true });
|
|
10475
11757
|
cleanStaleRunDirs(tmpDir);
|
|
10476
11758
|
const snapshotId = crypto2.randomUUID();
|
|
10477
11759
|
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
10478
11760
|
stagingDir = path16.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
|
|
10479
|
-
|
|
11761
|
+
fs15.mkdirSync(stagingDir);
|
|
10480
11762
|
writeOwnershipMarker(stagingDir, {
|
|
10481
11763
|
generator: GENERATOR_NAME,
|
|
10482
11764
|
version: GENERATOR_VERSION,
|
|
@@ -10488,45 +11770,66 @@ function generateSnapshot(configInput, options) {
|
|
|
10488
11770
|
});
|
|
10489
11771
|
const partsDir = path16.join(stagingDir, "parts");
|
|
10490
11772
|
const reportsDir = path16.join(stagingDir, "reports");
|
|
10491
|
-
if (artifacts.parts)
|
|
11773
|
+
if (artifacts.parts) fs15.mkdirSync(partsDir, { recursive: true });
|
|
10492
11774
|
if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
|
|
10493
|
-
|
|
10494
|
-
}
|
|
11775
|
+
fs15.mkdirSync(reportsDir, { recursive: true });
|
|
11776
|
+
}
|
|
11777
|
+
const writtenArtifacts = /* @__PURE__ */ new Map();
|
|
11778
|
+
const writeArtifact = (targetDir, relativeEntry, data) => {
|
|
11779
|
+
const full = path16.join(targetDir, ...relativeEntry.split("/"));
|
|
11780
|
+
fs15.writeFileSync(full, data, "utf8");
|
|
11781
|
+
const stats = fs15.statSync(full);
|
|
11782
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11783
|
+
digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
|
|
11784
|
+
mtimeMs: stats.mtimeMs
|
|
11785
|
+
});
|
|
11786
|
+
};
|
|
11787
|
+
const recordArtifact = (targetDir, relativeEntry) => {
|
|
11788
|
+
const full = path16.join(targetDir, ...relativeEntry.split("/"));
|
|
11789
|
+
const stats = fs15.statSync(full);
|
|
11790
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11791
|
+
digest: {
|
|
11792
|
+
path: relativeEntry,
|
|
11793
|
+
bytes: stats.size,
|
|
11794
|
+
sha256: sha256Hex2(fs15.readFileSync(full))
|
|
11795
|
+
},
|
|
11796
|
+
mtimeMs: stats.mtimeMs
|
|
11797
|
+
});
|
|
11798
|
+
};
|
|
10495
11799
|
if (artifacts.parts) {
|
|
10496
11800
|
for (const part of parts) {
|
|
10497
|
-
|
|
11801
|
+
writeArtifact(partsDir, part.filename, part.markdown);
|
|
10498
11802
|
}
|
|
10499
11803
|
}
|
|
10500
11804
|
if (projectTree !== null) {
|
|
10501
|
-
|
|
11805
|
+
writeArtifact(reportsDir, "project-tree.md", projectTree);
|
|
10502
11806
|
}
|
|
10503
|
-
if (
|
|
10504
|
-
|
|
11807
|
+
if (navigationText !== null) {
|
|
11808
|
+
writeArtifact(reportsDir, "navigation.md", navigationText);
|
|
10505
11809
|
}
|
|
10506
|
-
if (
|
|
10507
|
-
|
|
10508
|
-
path16.join(reportsDir, "audit.md"),
|
|
10509
|
-
generateAuditReport(manifest, secretFindings, config.secretRules),
|
|
10510
|
-
"utf8"
|
|
10511
|
-
);
|
|
11810
|
+
if (auditText !== null) {
|
|
11811
|
+
writeArtifact(reportsDir, "audit.md", auditText);
|
|
10512
11812
|
}
|
|
10513
11813
|
if (sarifText !== null) {
|
|
10514
|
-
|
|
11814
|
+
writeArtifact(reportsDir, "audit.sarif", sarifText);
|
|
10515
11815
|
}
|
|
10516
|
-
if (
|
|
10517
|
-
|
|
11816
|
+
if (readmeText !== null) {
|
|
11817
|
+
writeArtifact(stagingDir, "README.md", readmeText);
|
|
10518
11818
|
}
|
|
10519
11819
|
if (artifacts.manifest) {
|
|
10520
|
-
|
|
11820
|
+
writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
|
|
10521
11821
|
}
|
|
10522
11822
|
if (monolithJson !== null) {
|
|
10523
|
-
|
|
11823
|
+
writeArtifact(stagingDir, "full-codebase.json", monolithJson);
|
|
10524
11824
|
}
|
|
10525
11825
|
if (monolithMarkdown !== null) {
|
|
10526
|
-
|
|
11826
|
+
writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
|
|
10527
11827
|
}
|
|
10528
|
-
writeOwnershipMarker(
|
|
10529
|
-
|
|
11828
|
+
writeOwnershipMarker(
|
|
11829
|
+
stagingDir,
|
|
11830
|
+
markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11831
|
+
);
|
|
11832
|
+
swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
|
|
10530
11833
|
stagingDir = null;
|
|
10531
11834
|
const warningsBeforeHook = manifest.warnings.length;
|
|
10532
11835
|
const pendingHook = runAfterGenerate(config, manifest);
|
|
@@ -10534,8 +11837,12 @@ function generateSnapshot(configInput, options) {
|
|
|
10534
11837
|
if (!markerBelongsTo(outDir, snapshotId)) return;
|
|
10535
11838
|
if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
|
|
10536
11839
|
writeManifestAtomically(path16.join(outDir, "manifest.json"), manifest);
|
|
11840
|
+
recordArtifact(outDir, "manifest.json");
|
|
10537
11841
|
}
|
|
10538
|
-
writeOwnershipMarker(
|
|
11842
|
+
writeOwnershipMarker(
|
|
11843
|
+
outDir,
|
|
11844
|
+
markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11845
|
+
);
|
|
10539
11846
|
};
|
|
10540
11847
|
if (config.hooks.afterGenerate) shipHookState();
|
|
10541
11848
|
if (pendingHook) {
|
|
@@ -10562,19 +11869,26 @@ function generateSnapshot(configInput, options) {
|
|
|
10562
11869
|
if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
|
|
10563
11870
|
});
|
|
10564
11871
|
pendingHooks.set(outDir, tracked);
|
|
11872
|
+
releaseDeferred = true;
|
|
11873
|
+
void tracked.finally(() => {
|
|
11874
|
+
removeIfEmpty(tmpDir);
|
|
11875
|
+
releaseLock();
|
|
11876
|
+
});
|
|
10565
11877
|
}
|
|
10566
11878
|
return manifest;
|
|
10567
11879
|
} catch (err) {
|
|
10568
11880
|
if (stagingDir !== null) {
|
|
10569
11881
|
try {
|
|
10570
|
-
|
|
11882
|
+
fs15.rmSync(stagingDir, { recursive: true, force: true });
|
|
10571
11883
|
} catch {
|
|
10572
11884
|
}
|
|
10573
11885
|
}
|
|
10574
11886
|
throw err;
|
|
10575
11887
|
} finally {
|
|
10576
|
-
|
|
10577
|
-
|
|
11888
|
+
if (!releaseDeferred) {
|
|
11889
|
+
removeIfEmpty(tmpDir);
|
|
11890
|
+
releaseLock();
|
|
11891
|
+
}
|
|
10578
11892
|
}
|
|
10579
11893
|
}
|
|
10580
11894
|
var pendingHooks = /* @__PURE__ */ new Map();
|
|
@@ -10590,4 +11904,4 @@ async function generateSnapshotAsync(configInput, options) {
|
|
|
10590
11904
|
return manifest;
|
|
10591
11905
|
}
|
|
10592
11906
|
|
|
10593
|
-
export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
|
|
11907
|
+
export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
|