codebase-snapshot 0.9.16 → 0.9.17
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 +64 -0
- package/README.md +1 -1
- package/SECURITY.md +18 -6
- package/dist/bin.js +2019 -619
- package/dist/{chunk-6TRFLA7N.js → chunk-IIP43I7C.js} +1755 -443
- package/dist/{chunk-WIL536QD.js → chunk-S4367K5X.js} +97 -24
- package/dist/cli.cjs +2001 -605
- package/dist/cli.d.cts +1 -11
- package/dist/cli.d.ts +1 -11
- package/dist/cli.js +16 -5
- package/dist/index.cjs +1748 -437
- package/dist/index.d.cts +97 -8
- package/dist/index.d.ts +97 -8
- package/dist/index.js +1 -1
- package/dist/mcp.cjs +1760 -340
- 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 +14 -9
- 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/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var crypto2 = require('crypto');
|
|
4
|
+
var worker_threads = require('worker_threads');
|
|
4
5
|
var async_hooks = require('async_hooks');
|
|
5
|
-
var
|
|
6
|
+
var fs15 = require('fs');
|
|
6
7
|
var os = require('os');
|
|
7
8
|
var path16 = require('path');
|
|
8
9
|
var ts = require('typescript');
|
|
@@ -12,7 +13,6 @@ var childProcess = require('child_process');
|
|
|
12
13
|
var http = require('http');
|
|
13
14
|
var https = require('https');
|
|
14
15
|
var readline = require('readline');
|
|
15
|
-
require('worker_threads');
|
|
16
16
|
|
|
17
17
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
18
18
|
|
|
@@ -35,7 +35,7 @@ function _interopNamespace(e) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
var crypto2__namespace = /*#__PURE__*/_interopNamespace(crypto2);
|
|
38
|
-
var
|
|
38
|
+
var fs15__namespace = /*#__PURE__*/_interopNamespace(fs15);
|
|
39
39
|
var os__namespace = /*#__PURE__*/_interopNamespace(os);
|
|
40
40
|
var path16__namespace = /*#__PURE__*/_interopNamespace(path16);
|
|
41
41
|
var ts__default = /*#__PURE__*/_interopDefault(ts);
|
|
@@ -637,9 +637,9 @@ var rubyProfile = {
|
|
|
637
637
|
eachLine(content, (line) => {
|
|
638
638
|
const trimmed = line.trim();
|
|
639
639
|
if (!trimmed || trimmed.startsWith("#")) return;
|
|
640
|
-
const
|
|
641
|
-
if (
|
|
642
|
-
summary.imports.push(`./${
|
|
640
|
+
const relative10 = REQUIRE_RELATIVE.exec(trimmed);
|
|
641
|
+
if (relative10) {
|
|
642
|
+
summary.imports.push(`./${relative10[1]}`);
|
|
643
643
|
return;
|
|
644
644
|
}
|
|
645
645
|
const required = REQUIRE.exec(trimmed);
|
|
@@ -739,6 +739,16 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
|
|
|
739
739
|
"HEAD",
|
|
740
740
|
"OPTIONS"
|
|
741
741
|
]);
|
|
742
|
+
var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
|
|
743
|
+
var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
|
|
744
|
+
"get",
|
|
745
|
+
"post",
|
|
746
|
+
"put",
|
|
747
|
+
"delete",
|
|
748
|
+
"patch",
|
|
749
|
+
"head",
|
|
750
|
+
"options"
|
|
751
|
+
]);
|
|
742
752
|
function bindingNames(name, into) {
|
|
743
753
|
if (ts__default.default.isIdentifier(name)) {
|
|
744
754
|
into.push(name.text);
|
|
@@ -749,6 +759,53 @@ function bindingNames(name, into) {
|
|
|
749
759
|
bindingNames(element.name, into);
|
|
750
760
|
}
|
|
751
761
|
}
|
|
762
|
+
function objectLiteralNames(node) {
|
|
763
|
+
const names = [];
|
|
764
|
+
for (const property of node.properties) {
|
|
765
|
+
if (ts__default.default.isShorthandPropertyAssignment(property)) {
|
|
766
|
+
names.push(property.name.text);
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
if (!ts__default.default.isPropertyAssignment(property)) continue;
|
|
770
|
+
const name = property.name;
|
|
771
|
+
if (ts__default.default.isIdentifier(name) || ts__default.default.isStringLiteral(name) || ts__default.default.isNumericLiteral(name)) {
|
|
772
|
+
names.push(name.text);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return names;
|
|
776
|
+
}
|
|
777
|
+
function cjsExportedNames(expression) {
|
|
778
|
+
const left = expression.left;
|
|
779
|
+
if (!ts__default.default.isPropertyAccessExpression(left)) return null;
|
|
780
|
+
const isModuleExports = left.name.text === "exports" && ts__default.default.isIdentifier(left.expression) && left.expression.text === "module";
|
|
781
|
+
if (isModuleExports) {
|
|
782
|
+
const right = expression.right;
|
|
783
|
+
if (ts__default.default.isObjectLiteralExpression(right)) return objectLiteralNames(right);
|
|
784
|
+
if (ts__default.default.isIdentifier(right)) return [right.text];
|
|
785
|
+
return [];
|
|
786
|
+
}
|
|
787
|
+
if (ts__default.default.isIdentifier(left.expression) && left.expression.text === "exports") {
|
|
788
|
+
return [left.name.text];
|
|
789
|
+
}
|
|
790
|
+
const parent = left.expression;
|
|
791
|
+
if (ts__default.default.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts__default.default.isIdentifier(parent.expression) && parent.expression.text === "module") {
|
|
792
|
+
return [left.name.text];
|
|
793
|
+
}
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
function countSyntacticErrors(fileName, content) {
|
|
797
|
+
const result = ts__default.default.transpileModule(content, {
|
|
798
|
+
fileName,
|
|
799
|
+
compilerOptions: {
|
|
800
|
+
target: ts__default.default.ScriptTarget.Latest,
|
|
801
|
+
module: ts__default.default.ModuleKind.ESNext
|
|
802
|
+
},
|
|
803
|
+
reportDiagnostics: true
|
|
804
|
+
});
|
|
805
|
+
return (result.diagnostics ?? []).filter(
|
|
806
|
+
(diagnostic) => diagnostic.category === ts__default.default.DiagnosticCategory.Error
|
|
807
|
+
).length;
|
|
808
|
+
}
|
|
752
809
|
function summarizeTypeScriptSource(relativePath, content) {
|
|
753
810
|
const summary = {
|
|
754
811
|
directives: [],
|
|
@@ -766,16 +823,17 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
766
823
|
routeHandlers: []
|
|
767
824
|
};
|
|
768
825
|
const lowerPath = relativePath.toLowerCase();
|
|
769
|
-
const
|
|
826
|
+
const scriptKind = /.tsx$/.test(lowerPath) ? ts__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts__default.default.ScriptKind.JS : ts__default.default.ScriptKind.TS;
|
|
770
827
|
const sourceFile = ts__default.default.createSourceFile(
|
|
771
828
|
relativePath,
|
|
772
829
|
content,
|
|
773
830
|
ts__default.default.ScriptTarget.Latest,
|
|
774
831
|
/* setParentNodes */
|
|
775
832
|
false,
|
|
776
|
-
|
|
833
|
+
scriptKind
|
|
777
834
|
);
|
|
778
|
-
const
|
|
835
|
+
const parsedDiagnostics = sourceFile.parseDiagnostics;
|
|
836
|
+
const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts__default.default.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
|
|
779
837
|
if (parseErrors > 0) summary.parseErrors = parseErrors;
|
|
780
838
|
for (const statement of sourceFile.statements) {
|
|
781
839
|
if (ts__default.default.isExpressionStatement(statement) && ts__default.default.isStringLiteral(statement.expression)) {
|
|
@@ -832,6 +890,7 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
832
890
|
if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
|
|
833
891
|
if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
|
|
834
892
|
};
|
|
893
|
+
const cjsExports = [];
|
|
835
894
|
const stack = [sourceFile];
|
|
836
895
|
while (stack.length > 0) {
|
|
837
896
|
const node = stack.pop();
|
|
@@ -848,6 +907,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
848
907
|
const isRequire = ts__default.default.isIdentifier(node.expression) && node.expression.text === "require";
|
|
849
908
|
if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
|
|
850
909
|
}
|
|
910
|
+
const callee = node.expression;
|
|
911
|
+
if (ts__default.default.isPropertyAccessExpression(callee) && ts__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
|
|
912
|
+
summary.routeHandlers.push(callee.name.text.toUpperCase());
|
|
913
|
+
}
|
|
851
914
|
}
|
|
852
915
|
if (ts__default.default.isExportDeclaration(node)) {
|
|
853
916
|
if (node.moduleSpecifier && ts__default.default.isStringLiteral(node.moduleSpecifier)) {
|
|
@@ -865,6 +928,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
865
928
|
}
|
|
866
929
|
}
|
|
867
930
|
}
|
|
931
|
+
if (ts__default.default.isExpressionStatement(node) && ts__default.default.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts__default.default.SyntaxKind.EqualsToken) {
|
|
932
|
+
const cjsNames = cjsExportedNames(node.expression);
|
|
933
|
+
if (cjsNames !== null) cjsExports.push(...cjsNames);
|
|
934
|
+
}
|
|
868
935
|
if (ts__default.default.isExportAssignment(node)) {
|
|
869
936
|
summary.exports.push("default");
|
|
870
937
|
if (rendersJsx(node.expression)) summary.reactComponents.push("default");
|
|
@@ -928,6 +995,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
928
995
|
stack.push(children[index]);
|
|
929
996
|
}
|
|
930
997
|
}
|
|
998
|
+
if (cjsExports.length > 0) {
|
|
999
|
+
summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
|
|
1000
|
+
summary.exports.push(...cjsExports);
|
|
1001
|
+
}
|
|
931
1002
|
const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
932
1003
|
summary.directives = dedupeSorted2(summary.directives);
|
|
933
1004
|
summary.imports = dedupeSorted2(summary.imports);
|
|
@@ -1383,13 +1454,13 @@ function isBinaryFile(absolutePath) {
|
|
|
1383
1454
|
if (isBinaryExtension(absolutePath)) return true;
|
|
1384
1455
|
let fd;
|
|
1385
1456
|
try {
|
|
1386
|
-
fd =
|
|
1457
|
+
fd = fs15__namespace.openSync(absolutePath, "r");
|
|
1387
1458
|
const buffer = Buffer.alloc(CHUNK);
|
|
1388
1459
|
let sample;
|
|
1389
1460
|
let position = 0;
|
|
1390
1461
|
while (position < BINARY_SCAN_BYTES) {
|
|
1391
1462
|
const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
|
|
1392
|
-
const bytesRead =
|
|
1463
|
+
const bytesRead = fs15__namespace.readSync(fd, buffer, 0, wanted, position);
|
|
1393
1464
|
if (bytesRead === 0) return false;
|
|
1394
1465
|
const chunk = buffer.subarray(0, bytesRead);
|
|
1395
1466
|
if (sample === void 0) {
|
|
@@ -1407,7 +1478,7 @@ function isBinaryFile(absolutePath) {
|
|
|
1407
1478
|
} finally {
|
|
1408
1479
|
if (fd !== void 0) {
|
|
1409
1480
|
try {
|
|
1410
|
-
|
|
1481
|
+
fs15__namespace.closeSync(fd);
|
|
1411
1482
|
} catch {
|
|
1412
1483
|
}
|
|
1413
1484
|
}
|
|
@@ -1429,9 +1500,9 @@ function importsOfText(relativePath, text2) {
|
|
|
1429
1500
|
function importsOfFile(relativePath, absolutePath) {
|
|
1430
1501
|
let buffer;
|
|
1431
1502
|
try {
|
|
1432
|
-
const stats =
|
|
1503
|
+
const stats = fs15__namespace.statSync(absolutePath);
|
|
1433
1504
|
if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
|
|
1434
|
-
buffer =
|
|
1505
|
+
buffer = fs15__namespace.readFileSync(absolutePath);
|
|
1435
1506
|
} catch {
|
|
1436
1507
|
return [];
|
|
1437
1508
|
}
|
|
@@ -1723,9 +1794,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
|
|
|
1723
1794
|
]);
|
|
1724
1795
|
function readSmallFile(fullPath) {
|
|
1725
1796
|
try {
|
|
1726
|
-
const stats =
|
|
1797
|
+
const stats = fs15__namespace.statSync(fullPath);
|
|
1727
1798
|
if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
|
|
1728
|
-
return
|
|
1799
|
+
return fs15__namespace.readFileSync(fullPath, "utf8");
|
|
1729
1800
|
} catch {
|
|
1730
1801
|
return null;
|
|
1731
1802
|
}
|
|
@@ -1791,7 +1862,7 @@ function pnpmWorkspacePatterns(raw) {
|
|
|
1791
1862
|
function childDirectories(cwd, parent) {
|
|
1792
1863
|
let entries;
|
|
1793
1864
|
try {
|
|
1794
|
-
entries =
|
|
1865
|
+
entries = fs15__namespace.readdirSync(path16__namespace.join(cwd, parent), { withFileTypes: true });
|
|
1795
1866
|
} catch {
|
|
1796
1867
|
return [];
|
|
1797
1868
|
}
|
|
@@ -1826,10 +1897,10 @@ function workspacePackageDirs(cwd, patterns) {
|
|
|
1826
1897
|
function scanWorkspacePackages(cwd, patterns) {
|
|
1827
1898
|
const files = /* @__PURE__ */ new Set();
|
|
1828
1899
|
const dependencies = /* @__PURE__ */ new Set();
|
|
1829
|
-
for (const
|
|
1830
|
-
const full = path16__namespace.join(cwd,
|
|
1900
|
+
for (const relative10 of workspacePackageDirs(cwd, patterns)) {
|
|
1901
|
+
const full = path16__namespace.join(cwd, relative10);
|
|
1831
1902
|
try {
|
|
1832
|
-
for (const entry of
|
|
1903
|
+
for (const entry of fs15__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
|
|
1833
1904
|
} catch {
|
|
1834
1905
|
}
|
|
1835
1906
|
const raw = readSmallFile(path16__namespace.join(full, "package.json"));
|
|
@@ -1842,7 +1913,7 @@ function scanWorkspacePackages(cwd, patterns) {
|
|
|
1842
1913
|
var SNAPSHOT_MARKER = ".codebase-snapshot";
|
|
1843
1914
|
function isToolOwnedDirectory(dir) {
|
|
1844
1915
|
try {
|
|
1845
|
-
return
|
|
1916
|
+
return fs15__namespace.statSync(dir).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
|
|
1846
1917
|
} catch {
|
|
1847
1918
|
return false;
|
|
1848
1919
|
}
|
|
@@ -1857,7 +1928,7 @@ function countMarkdownFiles(cwd) {
|
|
|
1857
1928
|
directoriesSeen += 1;
|
|
1858
1929
|
let entries;
|
|
1859
1930
|
try {
|
|
1860
|
-
entries =
|
|
1931
|
+
entries = fs15__namespace.readdirSync(current.dir, { withFileTypes: true });
|
|
1861
1932
|
} catch {
|
|
1862
1933
|
continue;
|
|
1863
1934
|
}
|
|
@@ -1879,7 +1950,7 @@ function buildPresetContext(cwd) {
|
|
|
1879
1950
|
const files = /* @__PURE__ */ new Set();
|
|
1880
1951
|
const dirs = /* @__PURE__ */ new Set();
|
|
1881
1952
|
try {
|
|
1882
|
-
for (const entry of
|
|
1953
|
+
for (const entry of fs15__namespace.readdirSync(cwd, { withFileTypes: true })) {
|
|
1883
1954
|
if (entry.isDirectory()) dirs.add(entry.name);
|
|
1884
1955
|
else if (entry.isFile()) files.add(entry.name);
|
|
1885
1956
|
}
|
|
@@ -2754,7 +2825,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
|
|
|
2754
2825
|
var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
|
|
2755
2826
|
var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
|
|
2756
2827
|
var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
|
|
2757
|
-
|
|
2828
|
+
function quotedValueFor(delimiterGroup) {
|
|
2829
|
+
return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
|
|
2830
|
+
}
|
|
2831
|
+
var QUOTED_VALUE = quotedValueFor(1);
|
|
2758
2832
|
var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
|
|
2759
2833
|
var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
|
|
2760
2834
|
var DEFAULT_SECRET_PATTERNS = [
|
|
@@ -2908,7 +2982,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
2908
2982
|
// consumes the flag so the match is the credential alone.
|
|
2909
2983
|
// - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
|
|
2910
2984
|
rule: "uri-credentials",
|
|
2911
|
-
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[
|
|
2985
|
+
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%._=~-])/
|
|
2912
2986
|
},
|
|
2913
2987
|
{
|
|
2914
2988
|
// The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
|
|
@@ -3020,7 +3094,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3020
3094
|
// rendering of textual userinfo mixes cases, while the prose the earlier rules were
|
|
3021
3095
|
// protecting (`Bearer authentication`) is a lowercase word.
|
|
3022
3096
|
rule: "authorization-header",
|
|
3023
|
-
pattern: /(?<=
|
|
3097
|
+
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_.+/=-])/
|
|
3024
3098
|
},
|
|
3025
3099
|
{
|
|
3026
3100
|
// Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
|
|
@@ -3047,7 +3121,9 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3047
3121
|
// between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
|
|
3048
3122
|
rule: "interpolation-fallback-secret",
|
|
3049
3123
|
pattern: new RegExp(
|
|
3050
|
-
|
|
3124
|
+
// The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
|
|
3125
|
+
// and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
|
|
3126
|
+
`(?:["']${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})\\}["'\`]?`,
|
|
3051
3127
|
"i"
|
|
3052
3128
|
),
|
|
3053
3129
|
valueGroup: 1
|
|
@@ -3096,19 +3172,15 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3096
3172
|
if (pattern instanceof RegExp) {
|
|
3097
3173
|
const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
|
|
3098
3174
|
if (valueGroup !== void 0) flags.add("d");
|
|
3099
|
-
return
|
|
3100
|
-
rule,
|
|
3101
|
-
pattern: new RegExp(pattern.source, [...flags].join("")),
|
|
3102
|
-
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3103
|
-
};
|
|
3175
|
+
return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
|
|
3104
3176
|
}
|
|
3105
3177
|
if (typeof pattern === "string") {
|
|
3106
3178
|
try {
|
|
3107
|
-
return
|
|
3179
|
+
return checkedPattern(
|
|
3108
3180
|
rule,
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3181
|
+
new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
|
|
3182
|
+
valueGroup
|
|
3183
|
+
);
|
|
3112
3184
|
} catch (err) {
|
|
3113
3185
|
throw new Error(
|
|
3114
3186
|
`Invalid regular expression for secret rule "${rule}": ${err.message}`
|
|
@@ -3119,6 +3191,19 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3119
3191
|
`Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
|
|
3120
3192
|
);
|
|
3121
3193
|
}
|
|
3194
|
+
function checkedPattern(rule, compiled, valueGroup) {
|
|
3195
|
+
const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
|
|
3196
|
+
if (stateless.test("")) {
|
|
3197
|
+
throw new Error(
|
|
3198
|
+
`Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
|
|
3199
|
+
);
|
|
3200
|
+
}
|
|
3201
|
+
return {
|
|
3202
|
+
rule,
|
|
3203
|
+
pattern: compiled,
|
|
3204
|
+
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3205
|
+
};
|
|
3206
|
+
}
|
|
3122
3207
|
function compileSecretRules(rules) {
|
|
3123
3208
|
if (!Array.isArray(rules)) {
|
|
3124
3209
|
throw new Error(
|
|
@@ -3175,6 +3260,193 @@ function toGlobal(rule) {
|
|
|
3175
3260
|
}
|
|
3176
3261
|
var LINE_BREAK = /(\r\n|\n|\r)/;
|
|
3177
3262
|
var LINE_TERMINATOR = /\r\n|\n|\r/g;
|
|
3263
|
+
function isOpeningQuote(line, index) {
|
|
3264
|
+
const code = line.charCodeAt(index);
|
|
3265
|
+
if (code === 96) return true;
|
|
3266
|
+
if (code !== 34 && code !== 39) return false;
|
|
3267
|
+
return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
|
|
3268
|
+
}
|
|
3269
|
+
function quoteStates(line) {
|
|
3270
|
+
const states = new Uint8Array(line.length + 1);
|
|
3271
|
+
let quote = 0;
|
|
3272
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3273
|
+
states[index] = quote;
|
|
3274
|
+
const code = line.charCodeAt(index);
|
|
3275
|
+
if (quote === 0) {
|
|
3276
|
+
if (isOpeningQuote(line, index)) quote = code;
|
|
3277
|
+
} else if (code === 92) {
|
|
3278
|
+
if (index + 1 < line.length) {
|
|
3279
|
+
index += 1;
|
|
3280
|
+
states[index] = quote;
|
|
3281
|
+
}
|
|
3282
|
+
} else if (code === quote) {
|
|
3283
|
+
quote = 0;
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
states[line.length] = quote;
|
|
3287
|
+
return states;
|
|
3288
|
+
}
|
|
3289
|
+
function quoteStateFor(line, context) {
|
|
3290
|
+
if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
|
|
3291
|
+
return context.quoteAt;
|
|
3292
|
+
}
|
|
3293
|
+
function quoteStateAfter(text2, quote, end = text2.length) {
|
|
3294
|
+
for (let index = 0; index < end; index += 1) {
|
|
3295
|
+
const code = text2.charCodeAt(index);
|
|
3296
|
+
if (quote === 0) {
|
|
3297
|
+
if (isOpeningQuote(text2, index)) quote = code;
|
|
3298
|
+
} else if (code === 92) {
|
|
3299
|
+
index += 1;
|
|
3300
|
+
} else if (code === quote) {
|
|
3301
|
+
quote = 0;
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
return quote;
|
|
3305
|
+
}
|
|
3306
|
+
function commentStartFor(line, context) {
|
|
3307
|
+
if (context.commentStart !== void 0) return context.commentStart;
|
|
3308
|
+
const quotes = quoteStateFor(line, context);
|
|
3309
|
+
let start = line.length;
|
|
3310
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3311
|
+
if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
|
|
3312
|
+
if (index === 0 || /\s/.test(line[index - 1])) {
|
|
3313
|
+
start = index;
|
|
3314
|
+
break;
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
context.commentStart = start;
|
|
3318
|
+
return start;
|
|
3319
|
+
}
|
|
3320
|
+
function commandSeparatorsFor(line, context) {
|
|
3321
|
+
if (context.commandSeparators !== void 0) return context.commandSeparators;
|
|
3322
|
+
const quotes = quoteStateFor(line, context);
|
|
3323
|
+
const separators = [];
|
|
3324
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3325
|
+
if (quotes[index] !== 0) continue;
|
|
3326
|
+
const ch = line[index];
|
|
3327
|
+
const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
|
|
3328
|
+
if (ch === "&" || ch === "|") {
|
|
3329
|
+
if (line[index + 1] === ch) {
|
|
3330
|
+
const after = index + 2;
|
|
3331
|
+
const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
|
|
3332
|
+
if (doubleSpaced) separators.push(index);
|
|
3333
|
+
index += 1;
|
|
3334
|
+
} else if (spaced) {
|
|
3335
|
+
separators.push(index);
|
|
3336
|
+
}
|
|
3337
|
+
} else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
|
|
3338
|
+
separators.push(index);
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
context.commandSeparators = separators;
|
|
3342
|
+
return separators;
|
|
3343
|
+
}
|
|
3344
|
+
function lineValueEnd(line, start, context) {
|
|
3345
|
+
const comment = commentStartFor(line, context);
|
|
3346
|
+
let end = comment > start ? comment : line.length;
|
|
3347
|
+
for (const separator of commandSeparatorsFor(line, context)) {
|
|
3348
|
+
if (separator > start && separator < end) {
|
|
3349
|
+
end = separator;
|
|
3350
|
+
break;
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
while (end > start && /\s/.test(line[end - 1])) end -= 1;
|
|
3354
|
+
return end;
|
|
3355
|
+
}
|
|
3356
|
+
function hasStructuralQuote(line) {
|
|
3357
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3358
|
+
const ch = line[index];
|
|
3359
|
+
if (ch !== '"' && ch !== "'" && ch !== "`") continue;
|
|
3360
|
+
if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
|
|
3361
|
+
let backslashes = 0;
|
|
3362
|
+
for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
|
|
3363
|
+
if (backslashes % 2 === 1) continue;
|
|
3364
|
+
let before = index - 1;
|
|
3365
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3366
|
+
if (before < 0 || "+,=:([{".includes(line[before])) return true;
|
|
3367
|
+
}
|
|
3368
|
+
return false;
|
|
3369
|
+
}
|
|
3370
|
+
function maskRawPemLine(line) {
|
|
3371
|
+
if (line.trim() === "") return line;
|
|
3372
|
+
const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
|
|
3373
|
+
let rest = line.slice(leading.length);
|
|
3374
|
+
const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
|
|
3375
|
+
rest = rest.slice(0, rest.length - trailing.length);
|
|
3376
|
+
return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
|
|
3377
|
+
}
|
|
3378
|
+
function skeletonisePemLine(line, initialQuote) {
|
|
3379
|
+
const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
|
|
3380
|
+
const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
|
|
3381
|
+
if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
|
|
3382
|
+
let out = "";
|
|
3383
|
+
let quote = initialQuote;
|
|
3384
|
+
let masking = false;
|
|
3385
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3386
|
+
const code = line.charCodeAt(index);
|
|
3387
|
+
if (quote === 0) {
|
|
3388
|
+
if (isOpeningQuote(line, index)) {
|
|
3389
|
+
quote = code;
|
|
3390
|
+
masking = false;
|
|
3391
|
+
}
|
|
3392
|
+
out += line[index];
|
|
3393
|
+
continue;
|
|
3394
|
+
}
|
|
3395
|
+
if (code === 92) {
|
|
3396
|
+
masking = false;
|
|
3397
|
+
out += line[index];
|
|
3398
|
+
if (index + 1 < line.length) {
|
|
3399
|
+
out += line[index + 1];
|
|
3400
|
+
index += 1;
|
|
3401
|
+
}
|
|
3402
|
+
continue;
|
|
3403
|
+
}
|
|
3404
|
+
if (code === quote) {
|
|
3405
|
+
masking = false;
|
|
3406
|
+
quote = 0;
|
|
3407
|
+
out += line[index];
|
|
3408
|
+
continue;
|
|
3409
|
+
}
|
|
3410
|
+
if (!masking) {
|
|
3411
|
+
out += PEM_REDACTION_MARKER;
|
|
3412
|
+
masking = true;
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
return { text: out, quote };
|
|
3416
|
+
}
|
|
3417
|
+
function lineSpanAt(text2, start, end) {
|
|
3418
|
+
let lineStart = start;
|
|
3419
|
+
while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
|
|
3420
|
+
lineStart -= 1;
|
|
3421
|
+
}
|
|
3422
|
+
let lineEnd = end;
|
|
3423
|
+
while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
|
|
3424
|
+
if (lineEnd < text2.length) {
|
|
3425
|
+
lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
|
|
3426
|
+
}
|
|
3427
|
+
return { start: lineStart, end: lineEnd };
|
|
3428
|
+
}
|
|
3429
|
+
function redactPemSpan(text2, matchStart, matchEnd) {
|
|
3430
|
+
const span = lineSpanAt(text2, matchStart, matchEnd);
|
|
3431
|
+
const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
|
|
3432
|
+
let quote = quoteStateAfter(text2, 0, matchStart);
|
|
3433
|
+
let cursor = span.start;
|
|
3434
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3435
|
+
const line = segments[index];
|
|
3436
|
+
const lineStart = cursor;
|
|
3437
|
+
const lineEnd = lineStart + line.length;
|
|
3438
|
+
cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
|
|
3439
|
+
const from = Math.max(lineStart, matchStart);
|
|
3440
|
+
const to = Math.min(lineEnd, matchEnd);
|
|
3441
|
+
if (from >= to) continue;
|
|
3442
|
+
const localFrom = from - lineStart;
|
|
3443
|
+
const localTo = to - lineStart;
|
|
3444
|
+
const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
|
|
3445
|
+
segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
|
|
3446
|
+
quote = result.quote;
|
|
3447
|
+
}
|
|
3448
|
+
return { replacement: segments.join(""), start: span.start, end: span.end };
|
|
3449
|
+
}
|
|
3178
3450
|
var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
|
|
3179
3451
|
function compiledRuleFor(rule) {
|
|
3180
3452
|
let compiled = COMPILED_RULES.get(rule);
|
|
@@ -3189,22 +3461,30 @@ function compiledRuleFor(rule) {
|
|
|
3189
3461
|
return compiled;
|
|
3190
3462
|
}
|
|
3191
3463
|
function scanAndRedactSecrets(content, rules, filePath) {
|
|
3192
|
-
const
|
|
3464
|
+
const findingsByLine = /* @__PURE__ */ new Map();
|
|
3465
|
+
const recordFinding = (line, rulesForLine) => {
|
|
3466
|
+
let entry = findingsByLine.get(line);
|
|
3467
|
+
if (entry === void 0) {
|
|
3468
|
+
entry = /* @__PURE__ */ new Set();
|
|
3469
|
+
findingsByLine.set(line, entry);
|
|
3470
|
+
}
|
|
3471
|
+
for (const rule of rulesForLine) entry.add(rule);
|
|
3472
|
+
};
|
|
3193
3473
|
let redacted = content;
|
|
3194
3474
|
for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
|
|
3195
3475
|
blockPattern.lastIndex = 0;
|
|
3196
3476
|
let match;
|
|
3197
3477
|
while ((match = blockPattern.exec(redacted)) !== null) {
|
|
3198
3478
|
if (match[0].length === 0) {
|
|
3199
|
-
blockPattern.lastIndex
|
|
3479
|
+
blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
|
|
3200
3480
|
continue;
|
|
3201
3481
|
}
|
|
3202
|
-
const
|
|
3203
|
-
const line = (
|
|
3204
|
-
const
|
|
3205
|
-
|
|
3206
|
-
redacted =
|
|
3207
|
-
blockPattern.lastIndex =
|
|
3482
|
+
const matchEnd = match.index + match[0].length;
|
|
3483
|
+
const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
|
|
3484
|
+
const span = redactPemSpan(redacted, match.index, matchEnd);
|
|
3485
|
+
recordFinding(line, ["private-key-block"]);
|
|
3486
|
+
redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
|
|
3487
|
+
blockPattern.lastIndex = span.start + span.replacement.length;
|
|
3208
3488
|
}
|
|
3209
3489
|
}
|
|
3210
3490
|
const compiled = rules.map(compiledRuleFor);
|
|
@@ -3215,17 +3495,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3215
3495
|
if (line.length > 0) {
|
|
3216
3496
|
const spans = [];
|
|
3217
3497
|
const matchedRules = /* @__PURE__ */ new Set();
|
|
3498
|
+
const context = {};
|
|
3218
3499
|
for (const { rule, pattern, valueGroup } of compiled) {
|
|
3219
3500
|
pattern.lastIndex = 0;
|
|
3220
3501
|
let match;
|
|
3221
3502
|
while ((match = pattern.exec(line)) !== null) {
|
|
3222
3503
|
if (match[0].length === 0) {
|
|
3223
|
-
pattern.lastIndex
|
|
3504
|
+
pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
|
|
3224
3505
|
continue;
|
|
3225
3506
|
}
|
|
3226
3507
|
const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
|
|
3508
|
+
const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
|
|
3509
|
+
if (isPlaceholderValue(candidate)) continue;
|
|
3510
|
+
if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
|
|
3511
|
+
continue;
|
|
3512
|
+
}
|
|
3513
|
+
if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
|
|
3514
|
+
continue;
|
|
3515
|
+
}
|
|
3516
|
+
if (rule === "credential-assignment-weak" && group) {
|
|
3517
|
+
let before = match.index - 1;
|
|
3518
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3519
|
+
if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
|
|
3520
|
+
const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
|
|
3521
|
+
if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
|
|
3522
|
+
continue;
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3227
3525
|
if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
|
|
3228
|
-
if (
|
|
3526
|
+
if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
|
|
3527
|
+
continue;
|
|
3528
|
+
}
|
|
3529
|
+
if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
|
|
3229
3530
|
continue;
|
|
3230
3531
|
}
|
|
3231
3532
|
if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
|
|
@@ -3251,7 +3552,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3251
3552
|
if (wholeValue) {
|
|
3252
3553
|
spans.push({
|
|
3253
3554
|
start: group[0],
|
|
3254
|
-
|
|
3555
|
+
// A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
|
|
3556
|
+
// stop at the first one and emit the rest beside the marker. Stop at the end of
|
|
3557
|
+
// the value, a trailing comment, or a shell operator instead. The rule's own end
|
|
3558
|
+
// is not used: the colon form's value pattern includes the spaces before a
|
|
3559
|
+
// trailing `# comment`, and masking them welds the comment to the marker.
|
|
3560
|
+
end: lineValueEnd(line, group[0], context),
|
|
3255
3561
|
rule
|
|
3256
3562
|
});
|
|
3257
3563
|
matchedRules.add(rule);
|
|
@@ -3264,14 +3570,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3264
3570
|
matchedRules.add(rule);
|
|
3265
3571
|
}
|
|
3266
3572
|
}
|
|
3573
|
+
for (const span of concatenatedCredentialSpans(line)) {
|
|
3574
|
+
spans.push(span);
|
|
3575
|
+
matchedRules.add(span.rule);
|
|
3576
|
+
}
|
|
3267
3577
|
if (spans.length > 0) {
|
|
3268
|
-
|
|
3269
|
-
|
|
3578
|
+
const maskedLine = applySpans(line, spans);
|
|
3579
|
+
if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
|
|
3580
|
+
recordFinding(lineNumber, matchedRules);
|
|
3581
|
+
segments[index] = maskedLine;
|
|
3582
|
+
}
|
|
3270
3583
|
}
|
|
3271
3584
|
}
|
|
3272
3585
|
if (index + 1 < segments.length) lineNumber += 1;
|
|
3273
3586
|
}
|
|
3274
|
-
|
|
3587
|
+
let finalText = segments.join("");
|
|
3588
|
+
finalText = redactStructuredValues(finalText, filePath, recordFinding);
|
|
3589
|
+
finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
|
|
3590
|
+
const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
|
|
3591
|
+
rules: [...rulesForLine],
|
|
3592
|
+
line,
|
|
3593
|
+
path: filePath
|
|
3594
|
+
}));
|
|
3595
|
+
return { redacted: finalText, findings };
|
|
3596
|
+
}
|
|
3597
|
+
function advanceStringIndex(text2, index, unicode) {
|
|
3598
|
+
if (!unicode) return index + 1;
|
|
3599
|
+
const first = text2.charCodeAt(index);
|
|
3600
|
+
if (first >= 55296 && first <= 56319) {
|
|
3601
|
+
const second = text2.charCodeAt(index + 1);
|
|
3602
|
+
if (second >= 56320 && second <= 57343) return index + 2;
|
|
3603
|
+
}
|
|
3604
|
+
return index + 1;
|
|
3605
|
+
}
|
|
3606
|
+
var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
|
|
3607
|
+
var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
|
|
3608
|
+
function isStructuredFile(filePath) {
|
|
3609
|
+
if (filePath === void 0) return false;
|
|
3610
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3611
|
+
if (STRUCTURED_FILE.test(normalised)) return true;
|
|
3612
|
+
return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
|
|
3613
|
+
}
|
|
3614
|
+
function isDockerfile(filePath) {
|
|
3615
|
+
if (filePath === void 0) return false;
|
|
3616
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3617
|
+
return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
|
|
3618
|
+
normalised.slice(normalised.lastIndexOf("/") + 1)
|
|
3619
|
+
);
|
|
3620
|
+
}
|
|
3621
|
+
function maskLineContent(line) {
|
|
3622
|
+
if (line.trim() === "") return line;
|
|
3623
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3624
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3625
|
+
}
|
|
3626
|
+
function maskValueLine(line) {
|
|
3627
|
+
if (line.trim() === "") return line;
|
|
3628
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3629
|
+
const content = line.slice(indent.length);
|
|
3630
|
+
const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
|
|
3631
|
+
if (quoted !== null) {
|
|
3632
|
+
return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
|
|
3633
|
+
}
|
|
3634
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3635
|
+
}
|
|
3636
|
+
var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
|
|
3637
|
+
var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
|
|
3638
|
+
function redactStructuredValues(text2, filePath, recordFinding) {
|
|
3639
|
+
if (!isStructuredFile(filePath)) return text2;
|
|
3640
|
+
const segments = text2.split(LINE_BREAK);
|
|
3641
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3642
|
+
const line = segments[index];
|
|
3643
|
+
if (line === void 0 || line.length === 0) continue;
|
|
3644
|
+
const match = STRUCTURED_KEY.exec(line);
|
|
3645
|
+
if (match === null) continue;
|
|
3646
|
+
const key = match[2] ?? "";
|
|
3647
|
+
if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
|
|
3648
|
+
const baseIndent = (match[1] ?? "").length;
|
|
3649
|
+
const rest = (match[4] ?? "").trim();
|
|
3650
|
+
if (BLOCK_SCALAR.test(rest)) {
|
|
3651
|
+
let cursor2 = index + 2;
|
|
3652
|
+
let masked2 = false;
|
|
3653
|
+
while (cursor2 < segments.length) {
|
|
3654
|
+
const body = segments[cursor2] ?? "";
|
|
3655
|
+
if (body.trim() !== "") {
|
|
3656
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3657
|
+
if (indent <= baseIndent) break;
|
|
3658
|
+
segments[cursor2] = maskLineContent(body);
|
|
3659
|
+
masked2 = true;
|
|
3660
|
+
}
|
|
3661
|
+
cursor2 += 2;
|
|
3662
|
+
}
|
|
3663
|
+
if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
|
|
3664
|
+
continue;
|
|
3665
|
+
}
|
|
3666
|
+
if (rest !== "") continue;
|
|
3667
|
+
let cursor = index + 2;
|
|
3668
|
+
while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
|
|
3669
|
+
const firstValue = segments[cursor];
|
|
3670
|
+
if (firstValue === void 0) continue;
|
|
3671
|
+
const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
|
|
3672
|
+
if (valueIndent <= baseIndent) continue;
|
|
3673
|
+
let masked = false;
|
|
3674
|
+
while (cursor < segments.length) {
|
|
3675
|
+
const body = segments[cursor] ?? "";
|
|
3676
|
+
if (body.trim() !== "") {
|
|
3677
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3678
|
+
if (indent < valueIndent) break;
|
|
3679
|
+
segments[cursor] = maskValueLine(body);
|
|
3680
|
+
masked = true;
|
|
3681
|
+
}
|
|
3682
|
+
cursor += 2;
|
|
3683
|
+
}
|
|
3684
|
+
if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
|
|
3685
|
+
}
|
|
3686
|
+
return segments.join("");
|
|
3687
|
+
}
|
|
3688
|
+
var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
|
|
3689
|
+
function redactDockerfileEnv(text2, filePath, recordFinding) {
|
|
3690
|
+
if (!isDockerfile(filePath)) return text2;
|
|
3691
|
+
const segments = text2.split(LINE_BREAK);
|
|
3692
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3693
|
+
const line = segments[index];
|
|
3694
|
+
if (line === void 0) continue;
|
|
3695
|
+
const match = DOCKERFILE_ENV.exec(line);
|
|
3696
|
+
if (match === null) continue;
|
|
3697
|
+
if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
|
|
3698
|
+
const value = match[4] ?? "";
|
|
3699
|
+
if (value.startsWith("=")) continue;
|
|
3700
|
+
segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
|
|
3701
|
+
recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
|
|
3702
|
+
}
|
|
3703
|
+
return segments.join("");
|
|
3704
|
+
}
|
|
3705
|
+
var CONCATENATED_CREDENTIAL = new RegExp(
|
|
3706
|
+
"([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",
|
|
3707
|
+
"gid"
|
|
3708
|
+
);
|
|
3709
|
+
function concatenatedCredentialSpans(line) {
|
|
3710
|
+
const spans = [];
|
|
3711
|
+
CONCATENATED_CREDENTIAL.lastIndex = 0;
|
|
3712
|
+
let match;
|
|
3713
|
+
while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
|
|
3714
|
+
const group = match.indices?.[4];
|
|
3715
|
+
if (group !== void 0) {
|
|
3716
|
+
spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
|
|
3717
|
+
}
|
|
3718
|
+
}
|
|
3719
|
+
return spans;
|
|
3275
3720
|
}
|
|
3276
3721
|
var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
|
|
3277
3722
|
var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
|
|
@@ -3289,13 +3734,20 @@ function expandOverToken(line, start, end) {
|
|
|
3289
3734
|
while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
|
|
3290
3735
|
return { start: left, end: right };
|
|
3291
3736
|
}
|
|
3292
|
-
function startsInsideStringLiteral(line, matchIndex, valueStart) {
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
if (before !== '"' && before !== "'" && before !== "`") return false;
|
|
3737
|
+
function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
|
|
3738
|
+
const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
|
|
3739
|
+
if (quote === 0) return false;
|
|
3740
|
+
if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
|
|
3297
3741
|
if (valueStart === void 0) return true;
|
|
3298
|
-
|
|
3742
|
+
for (let index = matchIndex; index < valueStart; index += 1) {
|
|
3743
|
+
const code = line.charCodeAt(index);
|
|
3744
|
+
if (code === 92) {
|
|
3745
|
+
index += 1;
|
|
3746
|
+
} else if (code === quote) {
|
|
3747
|
+
return true;
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
return false;
|
|
3299
3751
|
}
|
|
3300
3752
|
function isTemplateInterpolation(line, start, end) {
|
|
3301
3753
|
if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
|
|
@@ -3323,6 +3775,40 @@ function isSelfNamingConstant(line, start, end) {
|
|
|
3323
3775
|
}
|
|
3324
3776
|
return line.endsWith(value, index);
|
|
3325
3777
|
}
|
|
3778
|
+
var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
|
|
3779
|
+
function isSourceCodeFile(filePath) {
|
|
3780
|
+
return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
|
|
3781
|
+
}
|
|
3782
|
+
var PLACEHOLDER_PATTERNS = [
|
|
3783
|
+
/^<[^>]*>?$/,
|
|
3784
|
+
/^\.{3,}$/,
|
|
3785
|
+
/^(?:x{4,}|X{4,}|\*{3,})$/,
|
|
3786
|
+
/^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
|
|
3787
|
+
/^your[-_ ].*$/i,
|
|
3788
|
+
/^(?:example|sample)(?:[-_ ].*)?$/i
|
|
3789
|
+
];
|
|
3790
|
+
function isPlaceholderValue(value) {
|
|
3791
|
+
const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
|
|
3792
|
+
if (trimmed.length === 0) return false;
|
|
3793
|
+
if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
|
|
3794
|
+
return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
|
|
3795
|
+
}
|
|
3796
|
+
function quotesAreBalanced(text2) {
|
|
3797
|
+
let single = 0;
|
|
3798
|
+
let double = 0;
|
|
3799
|
+
let backtick = 0;
|
|
3800
|
+
for (let index = 0; index < text2.length; index += 1) {
|
|
3801
|
+
const char = text2[index];
|
|
3802
|
+
if (char === "\\") {
|
|
3803
|
+
index += 1;
|
|
3804
|
+
continue;
|
|
3805
|
+
}
|
|
3806
|
+
if (char === '"') double += 1;
|
|
3807
|
+
else if (char === "'") single += 1;
|
|
3808
|
+
else if (char === "`") backtick += 1;
|
|
3809
|
+
}
|
|
3810
|
+
return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
|
|
3811
|
+
}
|
|
3326
3812
|
function assignmentAround(line, valueStart) {
|
|
3327
3813
|
let index = valueStart;
|
|
3328
3814
|
while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
|
|
@@ -3392,6 +3878,16 @@ function applySpans(line, spans) {
|
|
|
3392
3878
|
return out;
|
|
3393
3879
|
}
|
|
3394
3880
|
|
|
3881
|
+
// src/version.ts
|
|
3882
|
+
var GENERATOR_NAME = "codebase-snapshot";
|
|
3883
|
+
var GENERATOR_VERSION = "0.9.17";
|
|
3884
|
+
var SCHEMA_VERSION = "3.0.0";
|
|
3885
|
+
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
3886
|
+
function isOurGeneratorName(name) {
|
|
3887
|
+
if (typeof name !== "string") return false;
|
|
3888
|
+
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
3889
|
+
}
|
|
3890
|
+
|
|
3395
3891
|
// src/scanner/files.ts
|
|
3396
3892
|
function isDiscoveryMode(value) {
|
|
3397
3893
|
return value === "auto" || value === "git" || value === "walk";
|
|
@@ -3401,7 +3897,7 @@ var PRESET_IGNORES = new Set(
|
|
|
3401
3897
|
);
|
|
3402
3898
|
function readLinkTarget(linkPath, fallback) {
|
|
3403
3899
|
try {
|
|
3404
|
-
return
|
|
3900
|
+
return fs15__namespace.readlinkSync(linkPath);
|
|
3405
3901
|
} catch {
|
|
3406
3902
|
return fallback;
|
|
3407
3903
|
}
|
|
@@ -3416,8 +3912,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
|
|
|
3416
3912
|
};
|
|
3417
3913
|
}
|
|
3418
3914
|
function isInside(root, candidate) {
|
|
3419
|
-
const
|
|
3420
|
-
return
|
|
3915
|
+
const relative10 = path16__namespace.relative(root, candidate);
|
|
3916
|
+
return relative10 === "" || !relative10.startsWith(`..${path16__namespace.sep}`) && relative10 !== ".." && !path16__namespace.isAbsolute(relative10);
|
|
3421
3917
|
}
|
|
3422
3918
|
var GIT_OUTPUT_LIMIT = 68157440;
|
|
3423
3919
|
function getGitInfo(cwd, fallbackBranch = "main") {
|
|
@@ -3478,10 +3974,10 @@ var DEFAULT_IGNORED_FILES = [
|
|
|
3478
3974
|
"bun.lockb",
|
|
3479
3975
|
"composer.lock"
|
|
3480
3976
|
];
|
|
3481
|
-
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;
|
|
3482
|
-
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
|
|
3977
|
+
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;
|
|
3978
|
+
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
|
|
3483
3979
|
var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
|
|
3484
|
-
var TEMPLATE_SUFFIX =
|
|
3980
|
+
var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
|
|
3485
3981
|
var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
|
|
3486
3982
|
function normaliseName(name) {
|
|
3487
3983
|
let normalised = name.trim().replace(/[. ]+$/, "");
|
|
@@ -3497,12 +3993,16 @@ function isSensitivePath(relativePath) {
|
|
|
3497
3993
|
const posixPath = relativePath.replace(/\\/g, "/");
|
|
3498
3994
|
const raw = posixPath.split("/").pop() ?? posixPath;
|
|
3499
3995
|
const base = normaliseName(raw);
|
|
3500
|
-
if (
|
|
3501
|
-
const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
|
|
3502
|
-
if (matchesSensitiveList(posixPath, stripped)) return false;
|
|
3503
|
-
}
|
|
3996
|
+
if (templateOfCredentialFile(posixPath, base)) return false;
|
|
3504
3997
|
return matchesSensitiveList(posixPath, base);
|
|
3505
3998
|
}
|
|
3999
|
+
function templateOfCredentialFile(posixPath, base) {
|
|
4000
|
+
const match = TEMPLATE_SUFFIX.exec(base);
|
|
4001
|
+
if (match === null) return null;
|
|
4002
|
+
const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
|
|
4003
|
+
if (SENSITIVE_EXT.test(stripped)) return null;
|
|
4004
|
+
return matchesSensitiveList(posixPath, stripped) ? stripped : null;
|
|
4005
|
+
}
|
|
3506
4006
|
var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
|
|
3507
4007
|
var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
3508
4008
|
var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
@@ -3534,7 +4034,7 @@ function findSecretInPath(relativePath, extraRules) {
|
|
|
3534
4034
|
let match;
|
|
3535
4035
|
while ((match = scan.exec(posixPath)) !== null) {
|
|
3536
4036
|
if (match[0].length === 0) {
|
|
3537
|
-
scan.lastIndex
|
|
4037
|
+
scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
|
|
3538
4038
|
continue;
|
|
3539
4039
|
}
|
|
3540
4040
|
spans.push({ start: match.index, end: match.index + match[0].length });
|
|
@@ -3595,11 +4095,14 @@ function globBodyToRegExp(body, allowBraces) {
|
|
|
3595
4095
|
if (char === "*") {
|
|
3596
4096
|
if (body[i + 1] === "*") {
|
|
3597
4097
|
i += 1;
|
|
3598
|
-
|
|
4098
|
+
const startsSegment = i - 2 < 0 || body[i - 2] === "/";
|
|
4099
|
+
if (startsSegment && body[i + 1] === "/") {
|
|
3599
4100
|
i += 1;
|
|
3600
|
-
out += "(
|
|
3601
|
-
} else {
|
|
4101
|
+
out += "(?:[^/]+/)*";
|
|
4102
|
+
} else if (startsSegment && i + 1 === body.length) {
|
|
3602
4103
|
out += ".*";
|
|
4104
|
+
} else {
|
|
4105
|
+
out += "[^/]*";
|
|
3603
4106
|
}
|
|
3604
4107
|
} else {
|
|
3605
4108
|
out += "[^/]*";
|
|
@@ -3668,10 +4171,10 @@ function trimUnescapedTrailingSpaces(line) {
|
|
|
3668
4171
|
return line.slice(0, end);
|
|
3669
4172
|
}
|
|
3670
4173
|
function readGitignoreRules(dir) {
|
|
3671
|
-
const
|
|
4174
|
+
const gitignorePath2 = path16__namespace.join(dir, ".gitignore");
|
|
3672
4175
|
let raw;
|
|
3673
4176
|
try {
|
|
3674
|
-
raw =
|
|
4177
|
+
raw = fs15__namespace.readFileSync(gitignorePath2, "utf8");
|
|
3675
4178
|
} catch {
|
|
3676
4179
|
return [];
|
|
3677
4180
|
}
|
|
@@ -3844,10 +4347,49 @@ function listIgnoredPaths(cwd) {
|
|
|
3844
4347
|
}
|
|
3845
4348
|
function hasSnapshotMarker(target) {
|
|
3846
4349
|
try {
|
|
3847
|
-
return
|
|
4350
|
+
return fs15__namespace.statSync(target).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(target, ".codebase-snapshot"));
|
|
4351
|
+
} catch {
|
|
4352
|
+
return false;
|
|
4353
|
+
}
|
|
4354
|
+
}
|
|
4355
|
+
var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
|
|
4356
|
+
function isToolOwnedDirectory2(dir) {
|
|
4357
|
+
let raw;
|
|
4358
|
+
try {
|
|
4359
|
+
raw = fs15__namespace.readFileSync(path16__namespace.join(dir, ".codebase-snapshot"), "utf8");
|
|
4360
|
+
} catch {
|
|
4361
|
+
return false;
|
|
4362
|
+
}
|
|
4363
|
+
let parsed;
|
|
4364
|
+
try {
|
|
4365
|
+
parsed = JSON.parse(raw);
|
|
4366
|
+
} catch {
|
|
4367
|
+
return false;
|
|
4368
|
+
}
|
|
4369
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
4370
|
+
const marker2 = parsed;
|
|
4371
|
+
if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
|
|
4372
|
+
return false;
|
|
4373
|
+
}
|
|
4374
|
+
const accounted = /* @__PURE__ */ new Set();
|
|
4375
|
+
for (const item of marker2.files) {
|
|
4376
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
|
|
4377
|
+
const entry = item.path;
|
|
4378
|
+
if (typeof entry !== "string" || entry.length === 0) return false;
|
|
4379
|
+
const parts = entry.split("/");
|
|
4380
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
4381
|
+
accounted.add(parts.slice(0, depth).join("/"));
|
|
4382
|
+
}
|
|
4383
|
+
}
|
|
4384
|
+
let entries;
|
|
4385
|
+
try {
|
|
4386
|
+
entries = fs15__namespace.readdirSync(dir);
|
|
3848
4387
|
} catch {
|
|
3849
4388
|
return false;
|
|
3850
4389
|
}
|
|
4390
|
+
return entries.every(
|
|
4391
|
+
(entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
|
|
4392
|
+
);
|
|
3851
4393
|
}
|
|
3852
4394
|
function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
3853
4395
|
const markers = /* @__PURE__ */ new Map();
|
|
@@ -3858,7 +4400,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
|
3858
4400
|
const prefix = parts.slice(0, depth).join("/");
|
|
3859
4401
|
let hasMarker = markers.get(prefix);
|
|
3860
4402
|
if (hasMarker === void 0) {
|
|
3861
|
-
hasMarker =
|
|
4403
|
+
hasMarker = isToolOwnedDirectory2(path16__namespace.join(cwd, prefix));
|
|
3862
4404
|
markers.set(prefix, hasMarker);
|
|
3863
4405
|
}
|
|
3864
4406
|
if (hasMarker) return true;
|
|
@@ -3873,7 +4415,7 @@ function makeLinkProbe() {
|
|
|
3873
4415
|
let known = cache.get(absolutePath);
|
|
3874
4416
|
if (known === void 0) {
|
|
3875
4417
|
try {
|
|
3876
|
-
known =
|
|
4418
|
+
known = fs15__namespace.lstatSync(absolutePath).isSymbolicLink();
|
|
3877
4419
|
} catch {
|
|
3878
4420
|
known = false;
|
|
3879
4421
|
}
|
|
@@ -3886,7 +4428,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3886
4428
|
const isLink = makeLinkProbe();
|
|
3887
4429
|
let rootReal = cwd;
|
|
3888
4430
|
try {
|
|
3889
|
-
rootReal =
|
|
4431
|
+
rootReal = fs15__namespace.realpathSync(cwd);
|
|
3890
4432
|
} catch {
|
|
3891
4433
|
}
|
|
3892
4434
|
const reported = /* @__PURE__ */ new Set();
|
|
@@ -3914,7 +4456,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3914
4456
|
const rawTarget = readLinkTarget(absolute, absolute);
|
|
3915
4457
|
let targetReal = null;
|
|
3916
4458
|
try {
|
|
3917
|
-
targetReal =
|
|
4459
|
+
targetReal = fs15__namespace.realpathSync(absolute);
|
|
3918
4460
|
} catch {
|
|
3919
4461
|
targetReal = null;
|
|
3920
4462
|
}
|
|
@@ -3932,7 +4474,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3932
4474
|
}
|
|
3933
4475
|
let stats = null;
|
|
3934
4476
|
try {
|
|
3935
|
-
stats =
|
|
4477
|
+
stats = fs15__namespace.statSync(absolute);
|
|
3936
4478
|
} catch {
|
|
3937
4479
|
stats = null;
|
|
3938
4480
|
}
|
|
@@ -4020,7 +4562,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4020
4562
|
"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."
|
|
4021
4563
|
);
|
|
4022
4564
|
}
|
|
4023
|
-
if (
|
|
4565
|
+
if (fs15__namespace.existsSync(path16__namespace.join(cwd, ".git"))) {
|
|
4024
4566
|
throw new Error(
|
|
4025
4567
|
"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."
|
|
4026
4568
|
);
|
|
@@ -4030,6 +4572,15 @@ function collectFiles(cwd, options = {}) {
|
|
|
4030
4572
|
for (const record of walked.skipped) skipped.push(record);
|
|
4031
4573
|
}
|
|
4032
4574
|
}
|
|
4575
|
+
const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
|
|
4576
|
+
if (extraPaths.length > 0) {
|
|
4577
|
+
const known = new Set(candidates);
|
|
4578
|
+
for (const extra of extraPaths) {
|
|
4579
|
+
if (extra.length === 0 || known.has(extra)) continue;
|
|
4580
|
+
known.add(extra);
|
|
4581
|
+
candidates.push(extra);
|
|
4582
|
+
}
|
|
4583
|
+
}
|
|
4033
4584
|
const files = candidates.filter((file) => {
|
|
4034
4585
|
if (isToolOwned(file)) return false;
|
|
4035
4586
|
const ignored = defaultIgnoreReason(file, toolDirNames);
|
|
@@ -4079,7 +4630,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4079
4630
|
}
|
|
4080
4631
|
function rootRealFor(root) {
|
|
4081
4632
|
try {
|
|
4082
|
-
return
|
|
4633
|
+
return fs15__namespace.realpathSync(root);
|
|
4083
4634
|
} catch {
|
|
4084
4635
|
return root;
|
|
4085
4636
|
}
|
|
@@ -4099,7 +4650,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4099
4650
|
];
|
|
4100
4651
|
let entries;
|
|
4101
4652
|
try {
|
|
4102
|
-
entries =
|
|
4653
|
+
entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
|
|
4103
4654
|
} catch {
|
|
4104
4655
|
results.skipped.push({
|
|
4105
4656
|
path: relativeToBase(current),
|
|
@@ -4155,14 +4706,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4155
4706
|
if (entry.isSymbolicLink()) {
|
|
4156
4707
|
let targetReal;
|
|
4157
4708
|
try {
|
|
4158
|
-
targetReal =
|
|
4709
|
+
targetReal = fs15__namespace.realpathSync(fullPath);
|
|
4159
4710
|
} catch {
|
|
4160
4711
|
results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
|
|
4161
4712
|
continue;
|
|
4162
4713
|
}
|
|
4163
4714
|
let stats;
|
|
4164
4715
|
try {
|
|
4165
|
-
stats =
|
|
4716
|
+
stats = fs15__namespace.statSync(fullPath);
|
|
4166
4717
|
} catch {
|
|
4167
4718
|
results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
|
|
4168
4719
|
continue;
|
|
@@ -4192,6 +4743,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4192
4743
|
});
|
|
4193
4744
|
continue;
|
|
4194
4745
|
}
|
|
4746
|
+
const targetRelative = path16__namespace.relative(rootReal, targetReal).split(path16__namespace.sep).join("/");
|
|
4747
|
+
if (isSensitivePath(targetRelative)) {
|
|
4748
|
+
results.skipped.push({
|
|
4749
|
+
path: relPath,
|
|
4750
|
+
reason: "sensitive-file",
|
|
4751
|
+
detail: "link target is a credential-bearing file; not followed"
|
|
4752
|
+
});
|
|
4753
|
+
continue;
|
|
4754
|
+
}
|
|
4195
4755
|
isDirectory = false;
|
|
4196
4756
|
isFile = true;
|
|
4197
4757
|
}
|
|
@@ -4491,17 +5051,34 @@ function readConfigExport(exported, file) {
|
|
|
4491
5051
|
assertKnownConfigKeys(exported, file);
|
|
4492
5052
|
return exported;
|
|
4493
5053
|
}
|
|
4494
|
-
var
|
|
5054
|
+
var lastModuleConfig = null;
|
|
5055
|
+
function moduleConfigKey(fullPath) {
|
|
5056
|
+
try {
|
|
5057
|
+
return crypto2.createHash("sha256").update(fs15__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
|
|
5058
|
+
} catch {
|
|
5059
|
+
try {
|
|
5060
|
+
const stats = fs15__namespace.statSync(fullPath);
|
|
5061
|
+
return `stat-${stats.mtimeMs}-${stats.size}`;
|
|
5062
|
+
} catch {
|
|
5063
|
+
return "unreadable";
|
|
5064
|
+
}
|
|
5065
|
+
}
|
|
5066
|
+
}
|
|
4495
5067
|
async function importConfigModule(fullPath) {
|
|
5068
|
+
const key = moduleConfigKey(fullPath);
|
|
5069
|
+
if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
|
|
5070
|
+
return lastModuleConfig.exports;
|
|
5071
|
+
}
|
|
4496
5072
|
try {
|
|
4497
5073
|
const requireFromConfig = module$1.createRequire(fullPath);
|
|
4498
5074
|
delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
|
|
4499
5075
|
} catch {
|
|
4500
5076
|
}
|
|
4501
5077
|
const url$1 = url.pathToFileURL(fullPath);
|
|
4502
|
-
|
|
4503
|
-
url$1.
|
|
4504
|
-
|
|
5078
|
+
url$1.searchParams.set("codebaseSnapshotLoad", key);
|
|
5079
|
+
const loaded = await import(url$1.href);
|
|
5080
|
+
lastModuleConfig = { path: fullPath, key, exports: loaded };
|
|
5081
|
+
return loaded;
|
|
4505
5082
|
}
|
|
4506
5083
|
function attachConfigDir(config, filePath) {
|
|
4507
5084
|
if (typeof config === "object" && config !== null) {
|
|
@@ -4513,15 +5090,25 @@ function attachConfigDir(config, filePath) {
|
|
|
4513
5090
|
}
|
|
4514
5091
|
return config;
|
|
4515
5092
|
}
|
|
4516
|
-
async function loadConfigFileDetailed(cwd) {
|
|
5093
|
+
async function loadConfigFileDetailed(cwd, options = {}) {
|
|
4517
5094
|
const warnings = [];
|
|
4518
5095
|
const errors = [];
|
|
5096
|
+
const configDirectories = [];
|
|
4519
5097
|
for (const filename of CONFIG_FILENAMES) {
|
|
4520
5098
|
const fullPath = path16__namespace.join(cwd, filename);
|
|
4521
|
-
|
|
5099
|
+
let candidateStats = null;
|
|
5100
|
+
try {
|
|
5101
|
+
candidateStats = fs15__namespace.statSync(fullPath);
|
|
5102
|
+
} catch {
|
|
5103
|
+
if (!fs15__namespace.existsSync(fullPath)) continue;
|
|
5104
|
+
}
|
|
5105
|
+
if (candidateStats !== null && !candidateStats.isFile()) {
|
|
5106
|
+
configDirectories.push(fullPath);
|
|
5107
|
+
continue;
|
|
5108
|
+
}
|
|
4522
5109
|
if (filename.endsWith(".json") || filename === ".snapshotrc") {
|
|
4523
5110
|
try {
|
|
4524
|
-
const config = parseJsonish(
|
|
5111
|
+
const config = parseJsonish(fs15__namespace.readFileSync(fullPath, "utf8"), fullPath);
|
|
4525
5112
|
if (config === null || typeof config !== "object" || Array.isArray(config)) {
|
|
4526
5113
|
throw new Error(
|
|
4527
5114
|
`${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
|
|
@@ -4537,6 +5124,12 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4537
5124
|
continue;
|
|
4538
5125
|
}
|
|
4539
5126
|
}
|
|
5127
|
+
if (options.allowExecutableConfig === false) {
|
|
5128
|
+
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.`;
|
|
5129
|
+
warnings.push(message);
|
|
5130
|
+
errors.push(message);
|
|
5131
|
+
continue;
|
|
5132
|
+
}
|
|
4540
5133
|
if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
|
|
4541
5134
|
warnings.push(
|
|
4542
5135
|
`${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
|
|
@@ -4556,9 +5149,9 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4556
5149
|
}
|
|
4557
5150
|
}
|
|
4558
5151
|
const pkgJsonPath = path16__namespace.join(cwd, "package.json");
|
|
4559
|
-
if (
|
|
5152
|
+
if (fs15__namespace.existsSync(pkgJsonPath)) {
|
|
4560
5153
|
try {
|
|
4561
|
-
const parsed = parseJsonish(
|
|
5154
|
+
const parsed = parseJsonish(fs15__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
|
|
4562
5155
|
const snapshotKey = parsed.snapshot;
|
|
4563
5156
|
if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
|
|
4564
5157
|
assertKnownConfigKeys(
|
|
@@ -4584,6 +5177,11 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4584
5177
|
errors.push(message);
|
|
4585
5178
|
}
|
|
4586
5179
|
}
|
|
5180
|
+
if (configDirectories.length > 0) {
|
|
5181
|
+
warnings.push(
|
|
5182
|
+
`${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
|
|
5183
|
+
);
|
|
5184
|
+
}
|
|
4587
5185
|
return { config: null, file: null, warnings, errors };
|
|
4588
5186
|
}
|
|
4589
5187
|
async function loadConfigFile(cwd) {
|
|
@@ -4759,11 +5357,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
|
|
|
4759
5357
|
const patterns = [];
|
|
4760
5358
|
for (const dir of [outDir, tmpDir]) {
|
|
4761
5359
|
const absolute = path16__namespace.resolve(cwd, dir);
|
|
4762
|
-
const
|
|
4763
|
-
if (!
|
|
5360
|
+
const relative10 = path16__namespace.relative(cwd, absolute);
|
|
5361
|
+
if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative10)) {
|
|
4764
5362
|
continue;
|
|
4765
5363
|
}
|
|
4766
|
-
patterns.push(`${
|
|
5364
|
+
patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
|
|
4767
5365
|
}
|
|
4768
5366
|
return patterns;
|
|
4769
5367
|
}
|
|
@@ -4894,10 +5492,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
|
|
|
4894
5492
|
}
|
|
4895
5493
|
const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
|
|
4896
5494
|
const resolved = path16__namespace.resolve(candidate);
|
|
4897
|
-
if (!
|
|
5495
|
+
if (!fs15__namespace.existsSync(resolved)) {
|
|
4898
5496
|
throw new Error(`Working directory does not exist: ${resolved}`);
|
|
4899
5497
|
}
|
|
4900
|
-
if (!
|
|
5498
|
+
if (!fs15__namespace.statSync(resolved).isDirectory()) {
|
|
4901
5499
|
throw new Error(`Working directory is not a directory: ${resolved}`);
|
|
4902
5500
|
}
|
|
4903
5501
|
return resolved;
|
|
@@ -5147,6 +5745,13 @@ function configDigest(config) {
|
|
|
5147
5745
|
// moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
|
|
5148
5746
|
// digest, so `validate` reported "valid and up to date" for a snapshot whose files
|
|
5149
5747
|
// had all been reclassified — and per-layer budgets applied to different files.
|
|
5748
|
+
// A function matcher's `String()` is its source, not its closure: two functions with the same
|
|
5749
|
+
// body but different captured values digest identically. That cannot be fixed by hashing, so
|
|
5750
|
+
// the digest records that executable matchers are present and `validate` says the digest does
|
|
5751
|
+
// not cover their closure, instead of claiming a equality it cannot prove.
|
|
5752
|
+
executableMatchers: [...config.layers, ...config.kinds].some(
|
|
5753
|
+
(rule) => typeof rule.match === "function"
|
|
5754
|
+
),
|
|
5150
5755
|
layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
|
|
5151
5756
|
kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
|
|
5152
5757
|
// How files are enumerated decides what is in the snapshot at all.
|
|
@@ -5203,8 +5808,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5203
5808
|
`**Generated:** ${manifest.generatedAt} `,
|
|
5204
5809
|
`**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
|
|
5205
5810
|
`**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
|
|
5206
|
-
`**
|
|
5207
|
-
`**
|
|
5811
|
+
`**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
|
|
5812
|
+
`**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
|
|
5813
|
+
`**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
|
|
5208
5814
|
// This counts the bytes that were *emitted* after redaction, not the bytes
|
|
5209
5815
|
// that were masked: calling it "redacted bytes" made a repository with zero
|
|
5210
5816
|
// secrets report a non-zero redacted-byte figure directly above "no secrets
|
|
@@ -5244,9 +5850,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5244
5850
|
const parseIssues = manifest.files.filter(
|
|
5245
5851
|
(file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
|
|
5246
5852
|
);
|
|
5853
|
+
const unparsedPreviews = manifest.files.filter(
|
|
5854
|
+
(file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
|
|
5855
|
+
).length;
|
|
5247
5856
|
lines.push("## 2. Parse & AST Diagnostics", "");
|
|
5248
5857
|
if (parseIssues.length === 0) {
|
|
5249
|
-
|
|
5858
|
+
if (unparsedPreviews > 0) {
|
|
5859
|
+
lines.push(
|
|
5860
|
+
`\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.`,
|
|
5861
|
+
""
|
|
5862
|
+
);
|
|
5863
|
+
} else {
|
|
5864
|
+
lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
|
|
5865
|
+
}
|
|
5250
5866
|
} else {
|
|
5251
5867
|
lines.push(
|
|
5252
5868
|
`${parseIssues.length} file(s) produced an incomplete summary:`,
|
|
@@ -5446,9 +6062,9 @@ function truncateToBytes(content, maxBytes) {
|
|
|
5446
6062
|
if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
|
|
5447
6063
|
const buffer = Buffer.from(content, "utf8");
|
|
5448
6064
|
if (buffer.length <= maxBytes) return { content, isTruncated: false };
|
|
5449
|
-
let
|
|
5450
|
-
while (
|
|
5451
|
-
return { content:
|
|
6065
|
+
let end = maxBytes;
|
|
6066
|
+
while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
|
|
6067
|
+
return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
|
|
5452
6068
|
}
|
|
5453
6069
|
function truncatePreview(content, headLines, tailLines) {
|
|
5454
6070
|
const normalised = normaliseLineEndings(content);
|
|
@@ -5531,19 +6147,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5531
6147
|
for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
|
|
5532
6148
|
}
|
|
5533
6149
|
if (groups.length === 0) return [];
|
|
5534
|
-
const
|
|
6150
|
+
const assemblies = /* @__PURE__ */ new Map();
|
|
5535
6151
|
const widthOf = (total) => Math.max(3, String(total).length);
|
|
5536
|
-
const
|
|
5537
|
-
const cached = measurements.get(group);
|
|
6152
|
+
const assemble = (group, index, total) => {
|
|
5538
6153
|
const width = widthOf(total);
|
|
6154
|
+
const cached = assemblies.get(group);
|
|
5539
6155
|
if (cached !== void 0 && cached.index === index && cached.width === width) {
|
|
5540
|
-
return cached.
|
|
6156
|
+
return cached.value;
|
|
5541
6157
|
}
|
|
5542
|
-
const
|
|
5543
|
-
|
|
5544
|
-
|
|
5545
|
-
return size2;
|
|
6158
|
+
const value = assembleGroup(group, index, total, contentFingerprint);
|
|
6159
|
+
assemblies.set(group, { index, width, value });
|
|
6160
|
+
return value;
|
|
5546
6161
|
};
|
|
6162
|
+
const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
|
|
5547
6163
|
for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
|
|
5548
6164
|
const total = groups.length;
|
|
5549
6165
|
let oversized = -1;
|
|
@@ -5554,16 +6170,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5554
6170
|
break;
|
|
5555
6171
|
}
|
|
5556
6172
|
}
|
|
5557
|
-
if (oversized === -1) return renderGroups(groups, contentFingerprint);
|
|
6173
|
+
if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
|
|
5558
6174
|
const group = groups[oversized];
|
|
5559
6175
|
if (group.sections.length > 1) {
|
|
5560
6176
|
const moved = group.sections.pop();
|
|
5561
6177
|
groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
|
|
5562
|
-
|
|
6178
|
+
assemblies.delete(group);
|
|
5563
6179
|
continue;
|
|
5564
6180
|
}
|
|
5565
6181
|
const [section] = group.sections;
|
|
5566
|
-
if (section === void 0) return renderGroups(groups, contentFingerprint);
|
|
6182
|
+
if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
|
|
5567
6183
|
const overflow = measure(group, oversized, total) - group.budget;
|
|
5568
6184
|
const currentContent = section.file.content ?? "";
|
|
5569
6185
|
const shrinkTo = Math.max(
|
|
@@ -5580,10 +6196,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5580
6196
|
applyTruncatedContent(section.file, shrunk.content);
|
|
5581
6197
|
section.text = renderFileSection(section.file);
|
|
5582
6198
|
section.byteSize = Buffer.byteLength(section.text, "utf8");
|
|
5583
|
-
|
|
6199
|
+
assemblies.delete(group);
|
|
5584
6200
|
continue;
|
|
5585
6201
|
}
|
|
5586
|
-
const rendered = renderGroups(groups, contentFingerprint);
|
|
6202
|
+
const rendered = renderGroups(groups, contentFingerprint, assemble);
|
|
5587
6203
|
const marker2 = TRUNCATION_MARKER;
|
|
5588
6204
|
assertBudgetHoldsMarker(group.budget);
|
|
5589
6205
|
const target = Math.max(
|
|
@@ -5597,7 +6213,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5597
6213
|
);
|
|
5598
6214
|
return rendered;
|
|
5599
6215
|
}
|
|
5600
|
-
return renderGroups(groups, contentFingerprint).flatMap(
|
|
6216
|
+
return renderGroups(groups, contentFingerprint, assemble).flatMap(
|
|
5601
6217
|
(part) => enforceBudget([part], part.metadata.budgetBytes)
|
|
5602
6218
|
);
|
|
5603
6219
|
}
|
|
@@ -5635,8 +6251,8 @@ function renumberParts(parts, contentFingerprint) {
|
|
|
5635
6251
|
if (markerIndex === -1) {
|
|
5636
6252
|
throw new Error(`${part.filename} has no "## Contents" section to re-number.`);
|
|
5637
6253
|
}
|
|
5638
|
-
const layerCounts =
|
|
5639
|
-
const kindCounts =
|
|
6254
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6255
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5640
6256
|
for (const file of included) {
|
|
5641
6257
|
layerCounts[file.layer] = (layerCounts[file.layer] || 0) + 1;
|
|
5642
6258
|
kindCounts[file.kind] = (kindCounts[file.kind] || 0) + 1;
|
|
@@ -5833,8 +6449,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5833
6449
|
for (const section of group.sections) {
|
|
5834
6450
|
section.file.part = filename;
|
|
5835
6451
|
}
|
|
5836
|
-
const layerCounts =
|
|
5837
|
-
const kindCounts =
|
|
6452
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6453
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5838
6454
|
for (const section of group.sections) {
|
|
5839
6455
|
layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
|
|
5840
6456
|
kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
|
|
@@ -5869,15 +6485,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5869
6485
|
const estimatedTokens = estimateTokens(assembled);
|
|
5870
6486
|
return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
|
|
5871
6487
|
}
|
|
5872
|
-
function renderGroups(groups, contentFingerprint) {
|
|
6488
|
+
function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
|
|
5873
6489
|
const total = groups.length;
|
|
5874
6490
|
return groups.map((group, index) => {
|
|
5875
|
-
const { filename, content, estimatedTokens } =
|
|
5876
|
-
group,
|
|
5877
|
-
index,
|
|
5878
|
-
total,
|
|
5879
|
-
contentFingerprint
|
|
5880
|
-
);
|
|
6491
|
+
const { filename, content, estimatedTokens } = assemble(group, index, total);
|
|
5881
6492
|
const byteSize = Buffer.byteLength(content, "utf8");
|
|
5882
6493
|
const sha256 = crypto2__namespace.createHash("sha256").update(content).digest("hex");
|
|
5883
6494
|
const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
|
|
@@ -6094,9 +6705,10 @@ function generateReadme(manifest, artifacts) {
|
|
|
6094
6705
|
`- **Schema Version:** \`${manifest.schemaVersion}\``,
|
|
6095
6706
|
`- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
|
|
6096
6707
|
`- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
|
|
6097
|
-
`- **
|
|
6098
|
-
`- **
|
|
6099
|
-
`- **
|
|
6708
|
+
`- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
|
|
6709
|
+
`- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
|
|
6710
|
+
`- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6711
|
+
`- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6100
6712
|
`- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
|
|
6101
6713
|
`- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
|
|
6102
6714
|
"",
|
|
@@ -6228,7 +6840,18 @@ function gitPaths(cwd, args) {
|
|
|
6228
6840
|
`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.`
|
|
6229
6841
|
);
|
|
6230
6842
|
}
|
|
6231
|
-
return output.split("\0").
|
|
6843
|
+
return output.split("\0").filter((entry) => entry.length > 0);
|
|
6844
|
+
}
|
|
6845
|
+
function readStagedBlob(cwd, relativePath) {
|
|
6846
|
+
try {
|
|
6847
|
+
return childProcess.execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
|
|
6848
|
+
cwd,
|
|
6849
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
6850
|
+
maxBuffer: 512 * 1024 * 1024
|
|
6851
|
+
});
|
|
6852
|
+
} catch {
|
|
6853
|
+
return null;
|
|
6854
|
+
}
|
|
6232
6855
|
}
|
|
6233
6856
|
function assertUsableRef(ref) {
|
|
6234
6857
|
if (ref.startsWith("-")) {
|
|
@@ -6239,6 +6862,8 @@ function assertUsableRef(ref) {
|
|
|
6239
6862
|
}
|
|
6240
6863
|
function resolveChangedScope(cwd, request) {
|
|
6241
6864
|
const paths = /* @__PURE__ */ new Set();
|
|
6865
|
+
const stagedPaths = /* @__PURE__ */ new Set();
|
|
6866
|
+
const deletedPaths = /* @__PURE__ */ new Set();
|
|
6242
6867
|
const descriptions = [];
|
|
6243
6868
|
if (request.changedSince !== void 0) {
|
|
6244
6869
|
assertUsableRef(request.changedSince);
|
|
@@ -6247,7 +6872,17 @@ function resolveChangedScope(cwd, request) {
|
|
|
6247
6872
|
"--name-only",
|
|
6248
6873
|
"-z",
|
|
6249
6874
|
"--relative",
|
|
6250
|
-
request.changedSince
|
|
6875
|
+
`${request.changedSince}...HEAD`,
|
|
6876
|
+
"--"
|
|
6877
|
+
])) {
|
|
6878
|
+
paths.add(path17);
|
|
6879
|
+
}
|
|
6880
|
+
for (const path17 of gitPaths(cwd, [
|
|
6881
|
+
"diff",
|
|
6882
|
+
"--name-only",
|
|
6883
|
+
"-z",
|
|
6884
|
+
"--relative",
|
|
6885
|
+
"HEAD",
|
|
6251
6886
|
"--"
|
|
6252
6887
|
])) {
|
|
6253
6888
|
paths.add(path17);
|
|
@@ -6267,10 +6902,22 @@ function resolveChangedScope(cwd, request) {
|
|
|
6267
6902
|
"--"
|
|
6268
6903
|
])) {
|
|
6269
6904
|
paths.add(path17);
|
|
6905
|
+
stagedPaths.add(path17);
|
|
6906
|
+
}
|
|
6907
|
+
for (const path17 of gitPaths(cwd, [
|
|
6908
|
+
"diff",
|
|
6909
|
+
"--cached",
|
|
6910
|
+
"--name-only",
|
|
6911
|
+
"-z",
|
|
6912
|
+
"--relative",
|
|
6913
|
+
"--diff-filter=D",
|
|
6914
|
+
"--"
|
|
6915
|
+
])) {
|
|
6916
|
+
deletedPaths.add(path17);
|
|
6270
6917
|
}
|
|
6271
6918
|
descriptions.push("staged");
|
|
6272
6919
|
}
|
|
6273
|
-
return { paths, detail: descriptions.join(" and ") };
|
|
6920
|
+
return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
|
|
6274
6921
|
}
|
|
6275
6922
|
var RELATIVE_SPECIFIER = /^\.{1,2}\//;
|
|
6276
6923
|
var IMPORT_CANDIDATE_SUFFIXES = [
|
|
@@ -6301,34 +6948,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
|
|
|
6301
6948
|
var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
|
|
6302
6949
|
var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
|
|
6303
6950
|
var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
|
|
6304
|
-
|
|
6951
|
+
var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
|
|
6952
|
+
var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
|
|
6953
|
+
function tsconfigPathsFor(cwd) {
|
|
6954
|
+
const configPath = path16__namespace.join(cwd, "tsconfig.json");
|
|
6955
|
+
let stats;
|
|
6956
|
+
try {
|
|
6957
|
+
stats = fs15__namespace.statSync(configPath);
|
|
6958
|
+
} catch (err) {
|
|
6959
|
+
if (err.code === "ENOENT") return null;
|
|
6960
|
+
return null;
|
|
6961
|
+
}
|
|
6962
|
+
const key = `${stats.mtimeMs}:${stats.size}`;
|
|
6963
|
+
const cached = TSCONFIG_CACHE.get(configPath);
|
|
6964
|
+
if (cached !== void 0 && cached.key === key) return cached.value;
|
|
6965
|
+
let value = null;
|
|
6966
|
+
try {
|
|
6967
|
+
const read = ts__default.default.readConfigFile(configPath, ts__default.default.sys.readFile);
|
|
6968
|
+
if (read.error === void 0) {
|
|
6969
|
+
const parsed = ts__default.default.parseJsonConfigFileContent(read.config, ts__default.default.sys, cwd, void 0, configPath);
|
|
6970
|
+
const options = parsed.options;
|
|
6971
|
+
const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
|
|
6972
|
+
const rules = [];
|
|
6973
|
+
if (options.paths !== void 0) {
|
|
6974
|
+
for (const [pattern, targets] of Object.entries(options.paths)) {
|
|
6975
|
+
if (!Array.isArray(targets)) continue;
|
|
6976
|
+
rules.push({
|
|
6977
|
+
pattern,
|
|
6978
|
+
targets: targets.map((target) => String(target).replace(/\\/g, "/"))
|
|
6979
|
+
});
|
|
6980
|
+
}
|
|
6981
|
+
}
|
|
6982
|
+
if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
|
|
6983
|
+
}
|
|
6984
|
+
} catch (err) {
|
|
6985
|
+
value = null;
|
|
6986
|
+
}
|
|
6987
|
+
TSCONFIG_CACHE.set(configPath, { key, value });
|
|
6988
|
+
return value;
|
|
6989
|
+
}
|
|
6990
|
+
function repositoryRelative(cwd, target) {
|
|
6991
|
+
const relative10 = path16__namespace.relative(cwd, target).replace(/\\/g, "/");
|
|
6992
|
+
return relative10.length === 0 || !relative10.startsWith("..") && !path16__namespace.isAbsolute(relative10) ? relative10 : null;
|
|
6993
|
+
}
|
|
6994
|
+
function rememberFirst(map, key, value) {
|
|
6995
|
+
if (!map.has(key)) map.set(key, value);
|
|
6996
|
+
}
|
|
6997
|
+
function buildImportResolver(files, options = {}) {
|
|
6305
6998
|
const byPath = /* @__PURE__ */ new Map();
|
|
6306
6999
|
const byPathFolded = /* @__PURE__ */ new Map();
|
|
6307
7000
|
const byStem = /* @__PURE__ */ new Map();
|
|
6308
7001
|
const byStemFolded = /* @__PURE__ */ new Map();
|
|
6309
|
-
const
|
|
6310
|
-
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
|
|
6314
|
-
remember(byPath, relativePath, relativePath);
|
|
6315
|
-
remember(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7002
|
+
const register = (relativePath) => {
|
|
7003
|
+
rememberFirst(byPath, relativePath, relativePath);
|
|
7004
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7005
|
+
rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7006
|
+
}
|
|
6316
7007
|
const extension = path16__namespace.posix.extname(relativePath);
|
|
6317
|
-
if (!SOURCE_EXTENSIONS.has(extension))
|
|
7008
|
+
if (!SOURCE_EXTENSIONS.has(extension)) return;
|
|
6318
7009
|
const stem = relativePath.slice(0, -extension.length);
|
|
6319
|
-
|
|
6320
|
-
|
|
7010
|
+
rememberFirst(byStem, stem, relativePath);
|
|
7011
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7012
|
+
rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
|
|
7013
|
+
}
|
|
6321
7014
|
if (path16__namespace.posix.basename(stem) === "index") {
|
|
6322
7015
|
const directory = path16__namespace.posix.dirname(stem);
|
|
6323
|
-
|
|
6324
|
-
|
|
7016
|
+
rememberFirst(byStem, directory, relativePath);
|
|
7017
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7018
|
+
rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
|
|
7019
|
+
}
|
|
7020
|
+
}
|
|
7021
|
+
};
|
|
7022
|
+
for (const file of files) register(file.relativePath);
|
|
7023
|
+
if (options.extraPaths !== void 0) {
|
|
7024
|
+
for (const extra of options.extraPaths) {
|
|
7025
|
+
if (!byPath.has(extra)) register(extra);
|
|
6325
7026
|
}
|
|
6326
7027
|
}
|
|
6327
|
-
return { byPath, byPathFolded, byStem, byStemFolded };
|
|
7028
|
+
return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
|
|
6328
7029
|
}
|
|
6329
7030
|
function resolveSpecifier(fromFile, specifier, resolver) {
|
|
6330
7031
|
const extension = path16__namespace.posix.extname(fromFile).toLowerCase();
|
|
6331
|
-
const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
|
|
7032
|
+
const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
6332
7033
|
const firstOf = (candidates) => {
|
|
6333
7034
|
for (const candidate of candidates) {
|
|
6334
7035
|
const hit = exact(candidate);
|
|
@@ -6336,6 +7037,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6336
7037
|
}
|
|
6337
7038
|
return null;
|
|
6338
7039
|
};
|
|
7040
|
+
const lookupPath = (joined2) => {
|
|
7041
|
+
const direct = exact(joined2);
|
|
7042
|
+
if (direct) return direct;
|
|
7043
|
+
for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
|
|
7044
|
+
const hit = exact(`${joined2}${suffix}`);
|
|
7045
|
+
if (hit) return hit;
|
|
7046
|
+
}
|
|
7047
|
+
const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
|
|
7048
|
+
const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
7049
|
+
return byStem(joined2) ?? byStem(stem);
|
|
7050
|
+
};
|
|
6339
7051
|
if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
|
|
6340
7052
|
const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
|
|
6341
7053
|
const rest = specifier.slice(dots).replace(/\./g, "/");
|
|
@@ -6362,19 +7074,43 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6362
7074
|
);
|
|
6363
7075
|
return firstOf([joined2, `${joined2}.dart`]);
|
|
6364
7076
|
}
|
|
6365
|
-
if (!RELATIVE_SPECIFIER.test(specifier))
|
|
7077
|
+
if (!RELATIVE_SPECIFIER.test(specifier)) {
|
|
7078
|
+
return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
|
|
7079
|
+
}
|
|
6366
7080
|
const joined = path16__namespace.posix.normalize(
|
|
6367
7081
|
path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
|
|
6368
7082
|
);
|
|
6369
|
-
|
|
6370
|
-
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
7083
|
+
return lookupPath(joined);
|
|
7084
|
+
}
|
|
7085
|
+
function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
|
|
7086
|
+
const config = resolver.tsconfig;
|
|
7087
|
+
if (!config) return null;
|
|
7088
|
+
for (const rule of config.paths) {
|
|
7089
|
+
const star = rule.pattern.indexOf("*");
|
|
7090
|
+
let captured;
|
|
7091
|
+
if (star === -1) {
|
|
7092
|
+
captured = specifier === rule.pattern ? "" : null;
|
|
7093
|
+
} else {
|
|
7094
|
+
const prefix = rule.pattern.slice(0, star);
|
|
7095
|
+
const suffix = rule.pattern.slice(star + 1);
|
|
7096
|
+
if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
|
|
7097
|
+
captured = null;
|
|
7098
|
+
} else {
|
|
7099
|
+
captured = specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
7100
|
+
}
|
|
7101
|
+
}
|
|
7102
|
+
if (captured === null) continue;
|
|
7103
|
+
for (const target of rule.targets) {
|
|
7104
|
+
const substituted = target.split("*").join(captured);
|
|
7105
|
+
const base = config.baseUrl === null ? substituted : path16__namespace.posix.join(config.baseUrl, substituted);
|
|
7106
|
+
const hit = lookupPath(path16__namespace.posix.normalize(base));
|
|
7107
|
+
if (hit) return hit;
|
|
7108
|
+
}
|
|
6374
7109
|
}
|
|
6375
|
-
|
|
6376
|
-
|
|
6377
|
-
|
|
7110
|
+
if (config.baseUrl !== null) {
|
|
7111
|
+
return lookupPath(path16__namespace.posix.normalize(path16__namespace.posix.join(config.baseUrl, specifier)));
|
|
7112
|
+
}
|
|
7113
|
+
return null;
|
|
6378
7114
|
}
|
|
6379
7115
|
function importsChangedFile(importerPath, imports, changedPaths, resolver) {
|
|
6380
7116
|
for (const specifier of imports) {
|
|
@@ -6463,7 +7199,7 @@ function findStagingDirectory(config) {
|
|
|
6463
7199
|
const tmpDir = path16__namespace.resolve(config.cwd, config.tmpDir);
|
|
6464
7200
|
let entries;
|
|
6465
7201
|
try {
|
|
6466
|
-
entries =
|
|
7202
|
+
entries = fs15__namespace.readdirSync(tmpDir);
|
|
6467
7203
|
} catch {
|
|
6468
7204
|
return null;
|
|
6469
7205
|
}
|
|
@@ -6476,8 +7212,8 @@ function describeMissingManifest(config, manifestPath) {
|
|
|
6476
7212
|
const markerPath = path16__namespace.join(outDir, ".codebase-snapshot");
|
|
6477
7213
|
let marker2 = null;
|
|
6478
7214
|
try {
|
|
6479
|
-
if (
|
|
6480
|
-
const parsed = JSON.parse(
|
|
7215
|
+
if (fs15__namespace.existsSync(markerPath)) {
|
|
7216
|
+
const parsed = JSON.parse(fs15__namespace.readFileSync(markerPath, "utf8"));
|
|
6481
7217
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
6482
7218
|
marker2 = parsed;
|
|
6483
7219
|
}
|
|
@@ -6514,11 +7250,11 @@ function sha256Hex(buffer) {
|
|
|
6514
7250
|
function wouldNowBeIncluded(cwd, relativePath) {
|
|
6515
7251
|
const absolutePath = path16__namespace.join(cwd, relativePath);
|
|
6516
7252
|
try {
|
|
6517
|
-
const stats =
|
|
7253
|
+
const stats = fs15__namespace.statSync(absolutePath);
|
|
6518
7254
|
if (!stats.isFile()) return false;
|
|
6519
7255
|
if (isBinaryExtension(absolutePath)) return false;
|
|
6520
7256
|
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
|
|
6521
|
-
return !decodeText(
|
|
7257
|
+
return !decodeText(fs15__namespace.readFileSync(absolutePath)).binary;
|
|
6522
7258
|
} catch {
|
|
6523
7259
|
return false;
|
|
6524
7260
|
}
|
|
@@ -6549,14 +7285,71 @@ function describeManifestShapeProblem(value) {
|
|
|
6549
7285
|
if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
|
|
6550
7286
|
return 'missing "totals" object';
|
|
6551
7287
|
}
|
|
7288
|
+
const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
|
|
7289
|
+
if (currentSchema) {
|
|
7290
|
+
const generator = candidate.generator;
|
|
7291
|
+
if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
|
|
7292
|
+
return 'missing "generator" object';
|
|
7293
|
+
}
|
|
7294
|
+
const generatorFields = generator;
|
|
7295
|
+
if (!isOurGeneratorName(generatorFields.name)) {
|
|
7296
|
+
return "`generator.name` is not this generator";
|
|
7297
|
+
}
|
|
7298
|
+
if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
|
|
7299
|
+
return "`generator.version` must be a non-empty string";
|
|
7300
|
+
}
|
|
7301
|
+
const git = candidate.git;
|
|
7302
|
+
if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
|
|
7303
|
+
const gitFields = git;
|
|
7304
|
+
if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
|
|
7305
|
+
if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
|
|
7306
|
+
if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
|
|
7307
|
+
const config = candidate.config;
|
|
7308
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
7309
|
+
return 'missing "config" object';
|
|
7310
|
+
}
|
|
7311
|
+
const budgets = candidate.budgets;
|
|
7312
|
+
if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
|
|
7313
|
+
return 'missing "budgets" object';
|
|
7314
|
+
}
|
|
7315
|
+
for (const key of ["maxPartBytes", "largeFileBytes"]) {
|
|
7316
|
+
const value2 = budgets[key];
|
|
7317
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7318
|
+
return `\`budgets.${key}\` must be a non-negative integer`;
|
|
7319
|
+
}
|
|
7320
|
+
}
|
|
7321
|
+
if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
|
|
7322
|
+
return 'missing "indexes" object';
|
|
7323
|
+
}
|
|
7324
|
+
if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
|
|
7325
|
+
return 'missing "kinds" object';
|
|
7326
|
+
}
|
|
7327
|
+
}
|
|
6552
7328
|
if (!Array.isArray(candidate.files)) return 'missing "files" array';
|
|
6553
7329
|
for (const entry of candidate.files) {
|
|
6554
7330
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6555
7331
|
return 'a "files" entry is not an object';
|
|
6556
7332
|
}
|
|
6557
|
-
|
|
7333
|
+
const fields = entry;
|
|
7334
|
+
if (typeof fields.relativePath !== "string") {
|
|
6558
7335
|
return 'a "files" entry has no "relativePath"';
|
|
6559
7336
|
}
|
|
7337
|
+
if (!currentSchema) continue;
|
|
7338
|
+
if (typeof fields.part !== "string" || fields.part.length === 0) {
|
|
7339
|
+
return 'a "files" entry records no "part"';
|
|
7340
|
+
}
|
|
7341
|
+
if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
|
|
7342
|
+
return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
|
|
7343
|
+
}
|
|
7344
|
+
for (const key of ["sizeBytes", "lines"]) {
|
|
7345
|
+
const value2 = fields[key];
|
|
7346
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7347
|
+
return `a "files" entry "${key}" must be a non-negative integer`;
|
|
7348
|
+
}
|
|
7349
|
+
}
|
|
7350
|
+
if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
|
|
7351
|
+
return 'a "files" entry has an unknown "inclusionMode"';
|
|
7352
|
+
}
|
|
6560
7353
|
}
|
|
6561
7354
|
if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
|
|
6562
7355
|
if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
|
|
@@ -6564,13 +7357,28 @@ function describeManifestShapeProblem(value) {
|
|
|
6564
7357
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6565
7358
|
return 'a "parts" entry is not an object';
|
|
6566
7359
|
}
|
|
6567
|
-
const
|
|
7360
|
+
const fields = entry;
|
|
7361
|
+
const filename = fields.filename;
|
|
6568
7362
|
if (typeof filename !== "string" || filename.trim() === "") {
|
|
6569
7363
|
return 'a "parts" entry has no "filename"';
|
|
6570
7364
|
}
|
|
6571
7365
|
if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16__namespace.isAbsolute(filename)) {
|
|
6572
7366
|
return 'a "parts" entry "filename" must be a bare filename inside parts/';
|
|
6573
7367
|
}
|
|
7368
|
+
if (currentSchema) {
|
|
7369
|
+
if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
|
|
7370
|
+
return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
|
|
7371
|
+
}
|
|
7372
|
+
if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
|
|
7373
|
+
return 'a "parts" entry "byteSize" must be a non-negative integer';
|
|
7374
|
+
}
|
|
7375
|
+
if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
|
|
7376
|
+
return 'a "parts" entry "index" must be a positive integer';
|
|
7377
|
+
}
|
|
7378
|
+
if (!Array.isArray(fields.includedFiles)) {
|
|
7379
|
+
return 'a "parts" entry has no "includedFiles" array';
|
|
7380
|
+
}
|
|
7381
|
+
}
|
|
6574
7382
|
}
|
|
6575
7383
|
if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
|
|
6576
7384
|
return 'missing "layers" object';
|
|
@@ -6581,7 +7389,7 @@ function validateSnapshot(configInput) {
|
|
|
6581
7389
|
assertUsableConfigInput(configInput);
|
|
6582
7390
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
|
|
6583
7391
|
const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
|
|
6584
|
-
if (!
|
|
7392
|
+
if (!fs15__namespace.existsSync(manifestPath)) {
|
|
6585
7393
|
return {
|
|
6586
7394
|
valid: false,
|
|
6587
7395
|
manifestPresent: false,
|
|
@@ -6592,7 +7400,7 @@ function validateSnapshot(configInput) {
|
|
|
6592
7400
|
}
|
|
6593
7401
|
let manifest;
|
|
6594
7402
|
try {
|
|
6595
|
-
manifest = JSON.parse(
|
|
7403
|
+
manifest = JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
|
|
6596
7404
|
} catch (err) {
|
|
6597
7405
|
return {
|
|
6598
7406
|
valid: false,
|
|
@@ -6615,6 +7423,19 @@ function validateSnapshot(configInput) {
|
|
|
6615
7423
|
const drift = emptyDrift();
|
|
6616
7424
|
const warnings = [];
|
|
6617
7425
|
const snapshotDir = path16__namespace.resolve(config.cwd, config.outDir);
|
|
7426
|
+
const unreadableSkips = manifest.skipped.filter(
|
|
7427
|
+
(entry) => entry.reason === "missing" || entry.reason === "read-error"
|
|
7428
|
+
);
|
|
7429
|
+
if (unreadableSkips.length > 0) {
|
|
7430
|
+
warnings.push(
|
|
7431
|
+
`${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.`
|
|
7432
|
+
);
|
|
7433
|
+
}
|
|
7434
|
+
if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
|
|
7435
|
+
warnings.push(
|
|
7436
|
+
"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."
|
|
7437
|
+
);
|
|
7438
|
+
}
|
|
6618
7439
|
const manifestFileMap = /* @__PURE__ */ new Map();
|
|
6619
7440
|
for (const file of manifest.files) {
|
|
6620
7441
|
if (file && typeof file.relativePath === "string") {
|
|
@@ -6677,7 +7498,7 @@ function validateSnapshot(configInput) {
|
|
|
6677
7498
|
// snapshot was reported as drifting.
|
|
6678
7499
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
6679
7500
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
6680
|
-
).filter((
|
|
7501
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
|
|
6681
7502
|
});
|
|
6682
7503
|
for (const diskFile of collection.files) {
|
|
6683
7504
|
const snapshotHash = manifestFileMap.get(diskFile);
|
|
@@ -6702,7 +7523,7 @@ function validateSnapshot(configInput) {
|
|
|
6702
7523
|
}
|
|
6703
7524
|
let diskHash;
|
|
6704
7525
|
try {
|
|
6705
|
-
diskHash = sha256Hex(
|
|
7526
|
+
diskHash = sha256Hex(fs15__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
|
|
6706
7527
|
} catch (err) {
|
|
6707
7528
|
if (err.code === "ENOENT") {
|
|
6708
7529
|
drift.missingOnDisk.push(diskFile);
|
|
@@ -6726,7 +7547,7 @@ function validateSnapshot(configInput) {
|
|
|
6726
7547
|
}
|
|
6727
7548
|
let statFailure = null;
|
|
6728
7549
|
try {
|
|
6729
|
-
|
|
7550
|
+
fs15__namespace.statSync(confined);
|
|
6730
7551
|
} catch (err) {
|
|
6731
7552
|
statFailure = err;
|
|
6732
7553
|
}
|
|
@@ -6761,7 +7582,7 @@ function validateSnapshot(configInput) {
|
|
|
6761
7582
|
}
|
|
6762
7583
|
let buffer;
|
|
6763
7584
|
try {
|
|
6764
|
-
buffer =
|
|
7585
|
+
buffer = fs15__namespace.readFileSync(partPath);
|
|
6765
7586
|
} catch {
|
|
6766
7587
|
drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
|
|
6767
7588
|
continue;
|
|
@@ -6783,24 +7604,85 @@ function validateSnapshot(configInput) {
|
|
|
6783
7604
|
});
|
|
6784
7605
|
}
|
|
6785
7606
|
}
|
|
6786
|
-
const
|
|
6787
|
-
|
|
6788
|
-
|
|
6789
|
-
)
|
|
6790
|
-
|
|
6791
|
-
|
|
6792
|
-
|
|
6793
|
-
|
|
6794
|
-
|
|
7607
|
+
const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7608
|
+
const includedByPart = /* @__PURE__ */ new Map();
|
|
7609
|
+
const partIndexes = /* @__PURE__ */ new Set();
|
|
7610
|
+
for (const part of manifest.parts) {
|
|
7611
|
+
if (includedByPart.has(part.filename)) {
|
|
7612
|
+
drift.partIssues.push({
|
|
7613
|
+
part: maskDriftPath(part.filename),
|
|
7614
|
+
issue: "appears more than once in parts[]"
|
|
7615
|
+
});
|
|
7616
|
+
}
|
|
7617
|
+
if (typeof part.index === "number") {
|
|
7618
|
+
if (partIndexes.has(part.index)) {
|
|
7619
|
+
drift.partIssues.push({
|
|
7620
|
+
part: maskDriftPath(part.filename),
|
|
7621
|
+
issue: `reuses part index ${part.index}`
|
|
7622
|
+
});
|
|
7623
|
+
}
|
|
7624
|
+
partIndexes.add(part.index);
|
|
7625
|
+
}
|
|
7626
|
+
const listed = /* @__PURE__ */ new Set();
|
|
7627
|
+
for (const included of part.includedFiles ?? []) {
|
|
7628
|
+
if (typeof included?.relativePath !== "string") continue;
|
|
7629
|
+
if (listed.has(included.relativePath)) {
|
|
7630
|
+
drift.partIssues.push({
|
|
7631
|
+
part: maskDriftPath(part.filename),
|
|
7632
|
+
issue: `lists ${maskDriftPath(included.relativePath)} twice`
|
|
7633
|
+
});
|
|
7634
|
+
}
|
|
7635
|
+
listed.add(included.relativePath);
|
|
7636
|
+
}
|
|
7637
|
+
includedByPart.set(part.filename, listed);
|
|
7638
|
+
if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
|
|
7639
|
+
drift.partIssues.push({
|
|
7640
|
+
part: maskDriftPath(part.filename),
|
|
7641
|
+
issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
|
|
7642
|
+
});
|
|
7643
|
+
}
|
|
6795
7644
|
}
|
|
7645
|
+
const filePaths = /* @__PURE__ */ new Set();
|
|
6796
7646
|
for (const file of manifest.files) {
|
|
6797
|
-
if (
|
|
7647
|
+
if (filePaths.has(file.relativePath)) {
|
|
7648
|
+
drift.partIssues.push({
|
|
7649
|
+
part: "(files)",
|
|
7650
|
+
issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
|
|
7651
|
+
});
|
|
7652
|
+
continue;
|
|
7653
|
+
}
|
|
7654
|
+
filePaths.add(file.relativePath);
|
|
7655
|
+
if (typeof file.part !== "string" || file.part.length === 0) {
|
|
7656
|
+
drift.partIssues.push({
|
|
7657
|
+
part: "(files)",
|
|
7658
|
+
issue: `${maskDriftPath(file.relativePath)} records no part`
|
|
7659
|
+
});
|
|
7660
|
+
continue;
|
|
7661
|
+
}
|
|
7662
|
+
if (!partNames.has(file.part)) {
|
|
7663
|
+
drift.partIssues.push({
|
|
7664
|
+
part: maskDriftPath(file.part),
|
|
7665
|
+
issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
|
|
7666
|
+
});
|
|
7667
|
+
continue;
|
|
7668
|
+
}
|
|
7669
|
+
if (!includedByPart.get(file.part)?.has(file.relativePath)) {
|
|
6798
7670
|
drift.partIssues.push({
|
|
6799
|
-
part: file.part,
|
|
6800
|
-
issue: `${file.relativePath}
|
|
7671
|
+
part: maskDriftPath(file.part),
|
|
7672
|
+
issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
|
|
6801
7673
|
});
|
|
6802
7674
|
}
|
|
6803
7675
|
}
|
|
7676
|
+
for (const [partName, listed] of includedByPart) {
|
|
7677
|
+
for (const relativePath of listed) {
|
|
7678
|
+
if (!filePaths.has(relativePath)) {
|
|
7679
|
+
drift.partIssues.push({
|
|
7680
|
+
part: maskDriftPath(partName),
|
|
7681
|
+
issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
|
|
7682
|
+
});
|
|
7683
|
+
}
|
|
7684
|
+
}
|
|
7685
|
+
}
|
|
6804
7686
|
const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
6805
7687
|
const currentExcludes = config.excludePatterns.map(maskValue);
|
|
6806
7688
|
const currentInclude = config.include.map(maskValue);
|
|
@@ -6956,6 +7838,13 @@ function validateSnapshot(configInput) {
|
|
|
6956
7838
|
0
|
|
6957
7839
|
);
|
|
6958
7840
|
expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
|
|
7841
|
+
if (manifest.files.every((file) => typeof file?.lines === "number")) {
|
|
7842
|
+
expectEqual(
|
|
7843
|
+
"counts.totalLines",
|
|
7844
|
+
counts.totalLines,
|
|
7845
|
+
manifest.files.reduce((total, file) => total + file.lines, 0)
|
|
7846
|
+
);
|
|
7847
|
+
}
|
|
6959
7848
|
expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
|
|
6960
7849
|
expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
|
|
6961
7850
|
expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
|
|
@@ -6979,6 +7868,37 @@ function validateSnapshot(configInput) {
|
|
|
6979
7868
|
`totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
|
|
6980
7869
|
);
|
|
6981
7870
|
}
|
|
7871
|
+
const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
|
|
7872
|
+
if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
|
|
7873
|
+
const settingsLine = `settings:${recordedSettingsDigest}`;
|
|
7874
|
+
const currentDefinition = sha256Hex(
|
|
7875
|
+
Buffer.from(
|
|
7876
|
+
[
|
|
7877
|
+
...manifest.files.map(
|
|
7878
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
7879
|
+
),
|
|
7880
|
+
settingsLine
|
|
7881
|
+
].join("\n"),
|
|
7882
|
+
"utf8"
|
|
7883
|
+
)
|
|
7884
|
+
);
|
|
7885
|
+
const legacyDefinition = sha256Hex(
|
|
7886
|
+
Buffer.from(
|
|
7887
|
+
[
|
|
7888
|
+
...manifest.files.map(
|
|
7889
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
|
|
7890
|
+
),
|
|
7891
|
+
settingsLine
|
|
7892
|
+
].join("\n"),
|
|
7893
|
+
"utf8"
|
|
7894
|
+
)
|
|
7895
|
+
);
|
|
7896
|
+
if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
|
|
7897
|
+
totalsMismatches.push(
|
|
7898
|
+
"fingerprint: does not match the files and settings recorded in this manifest"
|
|
7899
|
+
);
|
|
7900
|
+
}
|
|
7901
|
+
}
|
|
6982
7902
|
if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
|
|
6983
7903
|
totalsMismatches.push(
|
|
6984
7904
|
`budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
|
|
@@ -7006,26 +7926,49 @@ function validateSnapshot(configInput) {
|
|
|
7006
7926
|
drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
|
|
7007
7927
|
}
|
|
7008
7928
|
}
|
|
7009
|
-
|
|
7929
|
+
const declaredArtifacts = [
|
|
7930
|
+
["README.md", manifest.artifacts?.readme],
|
|
7931
|
+
["reports/navigation.md", manifest.artifacts?.navigation],
|
|
7932
|
+
["reports/project-tree.md", manifest.artifacts?.projectTree],
|
|
7933
|
+
["reports/audit.md", manifest.artifacts?.audit],
|
|
7010
7934
|
["full-codebase.json", manifest.artifacts?.fullJson],
|
|
7011
7935
|
["full-codebase.md", manifest.artifacts?.fullMarkdown]
|
|
7012
|
-
]
|
|
7936
|
+
];
|
|
7937
|
+
for (const [key, artifact] of declaredArtifacts) {
|
|
7013
7938
|
if (!artifact) continue;
|
|
7014
|
-
const artifactPath = path16__namespace.join(snapshotDir, key);
|
|
7939
|
+
const artifactPath = path16__namespace.join(snapshotDir, ...key.split("/"));
|
|
7940
|
+
let buffer;
|
|
7015
7941
|
try {
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7019
|
-
}
|
|
7942
|
+
if (!fs15__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
|
|
7943
|
+
buffer = fs15__namespace.readFileSync(artifactPath);
|
|
7020
7944
|
} catch {
|
|
7021
7945
|
drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
|
|
7946
|
+
continue;
|
|
7947
|
+
}
|
|
7948
|
+
if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
|
|
7949
|
+
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7950
|
+
continue;
|
|
7951
|
+
}
|
|
7952
|
+
if (key === "reports/navigation.md") {
|
|
7953
|
+
for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
|
|
7954
|
+
const target = match[1].split("#")[0];
|
|
7955
|
+
if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
|
|
7956
|
+
const resolved = path16__namespace.resolve(snapshotDir, "reports", target);
|
|
7957
|
+
const relative10 = path16__namespace.relative(snapshotDir, resolved);
|
|
7958
|
+
if (relative10.startsWith("..") || path16__namespace.isAbsolute(relative10) || !fs15__namespace.existsSync(resolved)) {
|
|
7959
|
+
drift.partIssues.push({
|
|
7960
|
+
part: key,
|
|
7961
|
+
issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
|
|
7962
|
+
});
|
|
7963
|
+
}
|
|
7964
|
+
}
|
|
7022
7965
|
}
|
|
7023
7966
|
}
|
|
7024
7967
|
const sarifArtifact = manifest.artifacts?.sarif;
|
|
7025
7968
|
if (sarifArtifact) {
|
|
7026
7969
|
const sarifKey = "reports/audit.sarif";
|
|
7027
7970
|
try {
|
|
7028
|
-
const buffer =
|
|
7971
|
+
const buffer = fs15__namespace.readFileSync(path16__namespace.join(snapshotDir, "reports", "audit.sarif"));
|
|
7029
7972
|
if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
|
|
7030
7973
|
drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
|
|
7031
7974
|
}
|
|
@@ -7034,8 +7977,11 @@ function validateSnapshot(configInput) {
|
|
|
7034
7977
|
}
|
|
7035
7978
|
}
|
|
7036
7979
|
if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
|
|
7980
|
+
const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7981
|
+
const generatedOn = maskBranch(manifest.git.branch);
|
|
7982
|
+
const configuredAs = maskBranch(config.branch);
|
|
7037
7983
|
warnings.push(
|
|
7038
|
-
`Snapshot was generated on branch "${
|
|
7984
|
+
`Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
|
|
7039
7985
|
);
|
|
7040
7986
|
}
|
|
7041
7987
|
const errors = [];
|
|
@@ -7092,15 +8038,6 @@ function validateSnapshot(configInput) {
|
|
|
7092
8038
|
warnings
|
|
7093
8039
|
};
|
|
7094
8040
|
}
|
|
7095
|
-
|
|
7096
|
-
// src/version.ts
|
|
7097
|
-
var GENERATOR_NAME = "codebase-snapshot";
|
|
7098
|
-
var GENERATOR_VERSION = "0.9.16";
|
|
7099
|
-
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
7100
|
-
function isOurGeneratorName(name) {
|
|
7101
|
-
if (typeof name !== "string") return false;
|
|
7102
|
-
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
7103
|
-
}
|
|
7104
8041
|
var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
|
|
7105
8042
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
7106
8043
|
var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
@@ -7171,23 +8108,24 @@ function shouldCheck(argv, env) {
|
|
|
7171
8108
|
for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
|
|
7172
8109
|
if (args.includes(skip)) return false;
|
|
7173
8110
|
}
|
|
8111
|
+
let format = null;
|
|
7174
8112
|
for (let index = 0; index < args.length; index += 1) {
|
|
7175
8113
|
const argument = args[index];
|
|
8114
|
+
if (argument === "--") break;
|
|
7176
8115
|
if (argument === "--format") {
|
|
7177
|
-
|
|
7178
|
-
|
|
7179
|
-
|
|
7180
|
-
if (argument.startsWith("--format=")) {
|
|
7181
|
-
if (argument.slice("--format=".length) === "json") return false;
|
|
7182
|
-
break;
|
|
8116
|
+
format = args[index + 1] ?? null;
|
|
8117
|
+
index += 1;
|
|
8118
|
+
continue;
|
|
7183
8119
|
}
|
|
8120
|
+
if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
|
|
7184
8121
|
}
|
|
8122
|
+
if (format === "json") return false;
|
|
7185
8123
|
return true;
|
|
7186
8124
|
}
|
|
7187
8125
|
function readCache(file) {
|
|
7188
8126
|
let raw;
|
|
7189
8127
|
try {
|
|
7190
|
-
raw =
|
|
8128
|
+
raw = fs15__namespace.readFileSync(file, "utf8");
|
|
7191
8129
|
} catch {
|
|
7192
8130
|
return null;
|
|
7193
8131
|
}
|
|
@@ -7204,21 +8142,21 @@ function readCache(file) {
|
|
|
7204
8142
|
}
|
|
7205
8143
|
function writeCache(file, entry) {
|
|
7206
8144
|
try {
|
|
7207
|
-
|
|
7208
|
-
|
|
8145
|
+
fs15__namespace.mkdirSync(path16__namespace.dirname(file), { recursive: true });
|
|
8146
|
+
fs15__namespace.writeFileSync(file, `${JSON.stringify(entry)}
|
|
7209
8147
|
`, "utf8");
|
|
7210
8148
|
} catch {
|
|
7211
8149
|
}
|
|
7212
8150
|
}
|
|
7213
8151
|
function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
7214
|
-
return new Promise((
|
|
8152
|
+
return new Promise((resolve7) => {
|
|
7215
8153
|
let settled = false;
|
|
7216
8154
|
let request = null;
|
|
7217
8155
|
const finish = (value) => {
|
|
7218
8156
|
if (settled) return;
|
|
7219
8157
|
settled = true;
|
|
7220
8158
|
clearTimeout(deadline);
|
|
7221
|
-
|
|
8159
|
+
resolve7(value);
|
|
7222
8160
|
};
|
|
7223
8161
|
const deadline = setTimeout(() => {
|
|
7224
8162
|
request?.destroy();
|
|
@@ -7305,23 +8243,23 @@ function describeMatcher(matcher) {
|
|
|
7305
8243
|
function normalizeTarget(cwd, target) {
|
|
7306
8244
|
const resolvedCwd = path16__namespace.resolve(cwd);
|
|
7307
8245
|
const absolute = path16__namespace.resolve(resolvedCwd, target);
|
|
7308
|
-
const
|
|
7309
|
-
if (
|
|
8246
|
+
const relative10 = path16__namespace.relative(resolvedCwd, absolute);
|
|
8247
|
+
if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative10)) {
|
|
7310
8248
|
return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
|
|
7311
8249
|
}
|
|
7312
|
-
return { relative:
|
|
8250
|
+
return { relative: relative10.split(path16__namespace.sep).join("/"), outsideRoot: false };
|
|
7313
8251
|
}
|
|
7314
8252
|
function findRuleMatch(rules, relativePath) {
|
|
7315
8253
|
return rules.find(
|
|
7316
8254
|
(rule) => matchRule(relativePath, rule.match)
|
|
7317
8255
|
);
|
|
7318
8256
|
}
|
|
7319
|
-
function findRecordedAncestor(skipped,
|
|
8257
|
+
function findRecordedAncestor(skipped, relative10, maskedPath2) {
|
|
7320
8258
|
let nearest;
|
|
7321
8259
|
for (const record of skipped) {
|
|
7322
8260
|
const ancestorPath = record.path;
|
|
7323
8261
|
if (ancestorPath.length === 0) continue;
|
|
7324
|
-
const isAncestor =
|
|
8262
|
+
const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
|
|
7325
8263
|
if (!isAncestor) continue;
|
|
7326
8264
|
if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
|
|
7327
8265
|
}
|
|
@@ -7330,15 +8268,15 @@ function findRecordedAncestor(skipped, relative8, maskedPath2) {
|
|
|
7330
8268
|
function readManifest2(config) {
|
|
7331
8269
|
const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
|
|
7332
8270
|
try {
|
|
7333
|
-
return JSON.parse(
|
|
8271
|
+
return JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
|
|
7334
8272
|
} catch {
|
|
7335
8273
|
return null;
|
|
7336
8274
|
}
|
|
7337
8275
|
}
|
|
7338
8276
|
function explainPath(config, target) {
|
|
7339
8277
|
const normalized = normalizeTarget(config.cwd, target);
|
|
7340
|
-
const
|
|
7341
|
-
const maskedPath2 = findSecretInPath(
|
|
8278
|
+
const relative10 = normalized.relative;
|
|
8279
|
+
const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
|
|
7342
8280
|
if (normalized.outsideRoot) {
|
|
7343
8281
|
return {
|
|
7344
8282
|
path: maskedPath2,
|
|
@@ -7348,10 +8286,10 @@ function explainPath(config, target) {
|
|
|
7348
8286
|
detail: "path resolves outside the configured repository root and was not inspected"
|
|
7349
8287
|
};
|
|
7350
8288
|
}
|
|
7351
|
-
const absolute = path16__namespace.join(config.cwd,
|
|
8289
|
+
const absolute = path16__namespace.join(config.cwd, relative10);
|
|
7352
8290
|
const result = {
|
|
7353
8291
|
path: maskedPath2,
|
|
7354
|
-
exists:
|
|
8292
|
+
exists: fs15__namespace.existsSync(absolute),
|
|
7355
8293
|
included: false
|
|
7356
8294
|
};
|
|
7357
8295
|
const collection = collectFiles(config.cwd, {
|
|
@@ -7366,11 +8304,11 @@ function explainPath(config, target) {
|
|
|
7366
8304
|
// that is only missing because the walker dropped the tool's own output directory.
|
|
7367
8305
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
7368
8306
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
7369
|
-
).filter((
|
|
8307
|
+
).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
|
|
7370
8308
|
});
|
|
7371
|
-
if (!collection.files.includes(
|
|
8309
|
+
if (!collection.files.includes(relative10)) {
|
|
7372
8310
|
const record = collection.skipped.find(
|
|
7373
|
-
(entry2) => entry2.path ===
|
|
8311
|
+
(entry2) => entry2.path === relative10 || entry2.path === maskedPath2
|
|
7374
8312
|
);
|
|
7375
8313
|
if (record) {
|
|
7376
8314
|
result.reason = record.reason;
|
|
@@ -7379,7 +8317,7 @@ function explainPath(config, target) {
|
|
|
7379
8317
|
result.reason = "missing";
|
|
7380
8318
|
result.detail = "no such file or directory, relative to the configured cwd";
|
|
7381
8319
|
} else {
|
|
7382
|
-
const ancestor = findRecordedAncestor(collection.skipped,
|
|
8320
|
+
const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
|
|
7383
8321
|
if (ancestor) {
|
|
7384
8322
|
result.reason = ancestor.reason;
|
|
7385
8323
|
result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
|
|
@@ -7399,11 +8337,11 @@ function explainPath(config, target) {
|
|
|
7399
8337
|
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
7400
8338
|
...config.staged === true ? { staged: true } : {}
|
|
7401
8339
|
});
|
|
7402
|
-
inScope = scope.paths.has(
|
|
8340
|
+
inScope = scope.paths.has(relative10);
|
|
7403
8341
|
if (!inScope && config.withDependents === true) {
|
|
7404
8342
|
inScope = importsChangedFile(
|
|
7405
|
-
|
|
7406
|
-
importsOfFile(
|
|
8343
|
+
relative10,
|
|
8344
|
+
importsOfFile(relative10, absolute),
|
|
7407
8345
|
scope.paths,
|
|
7408
8346
|
buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
|
|
7409
8347
|
);
|
|
@@ -7430,7 +8368,7 @@ function explainPath(config, target) {
|
|
|
7430
8368
|
}
|
|
7431
8369
|
let sizeOnDisk = null;
|
|
7432
8370
|
try {
|
|
7433
|
-
sizeOnDisk =
|
|
8371
|
+
sizeOnDisk = fs15__namespace.statSync(absolute).size;
|
|
7434
8372
|
} catch {
|
|
7435
8373
|
sizeOnDisk = null;
|
|
7436
8374
|
}
|
|
@@ -7440,8 +8378,16 @@ function explainPath(config, target) {
|
|
|
7440
8378
|
result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
|
|
7441
8379
|
return result;
|
|
7442
8380
|
}
|
|
7443
|
-
if (
|
|
7444
|
-
|
|
8381
|
+
if (fs15__namespace.existsSync(absolute) && fs15__namespace.statSync(absolute).isFile()) {
|
|
8382
|
+
let buffer;
|
|
8383
|
+
try {
|
|
8384
|
+
buffer = fs15__namespace.readFileSync(absolute);
|
|
8385
|
+
} catch (err) {
|
|
8386
|
+
result.included = false;
|
|
8387
|
+
result.reason = "read-error";
|
|
8388
|
+
result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
|
|
8389
|
+
return result;
|
|
8390
|
+
}
|
|
7445
8391
|
const decoded = decodeText(buffer);
|
|
7446
8392
|
if (decoded.binary) {
|
|
7447
8393
|
result.included = false;
|
|
@@ -7453,21 +8399,30 @@ function explainPath(config, target) {
|
|
|
7453
8399
|
result.bytes = buffer.length;
|
|
7454
8400
|
result.lines = countLines(text2);
|
|
7455
8401
|
if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
|
|
7456
|
-
const { findings } = scanAndRedactSecrets(text2, config.secretRules,
|
|
8402
|
+
const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative10);
|
|
7457
8403
|
result.secretCount = findings.length;
|
|
7458
8404
|
result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
|
|
8405
|
+
let inclusionMode = "full";
|
|
8406
|
+
if (config.skeleton === true && isSkeletonizable(relative10)) {
|
|
8407
|
+
const skeleton = skeletonizeTypeScript(text2, relative10);
|
|
8408
|
+
if (skeleton.collapsed > 0) inclusionMode = "signatures";
|
|
8409
|
+
}
|
|
8410
|
+
if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
|
|
8411
|
+
const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
|
|
8412
|
+
inclusionMode = preview.isTruncated ? "preview" : "full";
|
|
8413
|
+
}
|
|
8414
|
+
result.inclusionMode = inclusionMode;
|
|
7459
8415
|
}
|
|
7460
|
-
result.layer = classifyLayer(
|
|
7461
|
-
result.kind = classifyKind(
|
|
7462
|
-
result.language = detectLanguage(
|
|
7463
|
-
const layerRule = findRuleMatch(config.layers,
|
|
8416
|
+
result.layer = classifyLayer(relative10, config.layers);
|
|
8417
|
+
result.kind = classifyKind(relative10, config.kinds);
|
|
8418
|
+
result.language = detectLanguage(relative10);
|
|
8419
|
+
const layerRule = findRuleMatch(config.layers, relative10);
|
|
7464
8420
|
if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
|
|
7465
|
-
const kindRule = findRuleMatch(config.kinds,
|
|
8421
|
+
const kindRule = findRuleMatch(config.kinds, relative10);
|
|
7466
8422
|
if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
|
|
7467
8423
|
const manifest = readManifest2(config);
|
|
7468
|
-
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath ===
|
|
8424
|
+
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
|
|
7469
8425
|
result.part = entry?.part ?? null;
|
|
7470
|
-
result.inclusionMode = entry?.inclusionMode;
|
|
7471
8426
|
return result;
|
|
7472
8427
|
}
|
|
7473
8428
|
function renderExplainText(result) {
|
|
@@ -7696,14 +8651,14 @@ function compareManifests(before, after) {
|
|
|
7696
8651
|
function loadManifest(target) {
|
|
7697
8652
|
let isDirectory;
|
|
7698
8653
|
try {
|
|
7699
|
-
isDirectory =
|
|
8654
|
+
isDirectory = fs15__namespace.statSync(target).isDirectory();
|
|
7700
8655
|
} catch {
|
|
7701
8656
|
throw new Error(`No snapshot found at ${target}: the path does not exist.`);
|
|
7702
8657
|
}
|
|
7703
8658
|
const manifestPath = isDirectory ? path16__namespace.join(target, "manifest.json") : target;
|
|
7704
8659
|
let raw;
|
|
7705
8660
|
try {
|
|
7706
|
-
raw =
|
|
8661
|
+
raw = fs15__namespace.readFileSync(manifestPath, "utf8");
|
|
7707
8662
|
} catch {
|
|
7708
8663
|
throw new Error(`Could not read a manifest at ${manifestPath}.`);
|
|
7709
8664
|
}
|
|
@@ -7757,18 +8712,70 @@ function renderDiffText(diff) {
|
|
|
7757
8712
|
}
|
|
7758
8713
|
return lines.join("\n");
|
|
7759
8714
|
}
|
|
8715
|
+
function decodeGitignore(buffer) {
|
|
8716
|
+
const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
|
|
8717
|
+
if (startsWith(239, 187, 191)) {
|
|
8718
|
+
const body = buffer.subarray(3);
|
|
8719
|
+
const text3 = body.toString("utf8");
|
|
8720
|
+
if (!Buffer.from(text3, "utf8").equals(body)) return null;
|
|
8721
|
+
return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
|
|
8722
|
+
}
|
|
8723
|
+
if (startsWith(255, 254)) {
|
|
8724
|
+
const body = buffer.subarray(2);
|
|
8725
|
+
if (body.length % 2 !== 0) return null;
|
|
8726
|
+
const text3 = body.toString("utf16le");
|
|
8727
|
+
if (!Buffer.from(text3, "utf16le").equals(body)) return null;
|
|
8728
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
|
|
8729
|
+
}
|
|
8730
|
+
if (startsWith(254, 255)) {
|
|
8731
|
+
const body = buffer.subarray(2);
|
|
8732
|
+
if (body.length % 2 !== 0) return null;
|
|
8733
|
+
const swapped = Buffer.from(body);
|
|
8734
|
+
swapped.swap16();
|
|
8735
|
+
const text3 = swapped.toString("utf16le");
|
|
8736
|
+
if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
|
|
8737
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
|
|
8738
|
+
}
|
|
8739
|
+
const text2 = buffer.toString("utf8");
|
|
8740
|
+
if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
|
|
8741
|
+
return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
|
|
8742
|
+
}
|
|
8743
|
+
function encodeGitignore(decoded, text2) {
|
|
8744
|
+
if (decoded.encoding === "utf8") {
|
|
8745
|
+
return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
|
|
8746
|
+
}
|
|
8747
|
+
const littleEndian = Buffer.from(text2, "utf16le");
|
|
8748
|
+
if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
|
|
8749
|
+
const bigEndian = Buffer.from(littleEndian);
|
|
8750
|
+
bigEndian.swap16();
|
|
8751
|
+
return Buffer.concat([decoded.bom, bigEndian]);
|
|
8752
|
+
}
|
|
8753
|
+
function canonicalIgnorePattern(line) {
|
|
8754
|
+
const trimmed = line.trim();
|
|
8755
|
+
if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
|
|
8756
|
+
const negated = trimmed.startsWith("!");
|
|
8757
|
+
const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
|
|
8758
|
+
return `${negated ? "!" : ""}${body}`;
|
|
8759
|
+
}
|
|
7760
8760
|
function appendGitignoreEntries(cwd, entries) {
|
|
7761
8761
|
const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
|
|
7762
8762
|
if (wanted.length === 0) return { added: [], note: null };
|
|
7763
8763
|
const ignorePath = path16__namespace.join(cwd, ".gitignore");
|
|
7764
8764
|
const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
|
|
7765
|
-
let
|
|
8765
|
+
let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
|
|
7766
8766
|
try {
|
|
7767
|
-
if (
|
|
7768
|
-
if (
|
|
8767
|
+
if (fs15__namespace.existsSync(ignorePath)) {
|
|
8768
|
+
if (fs15__namespace.statSync(ignorePath).isDirectory()) {
|
|
7769
8769
|
return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
|
|
7770
8770
|
}
|
|
7771
|
-
|
|
8771
|
+
const read = decodeGitignore(fs15__namespace.readFileSync(ignorePath));
|
|
8772
|
+
if (read === null) {
|
|
8773
|
+
return {
|
|
8774
|
+
added: [],
|
|
8775
|
+
note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
|
|
8776
|
+
};
|
|
8777
|
+
}
|
|
8778
|
+
decoded = read;
|
|
7772
8779
|
}
|
|
7773
8780
|
} catch (err) {
|
|
7774
8781
|
return {
|
|
@@ -7776,18 +8783,25 @@ function appendGitignoreEntries(cwd, entries) {
|
|
|
7776
8783
|
note: `${ignorePath} could not be read (${err.message}). ${manual}`
|
|
7777
8784
|
};
|
|
7778
8785
|
}
|
|
7779
|
-
const
|
|
7780
|
-
const
|
|
8786
|
+
const existing = decoded.text;
|
|
8787
|
+
const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
|
|
8788
|
+
const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
|
|
7781
8789
|
if (added.length === 0) return { added: [], note: null };
|
|
7782
|
-
const
|
|
8790
|
+
const newline = existing.includes("\r\n") ? "\r\n" : "\n";
|
|
8791
|
+
const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
|
|
7783
8792
|
try {
|
|
7784
|
-
|
|
7785
|
-
|
|
8793
|
+
fs15__namespace.writeFileSync(
|
|
8794
|
+
ignorePath,
|
|
8795
|
+
encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
|
|
8796
|
+
);
|
|
7786
8797
|
} catch (err) {
|
|
7787
8798
|
return { added: [], note: `${err.message}. ${manual}` };
|
|
7788
8799
|
}
|
|
7789
8800
|
return { added, note: null };
|
|
7790
8801
|
}
|
|
8802
|
+
function gitignorePath(cwd, filePath) {
|
|
8803
|
+
return path16__namespace.relative(cwd, filePath).split(path16__namespace.sep).join("/");
|
|
8804
|
+
}
|
|
7791
8805
|
|
|
7792
8806
|
// src/wizard/config-template.ts
|
|
7793
8807
|
var DEFAULT_ANSWERS = {
|
|
@@ -8097,7 +9111,7 @@ function keyReader(input) {
|
|
|
8097
9111
|
next() {
|
|
8098
9112
|
const queued = queue.shift();
|
|
8099
9113
|
if (queued) return Promise.resolve(queued);
|
|
8100
|
-
return new Promise((
|
|
9114
|
+
return new Promise((resolve7) => waiters.push(resolve7));
|
|
8101
9115
|
},
|
|
8102
9116
|
close() {
|
|
8103
9117
|
input.off("keypress", onKey);
|
|
@@ -8323,7 +9337,7 @@ function parsePackageJson(raw) {
|
|
|
8323
9337
|
}
|
|
8324
9338
|
function readPackageJson(cwd) {
|
|
8325
9339
|
try {
|
|
8326
|
-
return parsePackageJson(
|
|
9340
|
+
return parsePackageJson(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
|
|
8327
9341
|
} catch {
|
|
8328
9342
|
return null;
|
|
8329
9343
|
}
|
|
@@ -8360,7 +9374,7 @@ function artifactAnswers(options) {
|
|
|
8360
9374
|
}
|
|
8361
9375
|
function topLevelDirs(cwd) {
|
|
8362
9376
|
try {
|
|
8363
|
-
return
|
|
9377
|
+
return fs15__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
|
|
8364
9378
|
} catch {
|
|
8365
9379
|
return [];
|
|
8366
9380
|
}
|
|
@@ -8373,10 +9387,38 @@ function describeJsonValue(value) {
|
|
|
8373
9387
|
}
|
|
8374
9388
|
function writeFileOrExplain(target, content) {
|
|
8375
9389
|
try {
|
|
8376
|
-
|
|
9390
|
+
let stats = null;
|
|
9391
|
+
try {
|
|
9392
|
+
stats = fs15__namespace.lstatSync(target);
|
|
9393
|
+
} catch {
|
|
9394
|
+
stats = null;
|
|
9395
|
+
}
|
|
9396
|
+
if (stats !== null && stats.isSymbolicLink()) {
|
|
9397
|
+
throw new Error(
|
|
9398
|
+
`Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
|
|
9399
|
+
);
|
|
9400
|
+
}
|
|
9401
|
+
if (stats !== null && !stats.isFile()) {
|
|
9402
|
+
throw new Error(
|
|
9403
|
+
`Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
|
|
9404
|
+
);
|
|
9405
|
+
}
|
|
9406
|
+
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
9407
|
+
fs15__namespace.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
|
|
9408
|
+
try {
|
|
9409
|
+
fs15__namespace.renameSync(temporary, target);
|
|
9410
|
+
} catch (err) {
|
|
9411
|
+
try {
|
|
9412
|
+
fs15__namespace.unlinkSync(temporary);
|
|
9413
|
+
} catch {
|
|
9414
|
+
}
|
|
9415
|
+
throw err;
|
|
9416
|
+
}
|
|
8377
9417
|
} catch (err) {
|
|
9418
|
+
const message = err.message;
|
|
9419
|
+
if (message.startsWith(`Cannot write ${target}:`)) throw err;
|
|
8378
9420
|
const code = err.code;
|
|
8379
|
-
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" :
|
|
9421
|
+
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
|
|
8380
9422
|
throw new Error(`Cannot write ${target}: ${reason}`);
|
|
8381
9423
|
}
|
|
8382
9424
|
}
|
|
@@ -8420,14 +9462,14 @@ function updatePackageJson(cwd, notes) {
|
|
|
8420
9462
|
scripts: [],
|
|
8421
9463
|
dependency: { name: GENERATOR_NAME, range: null, added: false }
|
|
8422
9464
|
};
|
|
8423
|
-
if (!
|
|
9465
|
+
if (!fs15__namespace.existsSync(packagePath)) {
|
|
8424
9466
|
notes.push("No package.json found, so npm scripts and the devDependency were not added.");
|
|
8425
9467
|
return unchanged;
|
|
8426
9468
|
}
|
|
8427
9469
|
let raw;
|
|
8428
9470
|
let parsed;
|
|
8429
9471
|
try {
|
|
8430
|
-
raw =
|
|
9472
|
+
raw = fs15__namespace.readFileSync(packagePath, "utf8");
|
|
8431
9473
|
parsed = parsePackageJson(raw);
|
|
8432
9474
|
} catch {
|
|
8433
9475
|
notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
|
|
@@ -8498,7 +9540,7 @@ function updatePackageJson(cwd, notes) {
|
|
|
8498
9540
|
writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
|
|
8499
9541
|
return { scripts: added, dependency };
|
|
8500
9542
|
}
|
|
8501
|
-
var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
|
|
9543
|
+
var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
|
|
8502
9544
|
function resolvePresetChoice(detectedName, presetName) {
|
|
8503
9545
|
return {
|
|
8504
9546
|
value: presetName,
|
|
@@ -8736,7 +9778,7 @@ async function runInit(options) {
|
|
|
8736
9778
|
const configText = renderConfig(answers);
|
|
8737
9779
|
const preferredName = chooseConfigFileName(options.cwd);
|
|
8738
9780
|
const presentConfigs = CONFIG_CANDIDATES.filter(
|
|
8739
|
-
(name) =>
|
|
9781
|
+
(name) => fs15__namespace.existsSync(path16__namespace.join(options.cwd, name))
|
|
8740
9782
|
);
|
|
8741
9783
|
const present = presentConfigs[0] ?? null;
|
|
8742
9784
|
if (presentConfigs.length > 1) {
|
|
@@ -8779,7 +9821,7 @@ async function runInit(options) {
|
|
|
8779
9821
|
'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.'
|
|
8780
9822
|
);
|
|
8781
9823
|
}
|
|
8782
|
-
if (
|
|
9824
|
+
if (fs15__namespace.existsSync(configPath) && !options.force && !reused) {
|
|
8783
9825
|
throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
|
|
8784
9826
|
}
|
|
8785
9827
|
if (!reused) writeFileOrExplain(configPath, configText);
|
|
@@ -8802,10 +9844,10 @@ async function runInit(options) {
|
|
|
8802
9844
|
};
|
|
8803
9845
|
}
|
|
8804
9846
|
function describeTarget(cwd) {
|
|
8805
|
-
const
|
|
8806
|
-
if (
|
|
8807
|
-
if (
|
|
8808
|
-
return
|
|
9847
|
+
const relative10 = path16__namespace.relative(process.cwd(), cwd);
|
|
9848
|
+
if (relative10 === "") return "this directory";
|
|
9849
|
+
if (relative10.startsWith("..") || path16__namespace.isAbsolute(relative10)) return cwd;
|
|
9850
|
+
return relative10;
|
|
8809
9851
|
}
|
|
8810
9852
|
function firstRunMessage(reason, cwd) {
|
|
8811
9853
|
const where = describeTarget(cwd);
|
|
@@ -8828,7 +9870,7 @@ function planFirstRun(facts) {
|
|
|
8828
9870
|
var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
|
|
8829
9871
|
function isEffectivelyEmpty(cwd) {
|
|
8830
9872
|
try {
|
|
8831
|
-
return
|
|
9873
|
+
return fs15__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
|
|
8832
9874
|
} catch {
|
|
8833
9875
|
return false;
|
|
8834
9876
|
}
|
|
@@ -8836,7 +9878,7 @@ function isEffectivelyEmpty(cwd) {
|
|
|
8836
9878
|
function hasPriorSnapshot(cwd, outDir) {
|
|
8837
9879
|
let parsed;
|
|
8838
9880
|
try {
|
|
8839
|
-
parsed = JSON.parse(
|
|
9881
|
+
parsed = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
|
|
8840
9882
|
} catch {
|
|
8841
9883
|
return false;
|
|
8842
9884
|
}
|
|
@@ -8862,9 +9904,17 @@ set -e
|
|
|
8862
9904
|
SNAPSHOT_DIR="${dir}"
|
|
8863
9905
|
|
|
8864
9906
|
if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
|
|
8865
|
-
|
|
8866
|
-
|
|
8867
|
-
|
|
9907
|
+
# Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
|
|
9908
|
+
# renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
|
|
9909
|
+
# failure mode a commit gate must not have. The opt-out is explicit and documented.
|
|
9910
|
+
if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
|
|
9911
|
+
echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
|
|
9912
|
+
exit 0
|
|
9913
|
+
fi
|
|
9914
|
+
echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
|
|
9915
|
+
echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
|
|
9916
|
+
echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
|
|
9917
|
+
exit 1
|
|
8868
9918
|
fi
|
|
8869
9919
|
|
|
8870
9920
|
if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
|
|
@@ -8879,26 +9929,69 @@ function gitDirectory(cwd) {
|
|
|
8879
9929
|
const dotGit = path16__namespace.join(cwd, ".git");
|
|
8880
9930
|
let stats;
|
|
8881
9931
|
try {
|
|
8882
|
-
stats =
|
|
9932
|
+
stats = fs15__namespace.statSync(dotGit);
|
|
8883
9933
|
} catch {
|
|
8884
9934
|
return null;
|
|
8885
9935
|
}
|
|
8886
9936
|
if (stats.isDirectory()) return dotGit;
|
|
8887
9937
|
if (!stats.isFile()) return null;
|
|
8888
9938
|
try {
|
|
8889
|
-
const contents =
|
|
9939
|
+
const contents = fs15__namespace.readFileSync(dotGit, "utf8");
|
|
8890
9940
|
const match = /^gitdir:\s*(.+)$/m.exec(contents);
|
|
8891
9941
|
if (!match) return null;
|
|
8892
9942
|
const target = match[1];
|
|
8893
9943
|
const resolved = path16__namespace.isAbsolute(target.trim()) ? target.trim() : path16__namespace.join(cwd, target.trim());
|
|
8894
|
-
|
|
9944
|
+
if (!fs15__namespace.statSync(resolved).isDirectory()) return null;
|
|
9945
|
+
if (isInside2(path16__namespace.resolve(cwd), path16__namespace.resolve(resolved))) return resolved;
|
|
9946
|
+
return isRegisteredWorktree(path16__namespace.resolve(resolved), cwd) ? resolved : null;
|
|
8895
9947
|
} catch {
|
|
8896
9948
|
return null;
|
|
8897
9949
|
}
|
|
8898
9950
|
}
|
|
9951
|
+
function isInside2(parent, child) {
|
|
9952
|
+
const relative10 = path16__namespace.relative(parent, child);
|
|
9953
|
+
return relative10 === "" || !relative10.startsWith("..") && !path16__namespace.isAbsolute(relative10);
|
|
9954
|
+
}
|
|
9955
|
+
function isRegisteredWorktree(gitDir, cwd) {
|
|
9956
|
+
try {
|
|
9957
|
+
const back = fs15__namespace.readFileSync(path16__namespace.join(gitDir, "gitdir"), "utf8").trim();
|
|
9958
|
+
return path16__namespace.resolve(gitDir, back) === path16__namespace.join(path16__namespace.resolve(cwd), ".git");
|
|
9959
|
+
} catch {
|
|
9960
|
+
return false;
|
|
9961
|
+
}
|
|
9962
|
+
}
|
|
9963
|
+
function gitOutput(cwd, args) {
|
|
9964
|
+
try {
|
|
9965
|
+
const output = childProcess__namespace.execFileSync("git", args, {
|
|
9966
|
+
cwd,
|
|
9967
|
+
encoding: "utf8",
|
|
9968
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
9969
|
+
});
|
|
9970
|
+
const trimmed = output.trim();
|
|
9971
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
9972
|
+
} catch {
|
|
9973
|
+
return null;
|
|
9974
|
+
}
|
|
9975
|
+
}
|
|
9976
|
+
function configuredHooksDirectory(cwd) {
|
|
9977
|
+
const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
|
|
9978
|
+
if (hooks === null) return null;
|
|
9979
|
+
const resolved = path16__namespace.resolve(cwd, hooks);
|
|
9980
|
+
const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
|
|
9981
|
+
const commonDir = common === null ? null : path16__namespace.resolve(cwd, common);
|
|
9982
|
+
if (isInside2(path16__namespace.resolve(cwd), resolved)) return { dir: resolved };
|
|
9983
|
+
if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
|
|
9984
|
+
return {
|
|
9985
|
+
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.`
|
|
9986
|
+
};
|
|
9987
|
+
}
|
|
8899
9988
|
function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
8900
|
-
const
|
|
8901
|
-
if (
|
|
9989
|
+
const configured = configuredHooksDirectory(cwd);
|
|
9990
|
+
if (configured !== null && "refusal" in configured) {
|
|
9991
|
+
return { path: null, written: false, notes: [configured.refusal] };
|
|
9992
|
+
}
|
|
9993
|
+
const gitDir = configured === null ? gitDirectory(cwd) : null;
|
|
9994
|
+
if (configured === null && gitDir === null) {
|
|
8902
9995
|
return {
|
|
8903
9996
|
path: null,
|
|
8904
9997
|
written: false,
|
|
@@ -8907,10 +10000,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8907
10000
|
]
|
|
8908
10001
|
};
|
|
8909
10002
|
}
|
|
8910
|
-
const hooksDir = path16__namespace.join(gitDir, "hooks");
|
|
10003
|
+
const hooksDir = configured === null ? path16__namespace.join(gitDir, "hooks") : configured.dir;
|
|
8911
10004
|
const hookPath = path16__namespace.join(hooksDir, "pre-commit");
|
|
8912
10005
|
try {
|
|
8913
|
-
|
|
10006
|
+
fs15__namespace.mkdirSync(hooksDir, { recursive: true });
|
|
8914
10007
|
} catch (err) {
|
|
8915
10008
|
return {
|
|
8916
10009
|
path: hookPath,
|
|
@@ -8920,7 +10013,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8920
10013
|
}
|
|
8921
10014
|
let existing = null;
|
|
8922
10015
|
try {
|
|
8923
|
-
existing =
|
|
10016
|
+
existing = fs15__namespace.readFileSync(hookPath, "utf8");
|
|
8924
10017
|
} catch {
|
|
8925
10018
|
existing = null;
|
|
8926
10019
|
}
|
|
@@ -8935,8 +10028,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8935
10028
|
};
|
|
8936
10029
|
}
|
|
8937
10030
|
try {
|
|
8938
|
-
|
|
8939
|
-
|
|
10031
|
+
fs15__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
|
|
10032
|
+
fs15__namespace.chmodSync(hookPath, 493);
|
|
8940
10033
|
} catch (err) {
|
|
8941
10034
|
return {
|
|
8942
10035
|
path: hookPath,
|
|
@@ -8958,7 +10051,6 @@ function workerEntry(directory, isCjs) {
|
|
|
8958
10051
|
}
|
|
8959
10052
|
|
|
8960
10053
|
// src/index.ts
|
|
8961
|
-
var SCHEMA_VERSION = "3.0.0";
|
|
8962
10054
|
var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
|
|
8963
10055
|
var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
|
|
8964
10056
|
var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
@@ -8966,12 +10058,21 @@ var fileDerivationBytes = 0;
|
|
|
8966
10058
|
function takeDerivation(path17, hash, settings) {
|
|
8967
10059
|
const cached = FILE_DERIVATIONS.get(path17);
|
|
8968
10060
|
if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
|
|
10061
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10062
|
+
FILE_DERIVATIONS.set(path17, cached);
|
|
8969
10063
|
return cached;
|
|
8970
10064
|
}
|
|
8971
10065
|
function rememberDerivation(path17, hash, settings, derivation) {
|
|
8972
10066
|
const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
|
|
8973
10067
|
const bytes = bodyBytes * 2 + 512;
|
|
8974
10068
|
if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
|
|
10069
|
+
const previous = FILE_DERIVATIONS.get(path17);
|
|
10070
|
+
if (previous !== void 0) {
|
|
10071
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10072
|
+
fileDerivationBytes -= previous.bytes;
|
|
10073
|
+
} else {
|
|
10074
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10075
|
+
}
|
|
8975
10076
|
while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
|
|
8976
10077
|
const oldest = FILE_DERIVATIONS.keys().next();
|
|
8977
10078
|
if (oldest.done === true) break;
|
|
@@ -8992,11 +10093,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
8992
10093
|
const lineCount = countLines(rawContent);
|
|
8993
10094
|
const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
|
|
8994
10095
|
const isLarge = sizeBytes > config.largeFileBytes;
|
|
10096
|
+
const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
|
|
8995
10097
|
let finalContent = redacted;
|
|
8996
10098
|
let isPreviewTruncated = false;
|
|
8997
10099
|
let includedLines = lineCount;
|
|
8998
10100
|
let inclusionMode = "full";
|
|
8999
|
-
if (config.skeleton === true && isSkeletonizable(relativePath)) {
|
|
10101
|
+
if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
|
|
9000
10102
|
const skeleton = skeletonizeTypeScript(redacted, relativePath);
|
|
9001
10103
|
if (skeleton.collapsed > 0) {
|
|
9002
10104
|
finalContent = skeleton.text;
|
|
@@ -9016,7 +10118,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9016
10118
|
let summarySkip = null;
|
|
9017
10119
|
let summaryWarning = null;
|
|
9018
10120
|
let dependentImports = null;
|
|
9019
|
-
if (
|
|
10121
|
+
if (oversizeForSummary) {
|
|
9020
10122
|
summarySkip = "oversize";
|
|
9021
10123
|
dependentImports = [];
|
|
9022
10124
|
} else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
|
|
@@ -9103,8 +10205,8 @@ function retain(items, keep) {
|
|
|
9103
10205
|
}
|
|
9104
10206
|
items.length = write;
|
|
9105
10207
|
}
|
|
9106
|
-
function buildIndexes(files) {
|
|
9107
|
-
const resolver = buildImportResolver(files);
|
|
10208
|
+
function buildIndexes(files, tsconfigPaths) {
|
|
10209
|
+
const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
|
|
9108
10210
|
const importerCounts = /* @__PURE__ */ new Map();
|
|
9109
10211
|
const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
|
|
9110
10212
|
const summary = file.summary;
|
|
@@ -9247,20 +10349,20 @@ function listEntries(dir) {
|
|
|
9247
10349
|
const walk = (absolute, prefix) => {
|
|
9248
10350
|
let children;
|
|
9249
10351
|
try {
|
|
9250
|
-
children =
|
|
10352
|
+
children = fs15__namespace.readdirSync(absolute, { withFileTypes: true });
|
|
9251
10353
|
} catch {
|
|
9252
10354
|
return;
|
|
9253
10355
|
}
|
|
9254
10356
|
for (const child of children) {
|
|
9255
|
-
const
|
|
9256
|
-
entries.push(
|
|
9257
|
-
if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name),
|
|
10357
|
+
const relative10 = prefix === "" ? child.name : `${prefix}/${child.name}`;
|
|
10358
|
+
entries.push(relative10);
|
|
10359
|
+
if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative10);
|
|
9258
10360
|
}
|
|
9259
10361
|
};
|
|
9260
10362
|
walk(dir, "");
|
|
9261
10363
|
return entries.sort();
|
|
9262
10364
|
}
|
|
9263
|
-
function markerInventory(dir) {
|
|
10365
|
+
function markerInventory(dir, written) {
|
|
9264
10366
|
const entries = listEntries(dir);
|
|
9265
10367
|
const files = [];
|
|
9266
10368
|
for (const entry of entries) {
|
|
@@ -9269,14 +10371,19 @@ function markerInventory(dir) {
|
|
|
9269
10371
|
const full = path16__namespace.join(dir, ...entry.split("/"));
|
|
9270
10372
|
let stats;
|
|
9271
10373
|
try {
|
|
9272
|
-
stats =
|
|
10374
|
+
stats = fs15__namespace.lstatSync(full);
|
|
9273
10375
|
} catch {
|
|
9274
10376
|
continue;
|
|
9275
10377
|
}
|
|
9276
10378
|
if (!stats.isFile()) continue;
|
|
10379
|
+
const recorded = written?.get(entry);
|
|
10380
|
+
if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
|
|
10381
|
+
files.push(recorded.digest);
|
|
10382
|
+
continue;
|
|
10383
|
+
}
|
|
9277
10384
|
let digest;
|
|
9278
10385
|
try {
|
|
9279
|
-
digest = sha256Hex2(
|
|
10386
|
+
digest = sha256Hex2(fs15__namespace.readFileSync(full));
|
|
9280
10387
|
} catch {
|
|
9281
10388
|
continue;
|
|
9282
10389
|
}
|
|
@@ -9284,8 +10391,8 @@ function markerInventory(dir) {
|
|
|
9284
10391
|
}
|
|
9285
10392
|
return { entries, files };
|
|
9286
10393
|
}
|
|
9287
|
-
function markerPayload(dir, state, id, createdAt) {
|
|
9288
|
-
const { entries, files } = markerInventory(dir);
|
|
10394
|
+
function markerPayload(dir, state, id, createdAt, written) {
|
|
10395
|
+
const { entries, files } = markerInventory(dir, written);
|
|
9289
10396
|
const marker2 = {
|
|
9290
10397
|
generator: GENERATOR_NAME,
|
|
9291
10398
|
version: GENERATOR_VERSION,
|
|
@@ -9298,13 +10405,13 @@ function markerPayload(dir, state, id, createdAt) {
|
|
|
9298
10405
|
files
|
|
9299
10406
|
};
|
|
9300
10407
|
const manifestPath = path16__namespace.join(dir, "manifest.json");
|
|
9301
|
-
if (
|
|
9302
|
-
marker2.manifestSha256 = sha256Hex2(
|
|
10408
|
+
if (fs15__namespace.existsSync(manifestPath)) {
|
|
10409
|
+
marker2.manifestSha256 = sha256Hex2(fs15__namespace.readFileSync(manifestPath));
|
|
9303
10410
|
}
|
|
9304
10411
|
return marker2;
|
|
9305
10412
|
}
|
|
9306
10413
|
function writeOwnershipMarker(dir, marker2) {
|
|
9307
|
-
|
|
10414
|
+
fs15__namespace.writeFileSync(
|
|
9308
10415
|
path16__namespace.join(dir, OWNERSHIP_MARKER),
|
|
9309
10416
|
`${JSON.stringify(marker2, null, 2)}
|
|
9310
10417
|
`,
|
|
@@ -9318,12 +10425,12 @@ function markerBelongsTo(dir, id) {
|
|
|
9318
10425
|
}
|
|
9319
10426
|
function readOwnershipMarker(dir) {
|
|
9320
10427
|
const markerPath = path16__namespace.join(dir, OWNERSHIP_MARKER);
|
|
9321
|
-
if (!
|
|
10428
|
+
if (!fs15__namespace.existsSync(markerPath)) {
|
|
9322
10429
|
return { marker: null, problem: "it holds no .codebase-snapshot marker" };
|
|
9323
10430
|
}
|
|
9324
10431
|
let raw;
|
|
9325
10432
|
try {
|
|
9326
|
-
raw =
|
|
10433
|
+
raw = fs15__namespace.readFileSync(markerPath, "utf8");
|
|
9327
10434
|
} catch {
|
|
9328
10435
|
return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
|
|
9329
10436
|
}
|
|
@@ -9426,7 +10533,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9426
10533
|
const full = path16__namespace.join(dir, ...entry.split("/"));
|
|
9427
10534
|
let stats;
|
|
9428
10535
|
try {
|
|
9429
|
-
stats =
|
|
10536
|
+
stats = fs15__namespace.lstatSync(full);
|
|
9430
10537
|
} catch {
|
|
9431
10538
|
return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
|
|
9432
10539
|
}
|
|
@@ -9451,7 +10558,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9451
10558
|
}
|
|
9452
10559
|
let digest;
|
|
9453
10560
|
try {
|
|
9454
|
-
digest = sha256Hex2(
|
|
10561
|
+
digest = sha256Hex2(fs15__namespace.readFileSync(full));
|
|
9455
10562
|
} catch {
|
|
9456
10563
|
return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
|
|
9457
10564
|
}
|
|
@@ -9473,11 +10580,11 @@ function assessSnapshotDirectory(dir) {
|
|
|
9473
10580
|
};
|
|
9474
10581
|
}
|
|
9475
10582
|
const manifestPath = path16__namespace.join(dir, "manifest.json");
|
|
9476
|
-
const hasManifest =
|
|
10583
|
+
const hasManifest = fs15__namespace.existsSync(manifestPath);
|
|
9477
10584
|
if (hasManifest) {
|
|
9478
10585
|
let raw;
|
|
9479
10586
|
try {
|
|
9480
|
-
raw =
|
|
10587
|
+
raw = fs15__namespace.readFileSync(manifestPath, "utf8");
|
|
9481
10588
|
} catch {
|
|
9482
10589
|
return {
|
|
9483
10590
|
owned: false,
|
|
@@ -9572,7 +10679,7 @@ function containsNoFiles(dir) {
|
|
|
9572
10679
|
const current = pending.pop();
|
|
9573
10680
|
let entries;
|
|
9574
10681
|
try {
|
|
9575
|
-
entries =
|
|
10682
|
+
entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
|
|
9576
10683
|
} catch {
|
|
9577
10684
|
return false;
|
|
9578
10685
|
}
|
|
@@ -9587,13 +10694,13 @@ function containsNoFiles(dir) {
|
|
|
9587
10694
|
return true;
|
|
9588
10695
|
}
|
|
9589
10696
|
function assertReplaceable(target, label, secretRules) {
|
|
9590
|
-
if (!
|
|
9591
|
-
if (!
|
|
10697
|
+
if (!fs15__namespace.existsSync(target)) return;
|
|
10698
|
+
if (!fs15__namespace.statSync(target).isDirectory()) {
|
|
9592
10699
|
throw new Error(
|
|
9593
10700
|
`Refusing to write into ${label} ${target}: it exists but is not a directory.`
|
|
9594
10701
|
);
|
|
9595
10702
|
}
|
|
9596
|
-
const entries =
|
|
10703
|
+
const entries = fs15__namespace.readdirSync(target);
|
|
9597
10704
|
if (entries.length === 0) return;
|
|
9598
10705
|
if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
|
|
9599
10706
|
if (containsNoFiles(target)) return;
|
|
@@ -9613,18 +10720,18 @@ function assertReplaceable(target, label, secretRules) {
|
|
|
9613
10720
|
);
|
|
9614
10721
|
}
|
|
9615
10722
|
function assertStagingRootUsable(tmpDir, secretRules) {
|
|
9616
|
-
if (!
|
|
9617
|
-
if (!
|
|
10723
|
+
if (!fs15__namespace.existsSync(tmpDir)) return;
|
|
10724
|
+
if (!fs15__namespace.statSync(tmpDir).isDirectory()) {
|
|
9618
10725
|
throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
|
|
9619
10726
|
}
|
|
9620
|
-
const entries =
|
|
10727
|
+
const entries = fs15__namespace.readdirSync(tmpDir);
|
|
9621
10728
|
if (entries.length === 0) return;
|
|
9622
10729
|
const foreign = entries.filter((name) => {
|
|
9623
10730
|
const full = path16__namespace.join(tmpDir, name);
|
|
9624
10731
|
if (!name.startsWith(RUN_DIR_PREFIX)) return true;
|
|
9625
10732
|
let stats;
|
|
9626
10733
|
try {
|
|
9627
|
-
stats =
|
|
10734
|
+
stats = fs15__namespace.statSync(full);
|
|
9628
10735
|
} catch {
|
|
9629
10736
|
return true;
|
|
9630
10737
|
}
|
|
@@ -9632,7 +10739,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9632
10739
|
const { marker: marker2 } = readOwnershipMarker(full);
|
|
9633
10740
|
if (marker2) return false;
|
|
9634
10741
|
try {
|
|
9635
|
-
return
|
|
10742
|
+
return fs15__namespace.readdirSync(full).length > 0;
|
|
9636
10743
|
} catch {
|
|
9637
10744
|
return true;
|
|
9638
10745
|
}
|
|
@@ -9647,7 +10754,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9647
10754
|
function cleanStaleRunDirs(tmpDir) {
|
|
9648
10755
|
let entries;
|
|
9649
10756
|
try {
|
|
9650
|
-
entries =
|
|
10757
|
+
entries = fs15__namespace.readdirSync(tmpDir);
|
|
9651
10758
|
} catch {
|
|
9652
10759
|
return;
|
|
9653
10760
|
}
|
|
@@ -9661,58 +10768,101 @@ function cleanStaleRunDirs(tmpDir) {
|
|
|
9661
10768
|
const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
|
|
9662
10769
|
if (aged || abandoned) {
|
|
9663
10770
|
try {
|
|
9664
|
-
|
|
10771
|
+
fs15__namespace.rmSync(full, { recursive: true, force: true });
|
|
9665
10772
|
} catch {
|
|
9666
10773
|
}
|
|
9667
10774
|
}
|
|
9668
10775
|
continue;
|
|
9669
10776
|
}
|
|
9670
10777
|
try {
|
|
9671
|
-
if (
|
|
10778
|
+
if (fs15__namespace.readdirSync(full).length === 0) fs15__namespace.rmSync(full, { recursive: true, force: true });
|
|
9672
10779
|
} catch {
|
|
9673
10780
|
}
|
|
9674
10781
|
}
|
|
9675
10782
|
}
|
|
9676
10783
|
function removeIfEmpty(dir) {
|
|
9677
10784
|
try {
|
|
9678
|
-
if (
|
|
10785
|
+
if (fs15__namespace.readdirSync(dir).length === 0) fs15__namespace.rmSync(dir, { recursive: true, force: true });
|
|
9679
10786
|
} catch {
|
|
9680
10787
|
}
|
|
9681
10788
|
}
|
|
9682
10789
|
function ensureParentDirectory(target, label) {
|
|
9683
10790
|
const parent = path16__namespace.dirname(target);
|
|
9684
|
-
if (
|
|
10791
|
+
if (fs15__namespace.existsSync(parent) && !fs15__namespace.statSync(parent).isDirectory()) {
|
|
9685
10792
|
throw new Error(
|
|
9686
10793
|
`Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
|
|
9687
10794
|
);
|
|
9688
10795
|
}
|
|
9689
10796
|
try {
|
|
9690
|
-
|
|
10797
|
+
fs15__namespace.mkdirSync(parent, { recursive: true });
|
|
9691
10798
|
} catch (err) {
|
|
9692
10799
|
throw new Error(
|
|
9693
10800
|
`Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
|
|
9694
10801
|
);
|
|
9695
10802
|
}
|
|
9696
10803
|
}
|
|
10804
|
+
var LOCK_HEARTBEAT_MS = 5e3;
|
|
10805
|
+
var LOCK_STALE_HEARTBEAT_MS = 12e4;
|
|
10806
|
+
var LOCK_HEARTBEAT_SOURCE = `
|
|
10807
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
10808
|
+
const fs = require("node:fs");
|
|
10809
|
+
const { lockPath, intervalMs } = workerData;
|
|
10810
|
+
const timer = setInterval(() => {
|
|
10811
|
+
try {
|
|
10812
|
+
const now = new Date();
|
|
10813
|
+
fs.utimesSync(lockPath, now, now);
|
|
10814
|
+
} catch (err) {
|
|
10815
|
+
// The lock was reclaimed or removed; nothing left to keep alive.
|
|
10816
|
+
}
|
|
10817
|
+
}, intervalMs);
|
|
10818
|
+
timer.unref();
|
|
10819
|
+
if (parentPort) {
|
|
10820
|
+
parentPort.on("message", (message) => {
|
|
10821
|
+
if (message === "stop") {
|
|
10822
|
+
clearInterval(timer);
|
|
10823
|
+
process.exit(0);
|
|
10824
|
+
}
|
|
10825
|
+
});
|
|
10826
|
+
}
|
|
10827
|
+
`;
|
|
10828
|
+
function startLockHeartbeat(lockPath) {
|
|
10829
|
+
try {
|
|
10830
|
+
const worker = new worker_threads.Worker(LOCK_HEARTBEAT_SOURCE, {
|
|
10831
|
+
eval: true,
|
|
10832
|
+
workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
|
|
10833
|
+
});
|
|
10834
|
+
worker.unref();
|
|
10835
|
+
return () => {
|
|
10836
|
+
void worker.terminate().catch(() => void 0);
|
|
10837
|
+
};
|
|
10838
|
+
} catch {
|
|
10839
|
+
return () => void 0;
|
|
10840
|
+
}
|
|
10841
|
+
}
|
|
9697
10842
|
function acquireRunLock(stagingRoot) {
|
|
9698
10843
|
const lockPath = lockPathFor(stagingRoot);
|
|
9699
10844
|
const payload = `${JSON.stringify({
|
|
9700
10845
|
pid: process.pid,
|
|
9701
10846
|
stagingRoot,
|
|
10847
|
+
host: os__namespace.hostname(),
|
|
10848
|
+
runId: crypto2__namespace.randomUUID(),
|
|
10849
|
+
heartbeatMs: LOCK_HEARTBEAT_MS,
|
|
9702
10850
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
9703
10851
|
})}
|
|
9704
10852
|
`;
|
|
9705
10853
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9706
10854
|
try {
|
|
9707
|
-
const handle =
|
|
10855
|
+
const handle = fs15__namespace.openSync(lockPath, "wx");
|
|
9708
10856
|
try {
|
|
9709
|
-
|
|
10857
|
+
fs15__namespace.writeSync(handle, payload);
|
|
9710
10858
|
} finally {
|
|
9711
|
-
|
|
10859
|
+
fs15__namespace.closeSync(handle);
|
|
9712
10860
|
}
|
|
10861
|
+
const stopHeartbeat = startLockHeartbeat(lockPath);
|
|
9713
10862
|
return () => {
|
|
10863
|
+
stopHeartbeat();
|
|
9714
10864
|
try {
|
|
9715
|
-
|
|
10865
|
+
fs15__namespace.rmSync(lockPath, { force: true });
|
|
9716
10866
|
} catch {
|
|
9717
10867
|
}
|
|
9718
10868
|
};
|
|
@@ -9720,7 +10870,7 @@ function acquireRunLock(stagingRoot) {
|
|
|
9720
10870
|
if (err.code !== "EEXIST") throw err;
|
|
9721
10871
|
if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
|
|
9722
10872
|
throw new Error(
|
|
9723
|
-
`Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete
|
|
10873
|
+
`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.`
|
|
9724
10874
|
);
|
|
9725
10875
|
}
|
|
9726
10876
|
}
|
|
@@ -9737,7 +10887,7 @@ function canonicalLockTarget(targetPath) {
|
|
|
9737
10887
|
const tail = [];
|
|
9738
10888
|
for (; ; ) {
|
|
9739
10889
|
try {
|
|
9740
|
-
return path16__namespace.join(
|
|
10890
|
+
return path16__namespace.join(fs15__namespace.realpathSync(existing), ...tail);
|
|
9741
10891
|
} catch {
|
|
9742
10892
|
const parent = path16__namespace.dirname(existing);
|
|
9743
10893
|
if (parent === existing) return resolved;
|
|
@@ -9749,10 +10899,17 @@ function canonicalLockTarget(targetPath) {
|
|
|
9749
10899
|
function lockPathFor(stagingRoot) {
|
|
9750
10900
|
return path16__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
|
|
9751
10901
|
}
|
|
10902
|
+
function lockHeartbeatAgeMs(lockPath) {
|
|
10903
|
+
try {
|
|
10904
|
+
return Date.now() - fs15__namespace.statSync(lockPath).mtimeMs;
|
|
10905
|
+
} catch {
|
|
10906
|
+
return Number.POSITIVE_INFINITY;
|
|
10907
|
+
}
|
|
10908
|
+
}
|
|
9752
10909
|
function lockOwnerIsGone(lockPath) {
|
|
9753
10910
|
let raw;
|
|
9754
10911
|
try {
|
|
9755
|
-
raw =
|
|
10912
|
+
raw = fs15__namespace.readFileSync(lockPath, "utf8");
|
|
9756
10913
|
} catch {
|
|
9757
10914
|
return false;
|
|
9758
10915
|
}
|
|
@@ -9765,96 +10922,120 @@ function lockOwnerIsGone(lockPath) {
|
|
|
9765
10922
|
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
|
|
9766
10923
|
try {
|
|
9767
10924
|
process.kill(pid, 0);
|
|
9768
|
-
return
|
|
10925
|
+
return lockFileIsAncient(lockPath);
|
|
9769
10926
|
} catch (err) {
|
|
9770
|
-
|
|
10927
|
+
if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
|
|
10928
|
+
return true;
|
|
9771
10929
|
}
|
|
9772
10930
|
}
|
|
9773
10931
|
function reclaimStaleLock(lockPath) {
|
|
9774
10932
|
let before;
|
|
9775
10933
|
try {
|
|
9776
|
-
before =
|
|
10934
|
+
before = fs15__namespace.statSync(lockPath);
|
|
9777
10935
|
} catch {
|
|
9778
10936
|
return true;
|
|
9779
10937
|
}
|
|
9780
10938
|
if (!lockOwnerIsGone(lockPath)) return false;
|
|
9781
10939
|
try {
|
|
9782
|
-
const current =
|
|
10940
|
+
const current = fs15__namespace.statSync(lockPath);
|
|
9783
10941
|
const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
|
|
9784
10942
|
if (!sameFile) return false;
|
|
9785
|
-
|
|
10943
|
+
fs15__namespace.rmSync(lockPath, { force: true });
|
|
9786
10944
|
return true;
|
|
9787
10945
|
} catch {
|
|
9788
10946
|
return false;
|
|
9789
10947
|
}
|
|
9790
10948
|
}
|
|
9791
10949
|
function lockFileIsAncient(lockPath) {
|
|
9792
|
-
|
|
9793
|
-
return Date.now() - fs14__namespace.statSync(lockPath).mtimeMs > STALE_RUN_MS;
|
|
9794
|
-
} catch {
|
|
9795
|
-
return false;
|
|
9796
|
-
}
|
|
10950
|
+
return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
|
|
9797
10951
|
}
|
|
9798
10952
|
function writeManifestAtomically(manifestPath, manifest) {
|
|
9799
10953
|
const tempPath = `${manifestPath}.${process.pid}.tmp`;
|
|
9800
|
-
|
|
10954
|
+
fs15__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
|
|
9801
10955
|
try {
|
|
9802
|
-
|
|
10956
|
+
fs15__namespace.renameSync(tempPath, manifestPath);
|
|
9803
10957
|
} catch (err) {
|
|
9804
10958
|
try {
|
|
9805
|
-
|
|
10959
|
+
fs15__namespace.rmSync(tempPath, { force: true });
|
|
9806
10960
|
} catch {
|
|
9807
10961
|
}
|
|
9808
10962
|
throw err;
|
|
9809
10963
|
}
|
|
9810
10964
|
}
|
|
9811
|
-
function swapIntoPlace(stagingDir, outDir) {
|
|
10965
|
+
function swapIntoPlace(stagingDir, outDir, beforeSwap) {
|
|
9812
10966
|
ensureParentDirectory(outDir, "outDir");
|
|
9813
10967
|
const deadline = Date.now() + 3e3;
|
|
9814
|
-
|
|
10968
|
+
let delay = 25;
|
|
10969
|
+
for (; ; ) {
|
|
9815
10970
|
try {
|
|
9816
|
-
swapOnce(stagingDir, outDir);
|
|
10971
|
+
swapOnce(stagingDir, outDir, beforeSwap);
|
|
9817
10972
|
return;
|
|
9818
10973
|
} catch (err) {
|
|
9819
10974
|
const code = err.code;
|
|
9820
|
-
const
|
|
9821
|
-
|
|
9822
|
-
|
|
10975
|
+
const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
|
|
10976
|
+
const remaining = deadline - Date.now();
|
|
10977
|
+
if (!retryable || remaining <= 0) throw err;
|
|
10978
|
+
sleepSync(Math.min(delay, remaining));
|
|
10979
|
+
delay = Math.min(delay * 2, 400);
|
|
9823
10980
|
}
|
|
9824
10981
|
}
|
|
9825
10982
|
}
|
|
9826
|
-
function
|
|
10983
|
+
function recoverInterruptedPublish(outDir) {
|
|
10984
|
+
if (fs15__namespace.existsSync(outDir)) return;
|
|
10985
|
+
const parent = path16__namespace.dirname(outDir);
|
|
10986
|
+
const base = path16__namespace.basename(outDir);
|
|
10987
|
+
let backups;
|
|
10988
|
+
try {
|
|
10989
|
+
backups = fs15__namespace.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
|
|
10990
|
+
} catch {
|
|
10991
|
+
return;
|
|
10992
|
+
}
|
|
10993
|
+
if (backups.length !== 1) return;
|
|
10994
|
+
const backupDir = path16__namespace.join(parent, backups[0]);
|
|
10995
|
+
const { marker: marker2, problem } = readOwnershipMarker(backupDir);
|
|
10996
|
+
if (problem !== null || marker2 === null || marker2.state !== "complete") return;
|
|
10997
|
+
try {
|
|
10998
|
+
fs15__namespace.renameSync(backupDir, outDir);
|
|
10999
|
+
process.stderr.write(
|
|
11000
|
+
`\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
|
|
11001
|
+
`
|
|
11002
|
+
);
|
|
11003
|
+
} catch {
|
|
11004
|
+
}
|
|
11005
|
+
}
|
|
11006
|
+
function swapOnce(stagingDir, outDir, beforeSwap) {
|
|
9827
11007
|
const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
|
|
9828
|
-
const hadPrevious =
|
|
9829
|
-
if (hadPrevious)
|
|
11008
|
+
const hadPrevious = fs15__namespace.existsSync(outDir);
|
|
11009
|
+
if (hadPrevious) beforeSwap?.();
|
|
11010
|
+
if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
|
|
9830
11011
|
try {
|
|
9831
11012
|
try {
|
|
9832
|
-
|
|
11013
|
+
fs15__namespace.renameSync(stagingDir, outDir);
|
|
9833
11014
|
} catch (err) {
|
|
9834
11015
|
if (err.code !== "EXDEV") throw err;
|
|
9835
11016
|
const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
|
|
9836
11017
|
try {
|
|
9837
|
-
|
|
9838
|
-
|
|
9839
|
-
|
|
11018
|
+
fs15__namespace.cpSync(stagingDir, partialDir, { recursive: true });
|
|
11019
|
+
fs15__namespace.renameSync(partialDir, outDir);
|
|
11020
|
+
fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
|
|
9840
11021
|
} catch (copyErr) {
|
|
9841
11022
|
try {
|
|
9842
|
-
|
|
11023
|
+
fs15__namespace.rmSync(partialDir, { recursive: true, force: true });
|
|
9843
11024
|
} catch {
|
|
9844
11025
|
}
|
|
9845
11026
|
throw copyErr;
|
|
9846
11027
|
}
|
|
9847
11028
|
}
|
|
9848
11029
|
} catch (err) {
|
|
9849
|
-
if (hadPrevious &&
|
|
9850
|
-
if (
|
|
9851
|
-
|
|
11030
|
+
if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
|
|
11031
|
+
if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
|
|
11032
|
+
fs15__namespace.renameSync(backupDir, outDir);
|
|
9852
11033
|
}
|
|
9853
11034
|
throw err;
|
|
9854
11035
|
}
|
|
9855
11036
|
if (hadPrevious) {
|
|
9856
11037
|
try {
|
|
9857
|
-
|
|
11038
|
+
fs15__namespace.rmSync(backupDir, { recursive: true, force: true });
|
|
9858
11039
|
} catch (err) {
|
|
9859
11040
|
process.stderr.write(
|
|
9860
11041
|
`\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.
|
|
@@ -9931,6 +11112,13 @@ function generateSnapshot(configInput, options) {
|
|
|
9931
11112
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
|
|
9932
11113
|
const dryRun = options?.dryRun ?? false;
|
|
9933
11114
|
const gitInfo = getGitInfo(config.cwd, config.branch);
|
|
11115
|
+
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
11116
|
+
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
11117
|
+
...config.staged === true ? { staged: true } : {}
|
|
11118
|
+
}) : null;
|
|
11119
|
+
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
11120
|
+
const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
|
|
11121
|
+
const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
|
|
9934
11122
|
const collection = collectFiles(config.cwd, {
|
|
9935
11123
|
includePatterns: config.include,
|
|
9936
11124
|
excludePatterns: [...config.excludePatterns, ...config.presetExclude],
|
|
@@ -9942,13 +11130,11 @@ function generateSnapshot(configInput, options) {
|
|
|
9942
11130
|
// output — but only at these exact paths, not at every directory that shares the name.
|
|
9943
11131
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
9944
11132
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
9945
|
-
).filter((
|
|
11133
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith("..")),
|
|
11134
|
+
// A staged path can be absent from the working tree while its index blob exists. Discovery
|
|
11135
|
+
// lists the working tree, so those paths would never reach the scan at all.
|
|
11136
|
+
...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
|
|
9946
11137
|
});
|
|
9947
|
-
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
9948
|
-
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
9949
|
-
...config.staged === true ? { staged: true } : {}
|
|
9950
|
-
}) : null;
|
|
9951
|
-
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
9952
11138
|
const unchangedPaths = [];
|
|
9953
11139
|
const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
|
|
9954
11140
|
if (changedPaths.has(relativePath)) return true;
|
|
@@ -9970,45 +11156,92 @@ function generateSnapshot(configInput, options) {
|
|
|
9970
11156
|
const oversizeSummaryPaths = [];
|
|
9971
11157
|
const previewSummaryPaths = [];
|
|
9972
11158
|
const skippedSummaryImports = /* @__PURE__ */ new Map();
|
|
9973
|
-
const layerCounts =
|
|
9974
|
-
const kindCounts =
|
|
11159
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
11160
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
9975
11161
|
let totalLines = 0;
|
|
9976
11162
|
let totalSizeBytes = 0;
|
|
9977
11163
|
let largeFileCount = 0;
|
|
9978
11164
|
for (const relativePath of candidateFiles) {
|
|
9979
11165
|
const absolutePath = path16__namespace.join(config.cwd, relativePath);
|
|
9980
|
-
|
|
9981
|
-
|
|
9982
|
-
|
|
9983
|
-
|
|
9984
|
-
|
|
9985
|
-
|
|
9986
|
-
|
|
11166
|
+
const fromIndex = stagedPaths.has(relativePath);
|
|
11167
|
+
let buffer;
|
|
11168
|
+
let sizeBytes;
|
|
11169
|
+
if (fromIndex && stagedDeletedPaths.has(relativePath)) {
|
|
11170
|
+
skipped.push({
|
|
11171
|
+
path: relativePath,
|
|
11172
|
+
reason: "deleted",
|
|
11173
|
+
detail: "staged for deletion; it is not part of the next commit"
|
|
11174
|
+
});
|
|
11175
|
+
continue;
|
|
11176
|
+
}
|
|
11177
|
+
if (fromIndex) {
|
|
11178
|
+
const staged = readStagedBlob(config.cwd, relativePath);
|
|
11179
|
+
if (staged === null) {
|
|
11180
|
+
skipped.push({
|
|
11181
|
+
path: relativePath,
|
|
11182
|
+
reason: "deleted",
|
|
11183
|
+
detail: "staged path has no blob in the index; it is not part of the next commit"
|
|
11184
|
+
});
|
|
11185
|
+
continue;
|
|
11186
|
+
}
|
|
11187
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11188
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
|
|
11189
|
+
continue;
|
|
11190
|
+
}
|
|
11191
|
+
buffer = staged;
|
|
11192
|
+
sizeBytes = staged.length;
|
|
11193
|
+
} else {
|
|
11194
|
+
let stats;
|
|
11195
|
+
try {
|
|
11196
|
+
stats = fs15__namespace.statSync(absolutePath);
|
|
11197
|
+
if (!stats.isFile()) {
|
|
11198
|
+
const nestedRepository = stats.isDirectory() && fs15__namespace.existsSync(path16__namespace.join(absolutePath, ".git"));
|
|
11199
|
+
skipped.push(
|
|
11200
|
+
nestedRepository ? {
|
|
11201
|
+
path: relativePath,
|
|
11202
|
+
reason: "nested-repository",
|
|
11203
|
+
detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
|
|
11204
|
+
} : { path: relativePath, reason: "not-file" }
|
|
11205
|
+
);
|
|
11206
|
+
continue;
|
|
11207
|
+
}
|
|
11208
|
+
} catch (err) {
|
|
11209
|
+
const code = err.code;
|
|
11210
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
11211
|
+
skipped.push({
|
|
9987
11212
|
path: relativePath,
|
|
9988
|
-
reason: "
|
|
9989
|
-
detail: "
|
|
9990
|
-
}
|
|
9991
|
-
|
|
11213
|
+
reason: "missing",
|
|
11214
|
+
detail: "tracked but absent from disk (deleted without staging)"
|
|
11215
|
+
});
|
|
11216
|
+
} else {
|
|
11217
|
+
skipped.push({
|
|
11218
|
+
path: relativePath,
|
|
11219
|
+
reason: "read-error",
|
|
11220
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11221
|
+
});
|
|
11222
|
+
}
|
|
9992
11223
|
continue;
|
|
9993
11224
|
}
|
|
9994
|
-
|
|
9995
|
-
|
|
9996
|
-
|
|
9997
|
-
|
|
9998
|
-
|
|
9999
|
-
|
|
10000
|
-
|
|
10001
|
-
|
|
10002
|
-
|
|
10003
|
-
|
|
10004
|
-
|
|
10005
|
-
|
|
10006
|
-
|
|
10007
|
-
|
|
10008
|
-
|
|
10009
|
-
|
|
10010
|
-
|
|
10011
|
-
|
|
11225
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11226
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11227
|
+
continue;
|
|
11228
|
+
}
|
|
11229
|
+
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
|
|
11230
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11231
|
+
continue;
|
|
11232
|
+
}
|
|
11233
|
+
try {
|
|
11234
|
+
buffer = fs15__namespace.readFileSync(absolutePath);
|
|
11235
|
+
} catch (err) {
|
|
11236
|
+
const code = err.code;
|
|
11237
|
+
skipped.push({
|
|
11238
|
+
path: relativePath,
|
|
11239
|
+
reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
|
|
11240
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11241
|
+
});
|
|
11242
|
+
continue;
|
|
11243
|
+
}
|
|
11244
|
+
sizeBytes = stats.size;
|
|
10012
11245
|
}
|
|
10013
11246
|
let decoded;
|
|
10014
11247
|
try {
|
|
@@ -10017,7 +11250,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10017
11250
|
skipped.push({
|
|
10018
11251
|
path: relativePath,
|
|
10019
11252
|
reason: "read-error",
|
|
10020
|
-
detail: `Size: ${
|
|
11253
|
+
detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
|
|
10021
11254
|
/\s+/g,
|
|
10022
11255
|
" "
|
|
10023
11256
|
)
|
|
@@ -10028,13 +11261,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10028
11261
|
skipped.push({
|
|
10029
11262
|
path: relativePath,
|
|
10030
11263
|
reason: "binary",
|
|
10031
|
-
detail: `Size: ${
|
|
11264
|
+
detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
|
|
10032
11265
|
});
|
|
10033
11266
|
continue;
|
|
10034
11267
|
}
|
|
10035
11268
|
const hashSha256 = sha256Hex2(buffer);
|
|
10036
11269
|
const rawContent = decoded.text;
|
|
10037
|
-
totalSizeBytes +=
|
|
11270
|
+
totalSizeBytes += sizeBytes;
|
|
10038
11271
|
if (decoded.encoding !== "utf-8") {
|
|
10039
11272
|
encodingNotes.push({
|
|
10040
11273
|
path: relativePath,
|
|
@@ -10048,7 +11281,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10048
11281
|
bump(layerCounts, layer2);
|
|
10049
11282
|
bump(kindCounts, kind);
|
|
10050
11283
|
const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
|
|
10051
|
-
const fresh = deriveFile(relativePath, rawContent,
|
|
11284
|
+
const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
|
|
10052
11285
|
rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
|
|
10053
11286
|
return fresh;
|
|
10054
11287
|
})();
|
|
@@ -10069,7 +11302,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10069
11302
|
}
|
|
10070
11303
|
files.push({
|
|
10071
11304
|
relativePath,
|
|
10072
|
-
sizeBytes
|
|
11305
|
+
sizeBytes,
|
|
10073
11306
|
lines: lineCount,
|
|
10074
11307
|
hashSha256,
|
|
10075
11308
|
part: "",
|
|
@@ -10090,7 +11323,10 @@ function generateSnapshot(configInput, options) {
|
|
|
10090
11323
|
}
|
|
10091
11324
|
if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
|
|
10092
11325
|
const keep = new Set(changedPaths);
|
|
10093
|
-
const resolver = buildImportResolver(files
|
|
11326
|
+
const resolver = buildImportResolver(files, {
|
|
11327
|
+
extraPaths: changedPaths,
|
|
11328
|
+
tsconfig: tsconfigPathsFor(config.cwd)
|
|
11329
|
+
});
|
|
10094
11330
|
for (const file of files) {
|
|
10095
11331
|
const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
|
|
10096
11332
|
if (fileImports.length === 0) continue;
|
|
@@ -10184,7 +11420,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10184
11420
|
const fingerprint = sha256Hex2(
|
|
10185
11421
|
[
|
|
10186
11422
|
...files.map(
|
|
10187
|
-
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}
|
|
11423
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
10188
11424
|
),
|
|
10189
11425
|
`settings:${configDigest(config)}`
|
|
10190
11426
|
].join("\n")
|
|
@@ -10271,6 +11507,8 @@ function generateSnapshot(configInput, options) {
|
|
|
10271
11507
|
skippedFiles: skipped.length,
|
|
10272
11508
|
totalSourceBytes: totalSizeBytes,
|
|
10273
11509
|
totalContentBytes,
|
|
11510
|
+
sourceLines: totalLines,
|
|
11511
|
+
emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
|
|
10274
11512
|
// The parts are what a model is handed, so the estimate is over the parts rather than
|
|
10275
11513
|
// over the sources: previews and the byte budget both shrink the number.
|
|
10276
11514
|
estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
|
|
@@ -10289,7 +11527,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10289
11527
|
},
|
|
10290
11528
|
layers: layerCounts,
|
|
10291
11529
|
kinds: kindCounts,
|
|
10292
|
-
indexes: buildIndexes(files),
|
|
11530
|
+
indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
|
|
10293
11531
|
parts: parts.map((part) => part.metadata),
|
|
10294
11532
|
files: files.map((file) => {
|
|
10295
11533
|
const { content: _content, ...rest } = file;
|
|
@@ -10306,6 +11544,23 @@ function generateSnapshot(configInput, options) {
|
|
|
10306
11544
|
);
|
|
10307
11545
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10308
11546
|
}
|
|
11547
|
+
if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
|
|
11548
|
+
manifest.warnings.push(
|
|
11549
|
+
`${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.`
|
|
11550
|
+
);
|
|
11551
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11552
|
+
}
|
|
11553
|
+
if (config.maxPartTokens !== void 0) {
|
|
11554
|
+
const overTokenBudget = parts.filter(
|
|
11555
|
+
(part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
|
|
11556
|
+
);
|
|
11557
|
+
if (overTokenBudget.length > 0) {
|
|
11558
|
+
manifest.warnings.push(
|
|
11559
|
+
`${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.`
|
|
11560
|
+
);
|
|
11561
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11562
|
+
}
|
|
11563
|
+
}
|
|
10309
11564
|
if (secretFindings.length > 0 && !config.artifacts.audit) {
|
|
10310
11565
|
manifest.warnings.push(
|
|
10311
11566
|
`${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
|
|
@@ -10334,6 +11589,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10334
11589
|
sha256: sha256Hex2(sarifText)
|
|
10335
11590
|
};
|
|
10336
11591
|
}
|
|
11592
|
+
const artifacts = config.artifacts;
|
|
11593
|
+
const artifactRecord = (text2) => ({
|
|
11594
|
+
byteSize: Buffer.byteLength(text2, "utf8"),
|
|
11595
|
+
sha256: sha256Hex2(text2)
|
|
11596
|
+
});
|
|
11597
|
+
const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
|
|
11598
|
+
if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
|
|
11599
|
+
const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
|
|
11600
|
+
if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
|
|
11601
|
+
const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
|
|
11602
|
+
if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
|
|
11603
|
+
if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
|
|
10337
11604
|
let monolithJson = null;
|
|
10338
11605
|
let monolithMarkdown = null;
|
|
10339
11606
|
if (config.includeMonolith) {
|
|
@@ -10348,26 +11615,33 @@ function generateSnapshot(configInput, options) {
|
|
|
10348
11615
|
includedLines: countLines(content)
|
|
10349
11616
|
};
|
|
10350
11617
|
});
|
|
10351
|
-
const
|
|
10352
|
-
const
|
|
10353
|
-
if (
|
|
11618
|
+
const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
|
|
11619
|
+
const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
|
|
11620
|
+
if (definitelyTooLarge) {
|
|
11621
|
+
const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
|
|
11622
|
+
manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
|
|
11623
|
+
manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
|
|
11624
|
+
}
|
|
11625
|
+
const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
|
|
11626
|
+
const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
|
|
11627
|
+
if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
|
|
10354
11628
|
monolithMarkdown = markdown;
|
|
10355
11629
|
manifest.artifacts.fullMarkdown = {
|
|
10356
11630
|
byteSize: markdownBytes,
|
|
10357
11631
|
sha256: sha256Hex2(markdown)
|
|
10358
11632
|
};
|
|
10359
|
-
} else {
|
|
11633
|
+
} else if (!definitelyTooLarge) {
|
|
10360
11634
|
manifest.warnings.push(
|
|
10361
11635
|
`full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10362
11636
|
);
|
|
10363
11637
|
}
|
|
10364
11638
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10365
|
-
const json = generateMonolithJson(manifest, fullFiles);
|
|
10366
|
-
const jsonBytes = Buffer.byteLength(json, "utf8");
|
|
10367
|
-
if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
|
|
11639
|
+
const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
|
|
11640
|
+
const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
|
|
11641
|
+
if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
|
|
10368
11642
|
monolithJson = json;
|
|
10369
11643
|
manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
|
|
10370
|
-
} else {
|
|
11644
|
+
} else if (!definitelyTooLarge) {
|
|
10371
11645
|
manifest.warnings.push(
|
|
10372
11646
|
`full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10373
11647
|
);
|
|
@@ -10375,7 +11649,6 @@ function generateSnapshot(configInput, options) {
|
|
|
10375
11649
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10376
11650
|
}
|
|
10377
11651
|
const { outDir, tmpDir } = resolveSafeOutputDirs(config);
|
|
10378
|
-
const { artifacts } = config;
|
|
10379
11652
|
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10380
11653
|
assertStagingRootUsable(tmpDir, config.secretRules);
|
|
10381
11654
|
if (dryRun) {
|
|
@@ -10392,15 +11665,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10392
11665
|
const releaseLock = () => {
|
|
10393
11666
|
for (const release of [...releases].reverse()) release();
|
|
10394
11667
|
};
|
|
11668
|
+
recoverInterruptedPublish(outDir);
|
|
11669
|
+
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10395
11670
|
let stagingDir = null;
|
|
11671
|
+
let releaseDeferred = false;
|
|
10396
11672
|
try {
|
|
10397
11673
|
ensureParentDirectory(outDir, "outDir");
|
|
10398
|
-
|
|
11674
|
+
fs15__namespace.mkdirSync(tmpDir, { recursive: true });
|
|
10399
11675
|
cleanStaleRunDirs(tmpDir);
|
|
10400
11676
|
const snapshotId = crypto2__namespace.randomUUID();
|
|
10401
11677
|
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
10402
11678
|
stagingDir = path16__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
|
|
10403
|
-
|
|
11679
|
+
fs15__namespace.mkdirSync(stagingDir);
|
|
10404
11680
|
writeOwnershipMarker(stagingDir, {
|
|
10405
11681
|
generator: GENERATOR_NAME,
|
|
10406
11682
|
version: GENERATOR_VERSION,
|
|
@@ -10412,45 +11688,66 @@ function generateSnapshot(configInput, options) {
|
|
|
10412
11688
|
});
|
|
10413
11689
|
const partsDir = path16__namespace.join(stagingDir, "parts");
|
|
10414
11690
|
const reportsDir = path16__namespace.join(stagingDir, "reports");
|
|
10415
|
-
if (artifacts.parts)
|
|
11691
|
+
if (artifacts.parts) fs15__namespace.mkdirSync(partsDir, { recursive: true });
|
|
10416
11692
|
if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
|
|
10417
|
-
|
|
10418
|
-
}
|
|
11693
|
+
fs15__namespace.mkdirSync(reportsDir, { recursive: true });
|
|
11694
|
+
}
|
|
11695
|
+
const writtenArtifacts = /* @__PURE__ */ new Map();
|
|
11696
|
+
const writeArtifact = (targetDir, relativeEntry, data) => {
|
|
11697
|
+
const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
|
|
11698
|
+
fs15__namespace.writeFileSync(full, data, "utf8");
|
|
11699
|
+
const stats = fs15__namespace.statSync(full);
|
|
11700
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11701
|
+
digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
|
|
11702
|
+
mtimeMs: stats.mtimeMs
|
|
11703
|
+
});
|
|
11704
|
+
};
|
|
11705
|
+
const recordArtifact = (targetDir, relativeEntry) => {
|
|
11706
|
+
const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
|
|
11707
|
+
const stats = fs15__namespace.statSync(full);
|
|
11708
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11709
|
+
digest: {
|
|
11710
|
+
path: relativeEntry,
|
|
11711
|
+
bytes: stats.size,
|
|
11712
|
+
sha256: sha256Hex2(fs15__namespace.readFileSync(full))
|
|
11713
|
+
},
|
|
11714
|
+
mtimeMs: stats.mtimeMs
|
|
11715
|
+
});
|
|
11716
|
+
};
|
|
10419
11717
|
if (artifacts.parts) {
|
|
10420
11718
|
for (const part of parts) {
|
|
10421
|
-
|
|
11719
|
+
writeArtifact(partsDir, part.filename, part.markdown);
|
|
10422
11720
|
}
|
|
10423
11721
|
}
|
|
10424
11722
|
if (projectTree !== null) {
|
|
10425
|
-
|
|
11723
|
+
writeArtifact(reportsDir, "project-tree.md", projectTree);
|
|
10426
11724
|
}
|
|
10427
|
-
if (
|
|
10428
|
-
|
|
11725
|
+
if (navigationText !== null) {
|
|
11726
|
+
writeArtifact(reportsDir, "navigation.md", navigationText);
|
|
10429
11727
|
}
|
|
10430
|
-
if (
|
|
10431
|
-
|
|
10432
|
-
path16__namespace.join(reportsDir, "audit.md"),
|
|
10433
|
-
generateAuditReport(manifest, secretFindings, config.secretRules),
|
|
10434
|
-
"utf8"
|
|
10435
|
-
);
|
|
11728
|
+
if (auditText !== null) {
|
|
11729
|
+
writeArtifact(reportsDir, "audit.md", auditText);
|
|
10436
11730
|
}
|
|
10437
11731
|
if (sarifText !== null) {
|
|
10438
|
-
|
|
11732
|
+
writeArtifact(reportsDir, "audit.sarif", sarifText);
|
|
10439
11733
|
}
|
|
10440
|
-
if (
|
|
10441
|
-
|
|
11734
|
+
if (readmeText !== null) {
|
|
11735
|
+
writeArtifact(stagingDir, "README.md", readmeText);
|
|
10442
11736
|
}
|
|
10443
11737
|
if (artifacts.manifest) {
|
|
10444
|
-
|
|
11738
|
+
writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
|
|
10445
11739
|
}
|
|
10446
11740
|
if (monolithJson !== null) {
|
|
10447
|
-
|
|
11741
|
+
writeArtifact(stagingDir, "full-codebase.json", monolithJson);
|
|
10448
11742
|
}
|
|
10449
11743
|
if (monolithMarkdown !== null) {
|
|
10450
|
-
|
|
11744
|
+
writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
|
|
10451
11745
|
}
|
|
10452
|
-
writeOwnershipMarker(
|
|
10453
|
-
|
|
11746
|
+
writeOwnershipMarker(
|
|
11747
|
+
stagingDir,
|
|
11748
|
+
markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11749
|
+
);
|
|
11750
|
+
swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
|
|
10454
11751
|
stagingDir = null;
|
|
10455
11752
|
const warningsBeforeHook = manifest.warnings.length;
|
|
10456
11753
|
const pendingHook = runAfterGenerate(config, manifest);
|
|
@@ -10458,8 +11755,12 @@ function generateSnapshot(configInput, options) {
|
|
|
10458
11755
|
if (!markerBelongsTo(outDir, snapshotId)) return;
|
|
10459
11756
|
if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
|
|
10460
11757
|
writeManifestAtomically(path16__namespace.join(outDir, "manifest.json"), manifest);
|
|
11758
|
+
recordArtifact(outDir, "manifest.json");
|
|
10461
11759
|
}
|
|
10462
|
-
writeOwnershipMarker(
|
|
11760
|
+
writeOwnershipMarker(
|
|
11761
|
+
outDir,
|
|
11762
|
+
markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11763
|
+
);
|
|
10463
11764
|
};
|
|
10464
11765
|
if (config.hooks.afterGenerate) shipHookState();
|
|
10465
11766
|
if (pendingHook) {
|
|
@@ -10486,19 +11787,26 @@ function generateSnapshot(configInput, options) {
|
|
|
10486
11787
|
if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
|
|
10487
11788
|
});
|
|
10488
11789
|
pendingHooks.set(outDir, tracked);
|
|
11790
|
+
releaseDeferred = true;
|
|
11791
|
+
void tracked.finally(() => {
|
|
11792
|
+
removeIfEmpty(tmpDir);
|
|
11793
|
+
releaseLock();
|
|
11794
|
+
});
|
|
10489
11795
|
}
|
|
10490
11796
|
return manifest;
|
|
10491
11797
|
} catch (err) {
|
|
10492
11798
|
if (stagingDir !== null) {
|
|
10493
11799
|
try {
|
|
10494
|
-
|
|
11800
|
+
fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
|
|
10495
11801
|
} catch {
|
|
10496
11802
|
}
|
|
10497
11803
|
}
|
|
10498
11804
|
throw err;
|
|
10499
11805
|
} finally {
|
|
10500
|
-
|
|
10501
|
-
|
|
11806
|
+
if (!releaseDeferred) {
|
|
11807
|
+
removeIfEmpty(tmpDir);
|
|
11808
|
+
releaseLock();
|
|
11809
|
+
}
|
|
10502
11810
|
}
|
|
10503
11811
|
}
|
|
10504
11812
|
var pendingHooks = /* @__PURE__ */ new Map();
|
|
@@ -10533,6 +11841,7 @@ exports.PromptCancelled = PromptCancelled;
|
|
|
10533
11841
|
exports.REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
|
|
10534
11842
|
exports.SCHEMA_VERSION = SCHEMA_VERSION;
|
|
10535
11843
|
exports.anchorForPath = anchorForPath;
|
|
11844
|
+
exports.appendGitignoreEntries = appendGitignoreEntries;
|
|
10536
11845
|
exports.assertReplaceable = assertReplaceable;
|
|
10537
11846
|
exports.assertUsableConfigInput = assertUsableConfigInput;
|
|
10538
11847
|
exports.buildImportResolver = buildImportResolver;
|
|
@@ -10569,6 +11878,7 @@ exports.generateSnapshot = generateSnapshot;
|
|
|
10569
11878
|
exports.generateSnapshotAsync = generateSnapshotAsync;
|
|
10570
11879
|
exports.getGitInfo = getGitInfo;
|
|
10571
11880
|
exports.getPreset = getPreset;
|
|
11881
|
+
exports.gitignorePath = gitignorePath;
|
|
10572
11882
|
exports.globToRegExp = globToRegExp;
|
|
10573
11883
|
exports.hasPriorSnapshot = hasPriorSnapshot;
|
|
10574
11884
|
exports.importsChangedFile = importsChangedFile;
|
|
@@ -10619,6 +11929,7 @@ exports.summarizeWithProfile = summarizeWithProfile;
|
|
|
10619
11929
|
exports.supportsTypeScriptImports = supportsTypeScriptImports;
|
|
10620
11930
|
exports.truncatePreview = truncatePreview;
|
|
10621
11931
|
exports.truncateToBytes = truncateToBytes;
|
|
11932
|
+
exports.tsconfigPathsFor = tsconfigPathsFor;
|
|
10622
11933
|
exports.updateCommand = updateCommand;
|
|
10623
11934
|
exports.validateSnapshot = validateSnapshot;
|
|
10624
11935
|
exports.workerEntry = workerEntry;
|