codebase-snapshot 0.9.16 → 0.9.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/README.md +4 -4
- package/SECURITY.md +18 -6
- package/dist/bin.js +2024 -622
- package/dist/{chunk-WIL536QD.js → chunk-XAW5GY6X.js} +98 -25
- package/dist/{chunk-6TRFLA7N.js → chunk-ZXWAVHSZ.js} +1758 -444
- package/dist/cli.cjs +2006 -608
- package/dist/cli.d.cts +1 -11
- package/dist/cli.d.ts +1 -11
- package/dist/cli.js +17 -6
- package/dist/index.cjs +1752 -438
- package/dist/index.d.cts +106 -9
- package/dist/index.d.ts +106 -9
- package/dist/index.js +1 -1
- package/dist/mcp.cjs +1761 -341
- package/dist/mcp.d.cts +7 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.js +2 -2
- package/dist/{types-DIX6zWSt.d.cts → types-KbJvBjmV.d.cts} +46 -1
- package/dist/{types-DIX6zWSt.d.ts → types-KbJvBjmV.d.ts} +46 -1
- package/docs/cli.md +20 -13
- package/docs/configuration.md +16 -1
- package/docs/mcp.md +17 -7
- package/docs/output.md +3 -3
- package/docs/vs-gitingest.md +6 -2
- package/docs/vs-repomix.md +9 -5
- package/package.json +16 -18
package/dist/cli.cjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var childProcess = require('child_process');
|
|
4
|
-
var
|
|
4
|
+
var fs15 = require('fs');
|
|
5
5
|
var path16 = require('path');
|
|
6
6
|
var util = require('util');
|
|
7
7
|
var crypto3 = require('crypto');
|
|
8
8
|
var module$1 = require('module');
|
|
9
9
|
var url = require('url');
|
|
10
|
-
var
|
|
10
|
+
var ts2 = require('typescript');
|
|
11
11
|
var readline = require('readline');
|
|
12
|
+
var worker_threads = require('worker_threads');
|
|
12
13
|
var async_hooks = require('async_hooks');
|
|
13
14
|
var os = require('os');
|
|
14
15
|
var http = require('http');
|
|
15
16
|
var https = require('https');
|
|
16
|
-
var worker_threads = require('worker_threads');
|
|
17
17
|
|
|
18
18
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
19
19
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
@@ -37,10 +37,10 @@ function _interopNamespace(e) {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
|
|
40
|
-
var
|
|
40
|
+
var fs15__namespace = /*#__PURE__*/_interopNamespace(fs15);
|
|
41
41
|
var path16__namespace = /*#__PURE__*/_interopNamespace(path16);
|
|
42
42
|
var crypto3__namespace = /*#__PURE__*/_interopNamespace(crypto3);
|
|
43
|
-
var
|
|
43
|
+
var ts2__default = /*#__PURE__*/_interopDefault(ts2);
|
|
44
44
|
var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
|
|
45
45
|
var os__namespace = /*#__PURE__*/_interopNamespace(os);
|
|
46
46
|
var http__namespace = /*#__PURE__*/_interopNamespace(http);
|
|
@@ -93,9 +93,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
|
|
|
93
93
|
]);
|
|
94
94
|
function readSmallFile(fullPath) {
|
|
95
95
|
try {
|
|
96
|
-
const stats =
|
|
96
|
+
const stats = fs15__namespace.statSync(fullPath);
|
|
97
97
|
if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
|
|
98
|
-
return
|
|
98
|
+
return fs15__namespace.readFileSync(fullPath, "utf8");
|
|
99
99
|
} catch {
|
|
100
100
|
return null;
|
|
101
101
|
}
|
|
@@ -161,7 +161,7 @@ function pnpmWorkspacePatterns(raw) {
|
|
|
161
161
|
function childDirectories(cwd, parent) {
|
|
162
162
|
let entries;
|
|
163
163
|
try {
|
|
164
|
-
entries =
|
|
164
|
+
entries = fs15__namespace.readdirSync(path16__namespace.join(cwd, parent), { withFileTypes: true });
|
|
165
165
|
} catch {
|
|
166
166
|
return [];
|
|
167
167
|
}
|
|
@@ -196,10 +196,10 @@ function workspacePackageDirs(cwd, patterns) {
|
|
|
196
196
|
function scanWorkspacePackages(cwd, patterns) {
|
|
197
197
|
const files = /* @__PURE__ */ new Set();
|
|
198
198
|
const dependencies = /* @__PURE__ */ new Set();
|
|
199
|
-
for (const
|
|
200
|
-
const full = path16__namespace.join(cwd,
|
|
199
|
+
for (const relative14 of workspacePackageDirs(cwd, patterns)) {
|
|
200
|
+
const full = path16__namespace.join(cwd, relative14);
|
|
201
201
|
try {
|
|
202
|
-
for (const entry of
|
|
202
|
+
for (const entry of fs15__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
|
|
203
203
|
} catch {
|
|
204
204
|
}
|
|
205
205
|
const raw = readSmallFile(path16__namespace.join(full, "package.json"));
|
|
@@ -212,7 +212,7 @@ function scanWorkspacePackages(cwd, patterns) {
|
|
|
212
212
|
var SNAPSHOT_MARKER = ".codebase-snapshot";
|
|
213
213
|
function isToolOwnedDirectory(dir) {
|
|
214
214
|
try {
|
|
215
|
-
return
|
|
215
|
+
return fs15__namespace.statSync(dir).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(dir, SNAPSHOT_MARKER));
|
|
216
216
|
} catch {
|
|
217
217
|
return false;
|
|
218
218
|
}
|
|
@@ -227,7 +227,7 @@ function countMarkdownFiles(cwd) {
|
|
|
227
227
|
directoriesSeen += 1;
|
|
228
228
|
let entries;
|
|
229
229
|
try {
|
|
230
|
-
entries =
|
|
230
|
+
entries = fs15__namespace.readdirSync(current.dir, { withFileTypes: true });
|
|
231
231
|
} catch {
|
|
232
232
|
continue;
|
|
233
233
|
}
|
|
@@ -249,7 +249,7 @@ function buildPresetContext(cwd) {
|
|
|
249
249
|
const files = /* @__PURE__ */ new Set();
|
|
250
250
|
const dirs = /* @__PURE__ */ new Set();
|
|
251
251
|
try {
|
|
252
|
-
for (const entry of
|
|
252
|
+
for (const entry of fs15__namespace.readdirSync(cwd, { withFileTypes: true })) {
|
|
253
253
|
if (entry.isDirectory()) dirs.add(entry.name);
|
|
254
254
|
else if (entry.isFile()) files.add(entry.name);
|
|
255
255
|
}
|
|
@@ -1124,7 +1124,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
|
|
|
1124
1124
|
var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
|
|
1125
1125
|
var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
|
|
1126
1126
|
var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
|
|
1127
|
-
|
|
1127
|
+
function quotedValueFor(delimiterGroup) {
|
|
1128
|
+
return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
|
|
1129
|
+
}
|
|
1130
|
+
var QUOTED_VALUE = quotedValueFor(1);
|
|
1128
1131
|
var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
|
|
1129
1132
|
var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
|
|
1130
1133
|
var DEFAULT_SECRET_PATTERNS = [
|
|
@@ -1278,7 +1281,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
1278
1281
|
// consumes the flag so the match is the credential alone.
|
|
1279
1282
|
// - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
|
|
1280
1283
|
rule: "uri-credentials",
|
|
1281
|
-
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[
|
|
1284
|
+
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%._=~-])/
|
|
1282
1285
|
},
|
|
1283
1286
|
{
|
|
1284
1287
|
// The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
|
|
@@ -1390,7 +1393,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
1390
1393
|
// rendering of textual userinfo mixes cases, while the prose the earlier rules were
|
|
1391
1394
|
// protecting (`Bearer authentication`) is a lowercase word.
|
|
1392
1395
|
rule: "authorization-header",
|
|
1393
|
-
pattern: /(?<=
|
|
1396
|
+
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_.+/=-])/
|
|
1394
1397
|
},
|
|
1395
1398
|
{
|
|
1396
1399
|
// Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
|
|
@@ -1417,7 +1420,9 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
1417
1420
|
// between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
|
|
1418
1421
|
rule: "interpolation-fallback-secret",
|
|
1419
1422
|
pattern: new RegExp(
|
|
1420
|
-
|
|
1423
|
+
// The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
|
|
1424
|
+
// and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
|
|
1425
|
+
`(?:["']${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})\\}["'\`]?`,
|
|
1421
1426
|
"i"
|
|
1422
1427
|
),
|
|
1423
1428
|
valueGroup: 1
|
|
@@ -1466,19 +1471,15 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
1466
1471
|
if (pattern instanceof RegExp) {
|
|
1467
1472
|
const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
|
|
1468
1473
|
if (valueGroup !== void 0) flags.add("d");
|
|
1469
|
-
return
|
|
1470
|
-
rule,
|
|
1471
|
-
pattern: new RegExp(pattern.source, [...flags].join("")),
|
|
1472
|
-
...valueGroup === void 0 ? {} : { valueGroup }
|
|
1473
|
-
};
|
|
1474
|
+
return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
|
|
1474
1475
|
}
|
|
1475
1476
|
if (typeof pattern === "string") {
|
|
1476
1477
|
try {
|
|
1477
|
-
return
|
|
1478
|
+
return checkedPattern(
|
|
1478
1479
|
rule,
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1480
|
+
new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
|
|
1481
|
+
valueGroup
|
|
1482
|
+
);
|
|
1482
1483
|
} catch (err) {
|
|
1483
1484
|
throw new Error(
|
|
1484
1485
|
`Invalid regular expression for secret rule "${rule}": ${err.message}`
|
|
@@ -1489,6 +1490,19 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
1489
1490
|
`Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
|
|
1490
1491
|
);
|
|
1491
1492
|
}
|
|
1493
|
+
function checkedPattern(rule, compiled, valueGroup) {
|
|
1494
|
+
const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
|
|
1495
|
+
if (stateless.test("")) {
|
|
1496
|
+
throw new Error(
|
|
1497
|
+
`Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
|
|
1498
|
+
);
|
|
1499
|
+
}
|
|
1500
|
+
return {
|
|
1501
|
+
rule,
|
|
1502
|
+
pattern: compiled,
|
|
1503
|
+
...valueGroup === void 0 ? {} : { valueGroup }
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1492
1506
|
function compileSecretRules(rules) {
|
|
1493
1507
|
if (!Array.isArray(rules)) {
|
|
1494
1508
|
throw new Error(
|
|
@@ -1545,6 +1559,193 @@ function toGlobal(rule) {
|
|
|
1545
1559
|
}
|
|
1546
1560
|
var LINE_BREAK = /(\r\n|\n|\r)/;
|
|
1547
1561
|
var LINE_TERMINATOR = /\r\n|\n|\r/g;
|
|
1562
|
+
function isOpeningQuote(line, index) {
|
|
1563
|
+
const code = line.charCodeAt(index);
|
|
1564
|
+
if (code === 96) return true;
|
|
1565
|
+
if (code !== 34 && code !== 39) return false;
|
|
1566
|
+
return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
|
|
1567
|
+
}
|
|
1568
|
+
function quoteStates(line) {
|
|
1569
|
+
const states = new Uint8Array(line.length + 1);
|
|
1570
|
+
let quote = 0;
|
|
1571
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
1572
|
+
states[index] = quote;
|
|
1573
|
+
const code = line.charCodeAt(index);
|
|
1574
|
+
if (quote === 0) {
|
|
1575
|
+
if (isOpeningQuote(line, index)) quote = code;
|
|
1576
|
+
} else if (code === 92) {
|
|
1577
|
+
if (index + 1 < line.length) {
|
|
1578
|
+
index += 1;
|
|
1579
|
+
states[index] = quote;
|
|
1580
|
+
}
|
|
1581
|
+
} else if (code === quote) {
|
|
1582
|
+
quote = 0;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
states[line.length] = quote;
|
|
1586
|
+
return states;
|
|
1587
|
+
}
|
|
1588
|
+
function quoteStateFor(line, context) {
|
|
1589
|
+
if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
|
|
1590
|
+
return context.quoteAt;
|
|
1591
|
+
}
|
|
1592
|
+
function quoteStateAfter(text2, quote, end = text2.length) {
|
|
1593
|
+
for (let index = 0; index < end; index += 1) {
|
|
1594
|
+
const code = text2.charCodeAt(index);
|
|
1595
|
+
if (quote === 0) {
|
|
1596
|
+
if (isOpeningQuote(text2, index)) quote = code;
|
|
1597
|
+
} else if (code === 92) {
|
|
1598
|
+
index += 1;
|
|
1599
|
+
} else if (code === quote) {
|
|
1600
|
+
quote = 0;
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
return quote;
|
|
1604
|
+
}
|
|
1605
|
+
function commentStartFor(line, context) {
|
|
1606
|
+
if (context.commentStart !== void 0) return context.commentStart;
|
|
1607
|
+
const quotes = quoteStateFor(line, context);
|
|
1608
|
+
let start = line.length;
|
|
1609
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
1610
|
+
if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
|
|
1611
|
+
if (index === 0 || /\s/.test(line[index - 1])) {
|
|
1612
|
+
start = index;
|
|
1613
|
+
break;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
context.commentStart = start;
|
|
1617
|
+
return start;
|
|
1618
|
+
}
|
|
1619
|
+
function commandSeparatorsFor(line, context) {
|
|
1620
|
+
if (context.commandSeparators !== void 0) return context.commandSeparators;
|
|
1621
|
+
const quotes = quoteStateFor(line, context);
|
|
1622
|
+
const separators = [];
|
|
1623
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
1624
|
+
if (quotes[index] !== 0) continue;
|
|
1625
|
+
const ch = line[index];
|
|
1626
|
+
const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
|
|
1627
|
+
if (ch === "&" || ch === "|") {
|
|
1628
|
+
if (line[index + 1] === ch) {
|
|
1629
|
+
const after = index + 2;
|
|
1630
|
+
const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
|
|
1631
|
+
if (doubleSpaced) separators.push(index);
|
|
1632
|
+
index += 1;
|
|
1633
|
+
} else if (spaced) {
|
|
1634
|
+
separators.push(index);
|
|
1635
|
+
}
|
|
1636
|
+
} else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
|
|
1637
|
+
separators.push(index);
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
context.commandSeparators = separators;
|
|
1641
|
+
return separators;
|
|
1642
|
+
}
|
|
1643
|
+
function lineValueEnd(line, start, context) {
|
|
1644
|
+
const comment = commentStartFor(line, context);
|
|
1645
|
+
let end = comment > start ? comment : line.length;
|
|
1646
|
+
for (const separator of commandSeparatorsFor(line, context)) {
|
|
1647
|
+
if (separator > start && separator < end) {
|
|
1648
|
+
end = separator;
|
|
1649
|
+
break;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
while (end > start && /\s/.test(line[end - 1])) end -= 1;
|
|
1653
|
+
return end;
|
|
1654
|
+
}
|
|
1655
|
+
function hasStructuralQuote(line) {
|
|
1656
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
1657
|
+
const ch = line[index];
|
|
1658
|
+
if (ch !== '"' && ch !== "'" && ch !== "`") continue;
|
|
1659
|
+
if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
|
|
1660
|
+
let backslashes = 0;
|
|
1661
|
+
for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
|
|
1662
|
+
if (backslashes % 2 === 1) continue;
|
|
1663
|
+
let before = index - 1;
|
|
1664
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
1665
|
+
if (before < 0 || "+,=:([{".includes(line[before])) return true;
|
|
1666
|
+
}
|
|
1667
|
+
return false;
|
|
1668
|
+
}
|
|
1669
|
+
function maskRawPemLine(line) {
|
|
1670
|
+
if (line.trim() === "") return line;
|
|
1671
|
+
const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
|
|
1672
|
+
let rest = line.slice(leading.length);
|
|
1673
|
+
const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
|
|
1674
|
+
rest = rest.slice(0, rest.length - trailing.length);
|
|
1675
|
+
return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
|
|
1676
|
+
}
|
|
1677
|
+
function skeletonisePemLine(line, initialQuote) {
|
|
1678
|
+
const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
|
|
1679
|
+
const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
|
|
1680
|
+
if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
|
|
1681
|
+
let out = "";
|
|
1682
|
+
let quote = initialQuote;
|
|
1683
|
+
let masking = false;
|
|
1684
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
1685
|
+
const code = line.charCodeAt(index);
|
|
1686
|
+
if (quote === 0) {
|
|
1687
|
+
if (isOpeningQuote(line, index)) {
|
|
1688
|
+
quote = code;
|
|
1689
|
+
masking = false;
|
|
1690
|
+
}
|
|
1691
|
+
out += line[index];
|
|
1692
|
+
continue;
|
|
1693
|
+
}
|
|
1694
|
+
if (code === 92) {
|
|
1695
|
+
masking = false;
|
|
1696
|
+
out += line[index];
|
|
1697
|
+
if (index + 1 < line.length) {
|
|
1698
|
+
out += line[index + 1];
|
|
1699
|
+
index += 1;
|
|
1700
|
+
}
|
|
1701
|
+
continue;
|
|
1702
|
+
}
|
|
1703
|
+
if (code === quote) {
|
|
1704
|
+
masking = false;
|
|
1705
|
+
quote = 0;
|
|
1706
|
+
out += line[index];
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
if (!masking) {
|
|
1710
|
+
out += PEM_REDACTION_MARKER;
|
|
1711
|
+
masking = true;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
return { text: out, quote };
|
|
1715
|
+
}
|
|
1716
|
+
function lineSpanAt(text2, start, end) {
|
|
1717
|
+
let lineStart = start;
|
|
1718
|
+
while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
|
|
1719
|
+
lineStart -= 1;
|
|
1720
|
+
}
|
|
1721
|
+
let lineEnd = end;
|
|
1722
|
+
while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
|
|
1723
|
+
if (lineEnd < text2.length) {
|
|
1724
|
+
lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
|
|
1725
|
+
}
|
|
1726
|
+
return { start: lineStart, end: lineEnd };
|
|
1727
|
+
}
|
|
1728
|
+
function redactPemSpan(text2, matchStart, matchEnd) {
|
|
1729
|
+
const span = lineSpanAt(text2, matchStart, matchEnd);
|
|
1730
|
+
const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
|
|
1731
|
+
let quote = quoteStateAfter(text2, 0, matchStart);
|
|
1732
|
+
let cursor = span.start;
|
|
1733
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
1734
|
+
const line = segments[index];
|
|
1735
|
+
const lineStart = cursor;
|
|
1736
|
+
const lineEnd = lineStart + line.length;
|
|
1737
|
+
cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
|
|
1738
|
+
const from = Math.max(lineStart, matchStart);
|
|
1739
|
+
const to = Math.min(lineEnd, matchEnd);
|
|
1740
|
+
if (from >= to) continue;
|
|
1741
|
+
const localFrom = from - lineStart;
|
|
1742
|
+
const localTo = to - lineStart;
|
|
1743
|
+
const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
|
|
1744
|
+
segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
|
|
1745
|
+
quote = result.quote;
|
|
1746
|
+
}
|
|
1747
|
+
return { replacement: segments.join(""), start: span.start, end: span.end };
|
|
1748
|
+
}
|
|
1548
1749
|
var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
|
|
1549
1750
|
function compiledRuleFor(rule) {
|
|
1550
1751
|
let compiled = COMPILED_RULES.get(rule);
|
|
@@ -1559,22 +1760,30 @@ function compiledRuleFor(rule) {
|
|
|
1559
1760
|
return compiled;
|
|
1560
1761
|
}
|
|
1561
1762
|
function scanAndRedactSecrets(content, rules, filePath) {
|
|
1562
|
-
const
|
|
1763
|
+
const findingsByLine = /* @__PURE__ */ new Map();
|
|
1764
|
+
const recordFinding = (line, rulesForLine) => {
|
|
1765
|
+
let entry = findingsByLine.get(line);
|
|
1766
|
+
if (entry === void 0) {
|
|
1767
|
+
entry = /* @__PURE__ */ new Set();
|
|
1768
|
+
findingsByLine.set(line, entry);
|
|
1769
|
+
}
|
|
1770
|
+
for (const rule of rulesForLine) entry.add(rule);
|
|
1771
|
+
};
|
|
1563
1772
|
let redacted = content;
|
|
1564
1773
|
for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
|
|
1565
1774
|
blockPattern.lastIndex = 0;
|
|
1566
1775
|
let match;
|
|
1567
1776
|
while ((match = blockPattern.exec(redacted)) !== null) {
|
|
1568
1777
|
if (match[0].length === 0) {
|
|
1569
|
-
blockPattern.lastIndex
|
|
1778
|
+
blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
|
|
1570
1779
|
continue;
|
|
1571
1780
|
}
|
|
1572
|
-
const
|
|
1573
|
-
const line = (
|
|
1574
|
-
const
|
|
1575
|
-
|
|
1576
|
-
redacted =
|
|
1577
|
-
blockPattern.lastIndex =
|
|
1781
|
+
const matchEnd = match.index + match[0].length;
|
|
1782
|
+
const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
|
|
1783
|
+
const span = redactPemSpan(redacted, match.index, matchEnd);
|
|
1784
|
+
recordFinding(line, ["private-key-block"]);
|
|
1785
|
+
redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
|
|
1786
|
+
blockPattern.lastIndex = span.start + span.replacement.length;
|
|
1578
1787
|
}
|
|
1579
1788
|
}
|
|
1580
1789
|
const compiled = rules.map(compiledRuleFor);
|
|
@@ -1585,17 +1794,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
1585
1794
|
if (line.length > 0) {
|
|
1586
1795
|
const spans = [];
|
|
1587
1796
|
const matchedRules = /* @__PURE__ */ new Set();
|
|
1797
|
+
const context = {};
|
|
1588
1798
|
for (const { rule, pattern, valueGroup } of compiled) {
|
|
1589
1799
|
pattern.lastIndex = 0;
|
|
1590
1800
|
let match;
|
|
1591
1801
|
while ((match = pattern.exec(line)) !== null) {
|
|
1592
1802
|
if (match[0].length === 0) {
|
|
1593
|
-
pattern.lastIndex
|
|
1803
|
+
pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
|
|
1594
1804
|
continue;
|
|
1595
1805
|
}
|
|
1596
1806
|
const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
|
|
1807
|
+
const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
|
|
1808
|
+
if (isPlaceholderValue(candidate)) continue;
|
|
1809
|
+
if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
if (rule === "credential-assignment-weak" && group) {
|
|
1816
|
+
let before = match.index - 1;
|
|
1817
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
1818
|
+
if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
|
|
1819
|
+
const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
|
|
1820
|
+
if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
|
|
1821
|
+
continue;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1597
1824
|
if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
|
|
1598
|
-
if (
|
|
1825
|
+
if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
|
|
1599
1829
|
continue;
|
|
1600
1830
|
}
|
|
1601
1831
|
if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
|
|
@@ -1621,7 +1851,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
1621
1851
|
if (wholeValue) {
|
|
1622
1852
|
spans.push({
|
|
1623
1853
|
start: group[0],
|
|
1624
|
-
|
|
1854
|
+
// A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
|
|
1855
|
+
// stop at the first one and emit the rest beside the marker. Stop at the end of
|
|
1856
|
+
// the value, a trailing comment, or a shell operator instead. The rule's own end
|
|
1857
|
+
// is not used: the colon form's value pattern includes the spaces before a
|
|
1858
|
+
// trailing `# comment`, and masking them welds the comment to the marker.
|
|
1859
|
+
end: lineValueEnd(line, group[0], context),
|
|
1625
1860
|
rule
|
|
1626
1861
|
});
|
|
1627
1862
|
matchedRules.add(rule);
|
|
@@ -1634,14 +1869,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
1634
1869
|
matchedRules.add(rule);
|
|
1635
1870
|
}
|
|
1636
1871
|
}
|
|
1872
|
+
for (const span of concatenatedCredentialSpans(line)) {
|
|
1873
|
+
spans.push(span);
|
|
1874
|
+
matchedRules.add(span.rule);
|
|
1875
|
+
}
|
|
1637
1876
|
if (spans.length > 0) {
|
|
1638
|
-
|
|
1639
|
-
|
|
1877
|
+
const maskedLine = applySpans(line, spans);
|
|
1878
|
+
if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
|
|
1879
|
+
recordFinding(lineNumber, matchedRules);
|
|
1880
|
+
segments[index] = maskedLine;
|
|
1881
|
+
}
|
|
1640
1882
|
}
|
|
1641
1883
|
}
|
|
1642
1884
|
if (index + 1 < segments.length) lineNumber += 1;
|
|
1643
1885
|
}
|
|
1644
|
-
|
|
1886
|
+
let finalText = segments.join("");
|
|
1887
|
+
finalText = redactStructuredValues(finalText, filePath, recordFinding);
|
|
1888
|
+
finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
|
|
1889
|
+
const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
|
|
1890
|
+
rules: [...rulesForLine],
|
|
1891
|
+
line,
|
|
1892
|
+
path: filePath
|
|
1893
|
+
}));
|
|
1894
|
+
return { redacted: finalText, findings };
|
|
1895
|
+
}
|
|
1896
|
+
function advanceStringIndex(text2, index, unicode) {
|
|
1897
|
+
if (!unicode) return index + 1;
|
|
1898
|
+
const first = text2.charCodeAt(index);
|
|
1899
|
+
if (first >= 55296 && first <= 56319) {
|
|
1900
|
+
const second = text2.charCodeAt(index + 1);
|
|
1901
|
+
if (second >= 56320 && second <= 57343) return index + 2;
|
|
1902
|
+
}
|
|
1903
|
+
return index + 1;
|
|
1904
|
+
}
|
|
1905
|
+
var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
|
|
1906
|
+
var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
|
|
1907
|
+
function isStructuredFile(filePath) {
|
|
1908
|
+
if (filePath === void 0) return false;
|
|
1909
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
1910
|
+
if (STRUCTURED_FILE.test(normalised)) return true;
|
|
1911
|
+
return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
|
|
1912
|
+
}
|
|
1913
|
+
function isDockerfile(filePath) {
|
|
1914
|
+
if (filePath === void 0) return false;
|
|
1915
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
1916
|
+
return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
|
|
1917
|
+
normalised.slice(normalised.lastIndexOf("/") + 1)
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
function maskLineContent(line) {
|
|
1921
|
+
if (line.trim() === "") return line;
|
|
1922
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
1923
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
1924
|
+
}
|
|
1925
|
+
function maskValueLine(line) {
|
|
1926
|
+
if (line.trim() === "") return line;
|
|
1927
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
1928
|
+
const content = line.slice(indent.length);
|
|
1929
|
+
const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
|
|
1930
|
+
if (quoted !== null) {
|
|
1931
|
+
return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
|
|
1932
|
+
}
|
|
1933
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
1934
|
+
}
|
|
1935
|
+
var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
|
|
1936
|
+
var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
|
|
1937
|
+
function redactStructuredValues(text2, filePath, recordFinding) {
|
|
1938
|
+
if (!isStructuredFile(filePath)) return text2;
|
|
1939
|
+
const segments = text2.split(LINE_BREAK);
|
|
1940
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
1941
|
+
const line = segments[index];
|
|
1942
|
+
if (line === void 0 || line.length === 0) continue;
|
|
1943
|
+
const match = STRUCTURED_KEY.exec(line);
|
|
1944
|
+
if (match === null) continue;
|
|
1945
|
+
const key = match[2] ?? "";
|
|
1946
|
+
if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
|
|
1947
|
+
const baseIndent = (match[1] ?? "").length;
|
|
1948
|
+
const rest = (match[4] ?? "").trim();
|
|
1949
|
+
if (BLOCK_SCALAR.test(rest)) {
|
|
1950
|
+
let cursor2 = index + 2;
|
|
1951
|
+
let masked2 = false;
|
|
1952
|
+
while (cursor2 < segments.length) {
|
|
1953
|
+
const body = segments[cursor2] ?? "";
|
|
1954
|
+
if (body.trim() !== "") {
|
|
1955
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
1956
|
+
if (indent <= baseIndent) break;
|
|
1957
|
+
segments[cursor2] = maskLineContent(body);
|
|
1958
|
+
masked2 = true;
|
|
1959
|
+
}
|
|
1960
|
+
cursor2 += 2;
|
|
1961
|
+
}
|
|
1962
|
+
if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
if (rest !== "") continue;
|
|
1966
|
+
let cursor = index + 2;
|
|
1967
|
+
while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
|
|
1968
|
+
const firstValue = segments[cursor];
|
|
1969
|
+
if (firstValue === void 0) continue;
|
|
1970
|
+
const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
|
|
1971
|
+
if (valueIndent <= baseIndent) continue;
|
|
1972
|
+
let masked = false;
|
|
1973
|
+
while (cursor < segments.length) {
|
|
1974
|
+
const body = segments[cursor] ?? "";
|
|
1975
|
+
if (body.trim() !== "") {
|
|
1976
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
1977
|
+
if (indent < valueIndent) break;
|
|
1978
|
+
segments[cursor] = maskValueLine(body);
|
|
1979
|
+
masked = true;
|
|
1980
|
+
}
|
|
1981
|
+
cursor += 2;
|
|
1982
|
+
}
|
|
1983
|
+
if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
|
|
1984
|
+
}
|
|
1985
|
+
return segments.join("");
|
|
1986
|
+
}
|
|
1987
|
+
var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
|
|
1988
|
+
function redactDockerfileEnv(text2, filePath, recordFinding) {
|
|
1989
|
+
if (!isDockerfile(filePath)) return text2;
|
|
1990
|
+
const segments = text2.split(LINE_BREAK);
|
|
1991
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
1992
|
+
const line = segments[index];
|
|
1993
|
+
if (line === void 0) continue;
|
|
1994
|
+
const match = DOCKERFILE_ENV.exec(line);
|
|
1995
|
+
if (match === null) continue;
|
|
1996
|
+
if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
|
|
1997
|
+
const value = match[4] ?? "";
|
|
1998
|
+
if (value.startsWith("=")) continue;
|
|
1999
|
+
segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
|
|
2000
|
+
recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
|
|
2001
|
+
}
|
|
2002
|
+
return segments.join("");
|
|
2003
|
+
}
|
|
2004
|
+
var CONCATENATED_CREDENTIAL = new RegExp(
|
|
2005
|
+
"([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",
|
|
2006
|
+
"gid"
|
|
2007
|
+
);
|
|
2008
|
+
function concatenatedCredentialSpans(line) {
|
|
2009
|
+
const spans = [];
|
|
2010
|
+
CONCATENATED_CREDENTIAL.lastIndex = 0;
|
|
2011
|
+
let match;
|
|
2012
|
+
while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
|
|
2013
|
+
const group = match.indices?.[4];
|
|
2014
|
+
if (group !== void 0) {
|
|
2015
|
+
spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return spans;
|
|
1645
2019
|
}
|
|
1646
2020
|
var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
|
|
1647
2021
|
var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
|
|
@@ -1659,13 +2033,20 @@ function expandOverToken(line, start, end) {
|
|
|
1659
2033
|
while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
|
|
1660
2034
|
return { start: left, end: right };
|
|
1661
2035
|
}
|
|
1662
|
-
function startsInsideStringLiteral(line, matchIndex, valueStart) {
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
if (before !== '"' && before !== "'" && before !== "`") return false;
|
|
2036
|
+
function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
|
|
2037
|
+
const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
|
|
2038
|
+
if (quote === 0) return false;
|
|
2039
|
+
if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
|
|
1667
2040
|
if (valueStart === void 0) return true;
|
|
1668
|
-
|
|
2041
|
+
for (let index = matchIndex; index < valueStart; index += 1) {
|
|
2042
|
+
const code = line.charCodeAt(index);
|
|
2043
|
+
if (code === 92) {
|
|
2044
|
+
index += 1;
|
|
2045
|
+
} else if (code === quote) {
|
|
2046
|
+
return true;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
return false;
|
|
1669
2050
|
}
|
|
1670
2051
|
function isTemplateInterpolation(line, start, end) {
|
|
1671
2052
|
if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
|
|
@@ -1693,6 +2074,40 @@ function isSelfNamingConstant(line, start, end) {
|
|
|
1693
2074
|
}
|
|
1694
2075
|
return line.endsWith(value, index);
|
|
1695
2076
|
}
|
|
2077
|
+
var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
|
|
2078
|
+
function isSourceCodeFile(filePath) {
|
|
2079
|
+
return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
|
|
2080
|
+
}
|
|
2081
|
+
var PLACEHOLDER_PATTERNS = [
|
|
2082
|
+
/^<[^>]*>?$/,
|
|
2083
|
+
/^\.{3,}$/,
|
|
2084
|
+
/^(?:x{4,}|X{4,}|\*{3,})$/,
|
|
2085
|
+
/^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
|
|
2086
|
+
/^your[-_ ].*$/i,
|
|
2087
|
+
/^(?:example|sample)(?:[-_ ].*)?$/i
|
|
2088
|
+
];
|
|
2089
|
+
function isPlaceholderValue(value) {
|
|
2090
|
+
const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
|
|
2091
|
+
if (trimmed.length === 0) return false;
|
|
2092
|
+
if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
|
|
2093
|
+
return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
|
|
2094
|
+
}
|
|
2095
|
+
function quotesAreBalanced(text2) {
|
|
2096
|
+
let single = 0;
|
|
2097
|
+
let double = 0;
|
|
2098
|
+
let backtick = 0;
|
|
2099
|
+
for (let index = 0; index < text2.length; index += 1) {
|
|
2100
|
+
const char = text2[index];
|
|
2101
|
+
if (char === "\\") {
|
|
2102
|
+
index += 1;
|
|
2103
|
+
continue;
|
|
2104
|
+
}
|
|
2105
|
+
if (char === '"') double += 1;
|
|
2106
|
+
else if (char === "'") single += 1;
|
|
2107
|
+
else if (char === "`") backtick += 1;
|
|
2108
|
+
}
|
|
2109
|
+
return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
|
|
2110
|
+
}
|
|
1696
2111
|
function assignmentAround(line, valueStart) {
|
|
1697
2112
|
let index = valueStart;
|
|
1698
2113
|
while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
|
|
@@ -1762,6 +2177,16 @@ function applySpans(line, spans) {
|
|
|
1762
2177
|
return out;
|
|
1763
2178
|
}
|
|
1764
2179
|
|
|
2180
|
+
// src/version.ts
|
|
2181
|
+
var GENERATOR_NAME = "codebase-snapshot";
|
|
2182
|
+
var GENERATOR_VERSION = "0.9.18";
|
|
2183
|
+
var SCHEMA_VERSION = "3.0.0";
|
|
2184
|
+
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
2185
|
+
function isOurGeneratorName(name) {
|
|
2186
|
+
if (typeof name !== "string") return false;
|
|
2187
|
+
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
2188
|
+
}
|
|
2189
|
+
|
|
1765
2190
|
// src/scanner/files.ts
|
|
1766
2191
|
function isDiscoveryMode(value) {
|
|
1767
2192
|
return value === "auto" || value === "git" || value === "walk";
|
|
@@ -1771,7 +2196,7 @@ var PRESET_IGNORES = new Set(
|
|
|
1771
2196
|
);
|
|
1772
2197
|
function readLinkTarget(linkPath, fallback) {
|
|
1773
2198
|
try {
|
|
1774
|
-
return
|
|
2199
|
+
return fs15__namespace.readlinkSync(linkPath);
|
|
1775
2200
|
} catch {
|
|
1776
2201
|
return fallback;
|
|
1777
2202
|
}
|
|
@@ -1786,8 +2211,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
|
|
|
1786
2211
|
};
|
|
1787
2212
|
}
|
|
1788
2213
|
function isInside(root, candidate) {
|
|
1789
|
-
const
|
|
1790
|
-
return
|
|
2214
|
+
const relative14 = path16__namespace.relative(root, candidate);
|
|
2215
|
+
return relative14 === "" || !relative14.startsWith(`..${path16__namespace.sep}`) && relative14 !== ".." && !path16__namespace.isAbsolute(relative14);
|
|
1791
2216
|
}
|
|
1792
2217
|
var GIT_OUTPUT_LIMIT = 68157440;
|
|
1793
2218
|
function getGitInfo(cwd, fallbackBranch = "main") {
|
|
@@ -1848,10 +2273,10 @@ var DEFAULT_IGNORED_FILES = [
|
|
|
1848
2273
|
"bun.lockb",
|
|
1849
2274
|
"composer.lock"
|
|
1850
2275
|
];
|
|
1851
|
-
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;
|
|
1852
|
-
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
|
|
2276
|
+
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;
|
|
2277
|
+
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
|
|
1853
2278
|
var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
|
|
1854
|
-
var TEMPLATE_SUFFIX =
|
|
2279
|
+
var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
|
|
1855
2280
|
var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
|
|
1856
2281
|
function normaliseName(name) {
|
|
1857
2282
|
let normalised = name.trim().replace(/[. ]+$/, "");
|
|
@@ -1867,12 +2292,16 @@ function isSensitivePath(relativePath) {
|
|
|
1867
2292
|
const posixPath = relativePath.replace(/\\/g, "/");
|
|
1868
2293
|
const raw = posixPath.split("/").pop() ?? posixPath;
|
|
1869
2294
|
const base = normaliseName(raw);
|
|
1870
|
-
if (
|
|
1871
|
-
const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
|
|
1872
|
-
if (matchesSensitiveList(posixPath, stripped)) return false;
|
|
1873
|
-
}
|
|
2295
|
+
if (templateOfCredentialFile(posixPath, base)) return false;
|
|
1874
2296
|
return matchesSensitiveList(posixPath, base);
|
|
1875
2297
|
}
|
|
2298
|
+
function templateOfCredentialFile(posixPath, base) {
|
|
2299
|
+
const match = TEMPLATE_SUFFIX.exec(base);
|
|
2300
|
+
if (match === null) return null;
|
|
2301
|
+
const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
|
|
2302
|
+
if (SENSITIVE_EXT.test(stripped)) return null;
|
|
2303
|
+
return matchesSensitiveList(posixPath, stripped) ? stripped : null;
|
|
2304
|
+
}
|
|
1876
2305
|
var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
|
|
1877
2306
|
var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
1878
2307
|
var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
@@ -1904,7 +2333,7 @@ function findSecretInPath(relativePath, extraRules) {
|
|
|
1904
2333
|
let match;
|
|
1905
2334
|
while ((match = scan.exec(posixPath)) !== null) {
|
|
1906
2335
|
if (match[0].length === 0) {
|
|
1907
|
-
scan.lastIndex
|
|
2336
|
+
scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
|
|
1908
2337
|
continue;
|
|
1909
2338
|
}
|
|
1910
2339
|
spans.push({ start: match.index, end: match.index + match[0].length });
|
|
@@ -1965,11 +2394,14 @@ function globBodyToRegExp(body, allowBraces) {
|
|
|
1965
2394
|
if (char === "*") {
|
|
1966
2395
|
if (body[i + 1] === "*") {
|
|
1967
2396
|
i += 1;
|
|
1968
|
-
|
|
2397
|
+
const startsSegment = i - 2 < 0 || body[i - 2] === "/";
|
|
2398
|
+
if (startsSegment && body[i + 1] === "/") {
|
|
1969
2399
|
i += 1;
|
|
1970
|
-
out += "(
|
|
1971
|
-
} else {
|
|
2400
|
+
out += "(?:[^/]+/)*";
|
|
2401
|
+
} else if (startsSegment && i + 1 === body.length) {
|
|
1972
2402
|
out += ".*";
|
|
2403
|
+
} else {
|
|
2404
|
+
out += "[^/]*";
|
|
1973
2405
|
}
|
|
1974
2406
|
} else {
|
|
1975
2407
|
out += "[^/]*";
|
|
@@ -2041,7 +2473,7 @@ function readGitignoreRules(dir) {
|
|
|
2041
2473
|
const gitignorePath2 = path16__namespace.join(dir, ".gitignore");
|
|
2042
2474
|
let raw;
|
|
2043
2475
|
try {
|
|
2044
|
-
raw =
|
|
2476
|
+
raw = fs15__namespace.readFileSync(gitignorePath2, "utf8");
|
|
2045
2477
|
} catch {
|
|
2046
2478
|
return [];
|
|
2047
2479
|
}
|
|
@@ -2214,10 +2646,49 @@ function listIgnoredPaths(cwd) {
|
|
|
2214
2646
|
}
|
|
2215
2647
|
function hasSnapshotMarker(target) {
|
|
2216
2648
|
try {
|
|
2217
|
-
return
|
|
2649
|
+
return fs15__namespace.statSync(target).isDirectory() && fs15__namespace.existsSync(path16__namespace.join(target, ".codebase-snapshot"));
|
|
2650
|
+
} catch {
|
|
2651
|
+
return false;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
|
|
2655
|
+
function isToolOwnedDirectory2(dir) {
|
|
2656
|
+
let raw;
|
|
2657
|
+
try {
|
|
2658
|
+
raw = fs15__namespace.readFileSync(path16__namespace.join(dir, ".codebase-snapshot"), "utf8");
|
|
2659
|
+
} catch {
|
|
2660
|
+
return false;
|
|
2661
|
+
}
|
|
2662
|
+
let parsed;
|
|
2663
|
+
try {
|
|
2664
|
+
parsed = JSON.parse(raw);
|
|
2665
|
+
} catch {
|
|
2666
|
+
return false;
|
|
2667
|
+
}
|
|
2668
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
2669
|
+
const marker2 = parsed;
|
|
2670
|
+
if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
|
|
2671
|
+
return false;
|
|
2672
|
+
}
|
|
2673
|
+
const accounted = /* @__PURE__ */ new Set();
|
|
2674
|
+
for (const item of marker2.files) {
|
|
2675
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
|
|
2676
|
+
const entry = item.path;
|
|
2677
|
+
if (typeof entry !== "string" || entry.length === 0) return false;
|
|
2678
|
+
const parts = entry.split("/");
|
|
2679
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
2680
|
+
accounted.add(parts.slice(0, depth).join("/"));
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
let entries;
|
|
2684
|
+
try {
|
|
2685
|
+
entries = fs15__namespace.readdirSync(dir);
|
|
2218
2686
|
} catch {
|
|
2219
2687
|
return false;
|
|
2220
2688
|
}
|
|
2689
|
+
return entries.every(
|
|
2690
|
+
(entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
|
|
2691
|
+
);
|
|
2221
2692
|
}
|
|
2222
2693
|
function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
2223
2694
|
const markers = /* @__PURE__ */ new Map();
|
|
@@ -2228,7 +2699,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
|
2228
2699
|
const prefix = parts.slice(0, depth).join("/");
|
|
2229
2700
|
let hasMarker = markers.get(prefix);
|
|
2230
2701
|
if (hasMarker === void 0) {
|
|
2231
|
-
hasMarker =
|
|
2702
|
+
hasMarker = isToolOwnedDirectory2(path16__namespace.join(cwd, prefix));
|
|
2232
2703
|
markers.set(prefix, hasMarker);
|
|
2233
2704
|
}
|
|
2234
2705
|
if (hasMarker) return true;
|
|
@@ -2243,7 +2714,7 @@ function makeLinkProbe() {
|
|
|
2243
2714
|
let known = cache.get(absolutePath);
|
|
2244
2715
|
if (known === void 0) {
|
|
2245
2716
|
try {
|
|
2246
|
-
known =
|
|
2717
|
+
known = fs15__namespace.lstatSync(absolutePath).isSymbolicLink();
|
|
2247
2718
|
} catch {
|
|
2248
2719
|
known = false;
|
|
2249
2720
|
}
|
|
@@ -2256,7 +2727,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
2256
2727
|
const isLink = makeLinkProbe();
|
|
2257
2728
|
let rootReal = cwd;
|
|
2258
2729
|
try {
|
|
2259
|
-
rootReal =
|
|
2730
|
+
rootReal = fs15__namespace.realpathSync(cwd);
|
|
2260
2731
|
} catch {
|
|
2261
2732
|
}
|
|
2262
2733
|
const reported = /* @__PURE__ */ new Set();
|
|
@@ -2284,7 +2755,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
2284
2755
|
const rawTarget = readLinkTarget(absolute, absolute);
|
|
2285
2756
|
let targetReal = null;
|
|
2286
2757
|
try {
|
|
2287
|
-
targetReal =
|
|
2758
|
+
targetReal = fs15__namespace.realpathSync(absolute);
|
|
2288
2759
|
} catch {
|
|
2289
2760
|
targetReal = null;
|
|
2290
2761
|
}
|
|
@@ -2302,7 +2773,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
2302
2773
|
}
|
|
2303
2774
|
let stats = null;
|
|
2304
2775
|
try {
|
|
2305
|
-
stats =
|
|
2776
|
+
stats = fs15__namespace.statSync(absolute);
|
|
2306
2777
|
} catch {
|
|
2307
2778
|
stats = null;
|
|
2308
2779
|
}
|
|
@@ -2390,7 +2861,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
2390
2861
|
"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."
|
|
2391
2862
|
);
|
|
2392
2863
|
}
|
|
2393
|
-
if (
|
|
2864
|
+
if (fs15__namespace.existsSync(path16__namespace.join(cwd, ".git"))) {
|
|
2394
2865
|
throw new Error(
|
|
2395
2866
|
"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."
|
|
2396
2867
|
);
|
|
@@ -2400,6 +2871,15 @@ function collectFiles(cwd, options = {}) {
|
|
|
2400
2871
|
for (const record of walked.skipped) skipped.push(record);
|
|
2401
2872
|
}
|
|
2402
2873
|
}
|
|
2874
|
+
const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
|
|
2875
|
+
if (extraPaths.length > 0) {
|
|
2876
|
+
const known = new Set(candidates);
|
|
2877
|
+
for (const extra of extraPaths) {
|
|
2878
|
+
if (extra.length === 0 || known.has(extra)) continue;
|
|
2879
|
+
known.add(extra);
|
|
2880
|
+
candidates.push(extra);
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2403
2883
|
const files = candidates.filter((file) => {
|
|
2404
2884
|
if (isToolOwned(file)) return false;
|
|
2405
2885
|
const ignored = defaultIgnoreReason(file, toolDirNames);
|
|
@@ -2449,7 +2929,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
2449
2929
|
}
|
|
2450
2930
|
function rootRealFor(root) {
|
|
2451
2931
|
try {
|
|
2452
|
-
return
|
|
2932
|
+
return fs15__namespace.realpathSync(root);
|
|
2453
2933
|
} catch {
|
|
2454
2934
|
return root;
|
|
2455
2935
|
}
|
|
@@ -2469,7 +2949,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
2469
2949
|
];
|
|
2470
2950
|
let entries;
|
|
2471
2951
|
try {
|
|
2472
|
-
entries =
|
|
2952
|
+
entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
|
|
2473
2953
|
} catch {
|
|
2474
2954
|
results.skipped.push({
|
|
2475
2955
|
path: relativeToBase(current),
|
|
@@ -2525,14 +3005,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
2525
3005
|
if (entry.isSymbolicLink()) {
|
|
2526
3006
|
let targetReal;
|
|
2527
3007
|
try {
|
|
2528
|
-
targetReal =
|
|
3008
|
+
targetReal = fs15__namespace.realpathSync(fullPath);
|
|
2529
3009
|
} catch {
|
|
2530
3010
|
results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
|
|
2531
3011
|
continue;
|
|
2532
3012
|
}
|
|
2533
3013
|
let stats;
|
|
2534
3014
|
try {
|
|
2535
|
-
stats =
|
|
3015
|
+
stats = fs15__namespace.statSync(fullPath);
|
|
2536
3016
|
} catch {
|
|
2537
3017
|
results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
|
|
2538
3018
|
continue;
|
|
@@ -2562,6 +3042,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
2562
3042
|
});
|
|
2563
3043
|
continue;
|
|
2564
3044
|
}
|
|
3045
|
+
const targetRelative = path16__namespace.relative(rootReal, targetReal).split(path16__namespace.sep).join("/");
|
|
3046
|
+
if (isSensitivePath(targetRelative)) {
|
|
3047
|
+
results.skipped.push({
|
|
3048
|
+
path: relPath,
|
|
3049
|
+
reason: "sensitive-file",
|
|
3050
|
+
detail: "link target is a credential-bearing file; not followed"
|
|
3051
|
+
});
|
|
3052
|
+
continue;
|
|
3053
|
+
}
|
|
2565
3054
|
isDirectory = false;
|
|
2566
3055
|
isFile = true;
|
|
2567
3056
|
}
|
|
@@ -2610,12 +3099,19 @@ var CONFIG_FILENAMES = [
|
|
|
2610
3099
|
function findConfigFile(cwd) {
|
|
2611
3100
|
for (const filename of CONFIG_FILENAMES) {
|
|
2612
3101
|
const fullPath = path16__namespace.join(cwd, filename);
|
|
2613
|
-
|
|
3102
|
+
let stats = null;
|
|
3103
|
+
try {
|
|
3104
|
+
stats = fs15__namespace.statSync(fullPath);
|
|
3105
|
+
} catch {
|
|
3106
|
+
if (fs15__namespace.existsSync(fullPath)) return fullPath;
|
|
3107
|
+
continue;
|
|
3108
|
+
}
|
|
3109
|
+
if (stats.isFile()) return fullPath;
|
|
2614
3110
|
}
|
|
2615
3111
|
const pkgJsonPath = path16__namespace.join(cwd, "package.json");
|
|
2616
|
-
if (!
|
|
3112
|
+
if (!fs15__namespace.existsSync(pkgJsonPath)) return null;
|
|
2617
3113
|
try {
|
|
2618
|
-
const parsed = JSON.parse(stripJsonComments(
|
|
3114
|
+
const parsed = JSON.parse(stripJsonComments(fs15__namespace.readFileSync(pkgJsonPath, "utf8")));
|
|
2619
3115
|
const snapshot = parsed?.snapshot;
|
|
2620
3116
|
return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
|
|
2621
3117
|
} catch {
|
|
@@ -2876,17 +3372,34 @@ function readConfigExport(exported, file) {
|
|
|
2876
3372
|
assertKnownConfigKeys(exported, file);
|
|
2877
3373
|
return exported;
|
|
2878
3374
|
}
|
|
2879
|
-
var
|
|
3375
|
+
var lastModuleConfig = null;
|
|
3376
|
+
function moduleConfigKey(fullPath) {
|
|
3377
|
+
try {
|
|
3378
|
+
return crypto3.createHash("sha256").update(fs15__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
|
|
3379
|
+
} catch {
|
|
3380
|
+
try {
|
|
3381
|
+
const stats = fs15__namespace.statSync(fullPath);
|
|
3382
|
+
return `stat-${stats.mtimeMs}-${stats.size}`;
|
|
3383
|
+
} catch {
|
|
3384
|
+
return "unreadable";
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
}
|
|
2880
3388
|
async function importConfigModule(fullPath) {
|
|
3389
|
+
const key = moduleConfigKey(fullPath);
|
|
3390
|
+
if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
|
|
3391
|
+
return lastModuleConfig.exports;
|
|
3392
|
+
}
|
|
2881
3393
|
try {
|
|
2882
3394
|
const requireFromConfig = module$1.createRequire(fullPath);
|
|
2883
3395
|
delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
|
|
2884
3396
|
} catch {
|
|
2885
3397
|
}
|
|
2886
3398
|
const url$1 = url.pathToFileURL(fullPath);
|
|
2887
|
-
|
|
2888
|
-
url$1.
|
|
2889
|
-
|
|
3399
|
+
url$1.searchParams.set("codebaseSnapshotLoad", key);
|
|
3400
|
+
const loaded = await import(url$1.href);
|
|
3401
|
+
lastModuleConfig = { path: fullPath, key, exports: loaded };
|
|
3402
|
+
return loaded;
|
|
2890
3403
|
}
|
|
2891
3404
|
function attachConfigDir(config, filePath) {
|
|
2892
3405
|
if (typeof config === "object" && config !== null) {
|
|
@@ -2898,15 +3411,25 @@ function attachConfigDir(config, filePath) {
|
|
|
2898
3411
|
}
|
|
2899
3412
|
return config;
|
|
2900
3413
|
}
|
|
2901
|
-
async function loadConfigFileDetailed(cwd) {
|
|
3414
|
+
async function loadConfigFileDetailed(cwd, options = {}) {
|
|
2902
3415
|
const warnings = [];
|
|
2903
3416
|
const errors = [];
|
|
3417
|
+
const configDirectories = [];
|
|
2904
3418
|
for (const filename of CONFIG_FILENAMES) {
|
|
2905
3419
|
const fullPath = path16__namespace.join(cwd, filename);
|
|
2906
|
-
|
|
3420
|
+
let candidateStats = null;
|
|
3421
|
+
try {
|
|
3422
|
+
candidateStats = fs15__namespace.statSync(fullPath);
|
|
3423
|
+
} catch {
|
|
3424
|
+
if (!fs15__namespace.existsSync(fullPath)) continue;
|
|
3425
|
+
}
|
|
3426
|
+
if (candidateStats !== null && !candidateStats.isFile()) {
|
|
3427
|
+
configDirectories.push(fullPath);
|
|
3428
|
+
continue;
|
|
3429
|
+
}
|
|
2907
3430
|
if (filename.endsWith(".json") || filename === ".snapshotrc") {
|
|
2908
3431
|
try {
|
|
2909
|
-
const config = parseJsonish(
|
|
3432
|
+
const config = parseJsonish(fs15__namespace.readFileSync(fullPath, "utf8"), fullPath);
|
|
2910
3433
|
if (config === null || typeof config !== "object" || Array.isArray(config)) {
|
|
2911
3434
|
throw new Error(
|
|
2912
3435
|
`${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
|
|
@@ -2922,6 +3445,12 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
2922
3445
|
continue;
|
|
2923
3446
|
}
|
|
2924
3447
|
}
|
|
3448
|
+
if (options.allowExecutableConfig === false) {
|
|
3449
|
+
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.`;
|
|
3450
|
+
warnings.push(message);
|
|
3451
|
+
errors.push(message);
|
|
3452
|
+
continue;
|
|
3453
|
+
}
|
|
2925
3454
|
if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
|
|
2926
3455
|
warnings.push(
|
|
2927
3456
|
`${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
|
|
@@ -2941,9 +3470,9 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
2941
3470
|
}
|
|
2942
3471
|
}
|
|
2943
3472
|
const pkgJsonPath = path16__namespace.join(cwd, "package.json");
|
|
2944
|
-
if (
|
|
3473
|
+
if (fs15__namespace.existsSync(pkgJsonPath)) {
|
|
2945
3474
|
try {
|
|
2946
|
-
const parsed = parseJsonish(
|
|
3475
|
+
const parsed = parseJsonish(fs15__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
|
|
2947
3476
|
const snapshotKey = parsed.snapshot;
|
|
2948
3477
|
if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
|
|
2949
3478
|
assertKnownConfigKeys(
|
|
@@ -2969,6 +3498,11 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
2969
3498
|
errors.push(message);
|
|
2970
3499
|
}
|
|
2971
3500
|
}
|
|
3501
|
+
if (configDirectories.length > 0) {
|
|
3502
|
+
warnings.push(
|
|
3503
|
+
`${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
|
|
3504
|
+
);
|
|
3505
|
+
}
|
|
2972
3506
|
return { config: null, file: null, warnings, errors };
|
|
2973
3507
|
}
|
|
2974
3508
|
var MIN_MAX_PART_BYTES = 4096;
|
|
@@ -3137,11 +3671,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
|
|
|
3137
3671
|
const patterns = [];
|
|
3138
3672
|
for (const dir of [outDir, tmpDir]) {
|
|
3139
3673
|
const absolute = path16__namespace.resolve(cwd, dir);
|
|
3140
|
-
const
|
|
3141
|
-
if (!
|
|
3674
|
+
const relative14 = path16__namespace.relative(cwd, absolute);
|
|
3675
|
+
if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
|
|
3142
3676
|
continue;
|
|
3143
3677
|
}
|
|
3144
|
-
patterns.push(`${
|
|
3678
|
+
patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
|
|
3145
3679
|
}
|
|
3146
3680
|
return patterns;
|
|
3147
3681
|
}
|
|
@@ -3272,10 +3806,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
|
|
|
3272
3806
|
}
|
|
3273
3807
|
const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
|
|
3274
3808
|
const resolved = path16__namespace.resolve(candidate);
|
|
3275
|
-
if (!
|
|
3809
|
+
if (!fs15__namespace.existsSync(resolved)) {
|
|
3276
3810
|
throw new Error(`Working directory does not exist: ${resolved}`);
|
|
3277
3811
|
}
|
|
3278
|
-
if (!
|
|
3812
|
+
if (!fs15__namespace.statSync(resolved).isDirectory()) {
|
|
3279
3813
|
throw new Error(`Working directory is not a directory: ${resolved}`);
|
|
3280
3814
|
}
|
|
3281
3815
|
return resolved;
|
|
@@ -3525,6 +4059,13 @@ function configDigest(config) {
|
|
|
3525
4059
|
// moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
|
|
3526
4060
|
// digest, so `validate` reported "valid and up to date" for a snapshot whose files
|
|
3527
4061
|
// had all been reclassified — and per-layer budgets applied to different files.
|
|
4062
|
+
// A function matcher's `String()` is its source, not its closure: two functions with the same
|
|
4063
|
+
// body but different captured values digest identically. That cannot be fixed by hashing, so
|
|
4064
|
+
// the digest records that executable matchers are present and `validate` says the digest does
|
|
4065
|
+
// not cover their closure, instead of claiming a equality it cannot prove.
|
|
4066
|
+
executableMatchers: [...config.layers, ...config.kinds].some(
|
|
4067
|
+
(rule) => typeof rule.match === "function"
|
|
4068
|
+
),
|
|
3528
4069
|
layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
|
|
3529
4070
|
kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
|
|
3530
4071
|
// How files are enumerated decides what is in the snapshot at all.
|
|
@@ -3553,7 +4094,18 @@ function gitPaths(cwd, args) {
|
|
|
3553
4094
|
`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.`
|
|
3554
4095
|
);
|
|
3555
4096
|
}
|
|
3556
|
-
return output.split("\0").
|
|
4097
|
+
return output.split("\0").filter((entry) => entry.length > 0);
|
|
4098
|
+
}
|
|
4099
|
+
function readStagedBlob(cwd, relativePath) {
|
|
4100
|
+
try {
|
|
4101
|
+
return childProcess.execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
|
|
4102
|
+
cwd,
|
|
4103
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4104
|
+
maxBuffer: 512 * 1024 * 1024
|
|
4105
|
+
});
|
|
4106
|
+
} catch {
|
|
4107
|
+
return null;
|
|
4108
|
+
}
|
|
3557
4109
|
}
|
|
3558
4110
|
function assertUsableRef(ref) {
|
|
3559
4111
|
if (ref.startsWith("-")) {
|
|
@@ -3564,6 +4116,8 @@ function assertUsableRef(ref) {
|
|
|
3564
4116
|
}
|
|
3565
4117
|
function resolveChangedScope(cwd, request) {
|
|
3566
4118
|
const paths = /* @__PURE__ */ new Set();
|
|
4119
|
+
const stagedPaths = /* @__PURE__ */ new Set();
|
|
4120
|
+
const deletedPaths = /* @__PURE__ */ new Set();
|
|
3567
4121
|
const descriptions = [];
|
|
3568
4122
|
if (request.changedSince !== void 0) {
|
|
3569
4123
|
assertUsableRef(request.changedSince);
|
|
@@ -3572,7 +4126,17 @@ function resolveChangedScope(cwd, request) {
|
|
|
3572
4126
|
"--name-only",
|
|
3573
4127
|
"-z",
|
|
3574
4128
|
"--relative",
|
|
3575
|
-
request.changedSince
|
|
4129
|
+
`${request.changedSince}...HEAD`,
|
|
4130
|
+
"--"
|
|
4131
|
+
])) {
|
|
4132
|
+
paths.add(path22);
|
|
4133
|
+
}
|
|
4134
|
+
for (const path22 of gitPaths(cwd, [
|
|
4135
|
+
"diff",
|
|
4136
|
+
"--name-only",
|
|
4137
|
+
"-z",
|
|
4138
|
+
"--relative",
|
|
4139
|
+
"HEAD",
|
|
3576
4140
|
"--"
|
|
3577
4141
|
])) {
|
|
3578
4142
|
paths.add(path22);
|
|
@@ -3592,10 +4156,22 @@ function resolveChangedScope(cwd, request) {
|
|
|
3592
4156
|
"--"
|
|
3593
4157
|
])) {
|
|
3594
4158
|
paths.add(path22);
|
|
4159
|
+
stagedPaths.add(path22);
|
|
4160
|
+
}
|
|
4161
|
+
for (const path22 of gitPaths(cwd, [
|
|
4162
|
+
"diff",
|
|
4163
|
+
"--cached",
|
|
4164
|
+
"--name-only",
|
|
4165
|
+
"-z",
|
|
4166
|
+
"--relative",
|
|
4167
|
+
"--diff-filter=D",
|
|
4168
|
+
"--"
|
|
4169
|
+
])) {
|
|
4170
|
+
deletedPaths.add(path22);
|
|
3595
4171
|
}
|
|
3596
4172
|
descriptions.push("staged");
|
|
3597
4173
|
}
|
|
3598
|
-
return { paths, detail: descriptions.join(" and ") };
|
|
4174
|
+
return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
|
|
3599
4175
|
}
|
|
3600
4176
|
var RELATIVE_SPECIFIER = /^\.{1,2}\//;
|
|
3601
4177
|
var IMPORT_CANDIDATE_SUFFIXES = [
|
|
@@ -3626,34 +4202,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
|
|
|
3626
4202
|
var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
|
|
3627
4203
|
var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
|
|
3628
4204
|
var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
|
|
3629
|
-
|
|
4205
|
+
var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
|
|
4206
|
+
var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
|
|
4207
|
+
function tsconfigPathsFor(cwd) {
|
|
4208
|
+
const configPath = path16__namespace.join(cwd, "tsconfig.json");
|
|
4209
|
+
let stats;
|
|
4210
|
+
try {
|
|
4211
|
+
stats = fs15__namespace.statSync(configPath);
|
|
4212
|
+
} catch (err) {
|
|
4213
|
+
if (err.code === "ENOENT") return null;
|
|
4214
|
+
return null;
|
|
4215
|
+
}
|
|
4216
|
+
const key = `${stats.mtimeMs}:${stats.size}`;
|
|
4217
|
+
const cached = TSCONFIG_CACHE.get(configPath);
|
|
4218
|
+
if (cached !== void 0 && cached.key === key) return cached.value;
|
|
4219
|
+
let value = null;
|
|
4220
|
+
try {
|
|
4221
|
+
const read = ts2__default.default.readConfigFile(configPath, ts2__default.default.sys.readFile);
|
|
4222
|
+
if (read.error === void 0) {
|
|
4223
|
+
const parsed = ts2__default.default.parseJsonConfigFileContent(read.config, ts2__default.default.sys, cwd, void 0, configPath);
|
|
4224
|
+
const options = parsed.options;
|
|
4225
|
+
const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
|
|
4226
|
+
const rules = [];
|
|
4227
|
+
if (options.paths !== void 0) {
|
|
4228
|
+
for (const [pattern, targets] of Object.entries(options.paths)) {
|
|
4229
|
+
if (!Array.isArray(targets)) continue;
|
|
4230
|
+
rules.push({
|
|
4231
|
+
pattern,
|
|
4232
|
+
targets: targets.map((target) => String(target).replace(/\\/g, "/"))
|
|
4233
|
+
});
|
|
4234
|
+
}
|
|
4235
|
+
}
|
|
4236
|
+
if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
|
|
4237
|
+
}
|
|
4238
|
+
} catch (err) {
|
|
4239
|
+
value = null;
|
|
4240
|
+
}
|
|
4241
|
+
TSCONFIG_CACHE.set(configPath, { key, value });
|
|
4242
|
+
return value;
|
|
4243
|
+
}
|
|
4244
|
+
function repositoryRelative(cwd, target) {
|
|
4245
|
+
const relative14 = path16__namespace.relative(cwd, target).replace(/\\/g, "/");
|
|
4246
|
+
return relative14.length === 0 || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14) ? relative14 : null;
|
|
4247
|
+
}
|
|
4248
|
+
function rememberFirst(map, key, value) {
|
|
4249
|
+
if (!map.has(key)) map.set(key, value);
|
|
4250
|
+
}
|
|
4251
|
+
function buildImportResolver(files, options = {}) {
|
|
3630
4252
|
const byPath = /* @__PURE__ */ new Map();
|
|
3631
4253
|
const byPathFolded = /* @__PURE__ */ new Map();
|
|
3632
4254
|
const byStem = /* @__PURE__ */ new Map();
|
|
3633
4255
|
const byStemFolded = /* @__PURE__ */ new Map();
|
|
3634
|
-
const
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
remember(byPath, relativePath, relativePath);
|
|
3640
|
-
remember(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
4256
|
+
const register = (relativePath) => {
|
|
4257
|
+
rememberFirst(byPath, relativePath, relativePath);
|
|
4258
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
4259
|
+
rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
4260
|
+
}
|
|
3641
4261
|
const extension = path16__namespace.posix.extname(relativePath);
|
|
3642
|
-
if (!SOURCE_EXTENSIONS.has(extension))
|
|
4262
|
+
if (!SOURCE_EXTENSIONS.has(extension)) return;
|
|
3643
4263
|
const stem = relativePath.slice(0, -extension.length);
|
|
3644
|
-
|
|
3645
|
-
|
|
4264
|
+
rememberFirst(byStem, stem, relativePath);
|
|
4265
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
4266
|
+
rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
|
|
4267
|
+
}
|
|
3646
4268
|
if (path16__namespace.posix.basename(stem) === "index") {
|
|
3647
4269
|
const directory = path16__namespace.posix.dirname(stem);
|
|
3648
|
-
|
|
3649
|
-
|
|
4270
|
+
rememberFirst(byStem, directory, relativePath);
|
|
4271
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
4272
|
+
rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
};
|
|
4276
|
+
for (const file of files) register(file.relativePath);
|
|
4277
|
+
if (options.extraPaths !== void 0) {
|
|
4278
|
+
for (const extra of options.extraPaths) {
|
|
4279
|
+
if (!byPath.has(extra)) register(extra);
|
|
3650
4280
|
}
|
|
3651
4281
|
}
|
|
3652
|
-
return { byPath, byPathFolded, byStem, byStemFolded };
|
|
4282
|
+
return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
|
|
3653
4283
|
}
|
|
3654
4284
|
function resolveSpecifier(fromFile, specifier, resolver) {
|
|
3655
4285
|
const extension = path16__namespace.posix.extname(fromFile).toLowerCase();
|
|
3656
|
-
const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
|
|
4286
|
+
const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
3657
4287
|
const firstOf = (candidates) => {
|
|
3658
4288
|
for (const candidate of candidates) {
|
|
3659
4289
|
const hit = exact(candidate);
|
|
@@ -3661,6 +4291,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
3661
4291
|
}
|
|
3662
4292
|
return null;
|
|
3663
4293
|
};
|
|
4294
|
+
const lookupPath = (joined2) => {
|
|
4295
|
+
const direct = exact(joined2);
|
|
4296
|
+
if (direct) return direct;
|
|
4297
|
+
for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
|
|
4298
|
+
const hit = exact(`${joined2}${suffix}`);
|
|
4299
|
+
if (hit) return hit;
|
|
4300
|
+
}
|
|
4301
|
+
const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
|
|
4302
|
+
const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
4303
|
+
return byStem(joined2) ?? byStem(stem);
|
|
4304
|
+
};
|
|
3664
4305
|
if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
|
|
3665
4306
|
const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
|
|
3666
4307
|
const rest = specifier.slice(dots).replace(/\./g, "/");
|
|
@@ -3687,19 +4328,43 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
3687
4328
|
);
|
|
3688
4329
|
return firstOf([joined2, `${joined2}.dart`]);
|
|
3689
4330
|
}
|
|
3690
|
-
if (!RELATIVE_SPECIFIER.test(specifier))
|
|
4331
|
+
if (!RELATIVE_SPECIFIER.test(specifier)) {
|
|
4332
|
+
return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
|
|
4333
|
+
}
|
|
3691
4334
|
const joined = path16__namespace.posix.normalize(
|
|
3692
4335
|
path16__namespace.posix.join(path16__namespace.posix.dirname(fromFile), specifier)
|
|
3693
4336
|
);
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
4337
|
+
return lookupPath(joined);
|
|
4338
|
+
}
|
|
4339
|
+
function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
|
|
4340
|
+
const config = resolver.tsconfig;
|
|
4341
|
+
if (!config) return null;
|
|
4342
|
+
for (const rule of config.paths) {
|
|
4343
|
+
const star = rule.pattern.indexOf("*");
|
|
4344
|
+
let captured;
|
|
4345
|
+
if (star === -1) {
|
|
4346
|
+
captured = specifier === rule.pattern ? "" : null;
|
|
4347
|
+
} else {
|
|
4348
|
+
const prefix = rule.pattern.slice(0, star);
|
|
4349
|
+
const suffix = rule.pattern.slice(star + 1);
|
|
4350
|
+
if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
|
|
4351
|
+
captured = null;
|
|
4352
|
+
} else {
|
|
4353
|
+
captured = specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
4356
|
+
if (captured === null) continue;
|
|
4357
|
+
for (const target of rule.targets) {
|
|
4358
|
+
const substituted = target.split("*").join(captured);
|
|
4359
|
+
const base = config.baseUrl === null ? substituted : path16__namespace.posix.join(config.baseUrl, substituted);
|
|
4360
|
+
const hit = lookupPath(path16__namespace.posix.normalize(base));
|
|
4361
|
+
if (hit) return hit;
|
|
4362
|
+
}
|
|
4363
|
+
}
|
|
4364
|
+
if (config.baseUrl !== null) {
|
|
4365
|
+
return lookupPath(path16__namespace.posix.normalize(path16__namespace.posix.join(config.baseUrl, specifier)));
|
|
3699
4366
|
}
|
|
3700
|
-
|
|
3701
|
-
const byStem = (key) => resolver.byStem.get(key) ?? resolver.byStemFolded.get(key.toLowerCase()) ?? null;
|
|
3702
|
-
return byStem(joined) ?? byStem(stem);
|
|
4367
|
+
return null;
|
|
3703
4368
|
}
|
|
3704
4369
|
function importsChangedFile(importerPath, imports, changedPaths, resolver) {
|
|
3705
4370
|
for (const specifier of imports) {
|
|
@@ -3717,16 +4382,73 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
|
|
|
3717
4382
|
"HEAD",
|
|
3718
4383
|
"OPTIONS"
|
|
3719
4384
|
]);
|
|
4385
|
+
var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
|
|
4386
|
+
var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
|
|
4387
|
+
"get",
|
|
4388
|
+
"post",
|
|
4389
|
+
"put",
|
|
4390
|
+
"delete",
|
|
4391
|
+
"patch",
|
|
4392
|
+
"head",
|
|
4393
|
+
"options"
|
|
4394
|
+
]);
|
|
3720
4395
|
function bindingNames(name, into) {
|
|
3721
|
-
if (
|
|
4396
|
+
if (ts2__default.default.isIdentifier(name)) {
|
|
3722
4397
|
into.push(name.text);
|
|
3723
4398
|
return;
|
|
3724
4399
|
}
|
|
3725
4400
|
for (const element of name.elements) {
|
|
3726
|
-
if (
|
|
4401
|
+
if (ts2__default.default.isOmittedExpression(element)) continue;
|
|
3727
4402
|
bindingNames(element.name, into);
|
|
3728
4403
|
}
|
|
3729
4404
|
}
|
|
4405
|
+
function objectLiteralNames(node) {
|
|
4406
|
+
const names = [];
|
|
4407
|
+
for (const property of node.properties) {
|
|
4408
|
+
if (ts2__default.default.isShorthandPropertyAssignment(property)) {
|
|
4409
|
+
names.push(property.name.text);
|
|
4410
|
+
continue;
|
|
4411
|
+
}
|
|
4412
|
+
if (!ts2__default.default.isPropertyAssignment(property)) continue;
|
|
4413
|
+
const name = property.name;
|
|
4414
|
+
if (ts2__default.default.isIdentifier(name) || ts2__default.default.isStringLiteral(name) || ts2__default.default.isNumericLiteral(name)) {
|
|
4415
|
+
names.push(name.text);
|
|
4416
|
+
}
|
|
4417
|
+
}
|
|
4418
|
+
return names;
|
|
4419
|
+
}
|
|
4420
|
+
function cjsExportedNames(expression) {
|
|
4421
|
+
const left = expression.left;
|
|
4422
|
+
if (!ts2__default.default.isPropertyAccessExpression(left)) return null;
|
|
4423
|
+
const isModuleExports = left.name.text === "exports" && ts2__default.default.isIdentifier(left.expression) && left.expression.text === "module";
|
|
4424
|
+
if (isModuleExports) {
|
|
4425
|
+
const right = expression.right;
|
|
4426
|
+
if (ts2__default.default.isObjectLiteralExpression(right)) return objectLiteralNames(right);
|
|
4427
|
+
if (ts2__default.default.isIdentifier(right)) return [right.text];
|
|
4428
|
+
return [];
|
|
4429
|
+
}
|
|
4430
|
+
if (ts2__default.default.isIdentifier(left.expression) && left.expression.text === "exports") {
|
|
4431
|
+
return [left.name.text];
|
|
4432
|
+
}
|
|
4433
|
+
const parent = left.expression;
|
|
4434
|
+
if (ts2__default.default.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts2__default.default.isIdentifier(parent.expression) && parent.expression.text === "module") {
|
|
4435
|
+
return [left.name.text];
|
|
4436
|
+
}
|
|
4437
|
+
return null;
|
|
4438
|
+
}
|
|
4439
|
+
function countSyntacticErrors(fileName, content) {
|
|
4440
|
+
const result = ts2__default.default.transpileModule(content, {
|
|
4441
|
+
fileName,
|
|
4442
|
+
compilerOptions: {
|
|
4443
|
+
target: ts2__default.default.ScriptTarget.Latest,
|
|
4444
|
+
module: ts2__default.default.ModuleKind.ESNext
|
|
4445
|
+
},
|
|
4446
|
+
reportDiagnostics: true
|
|
4447
|
+
});
|
|
4448
|
+
return (result.diagnostics ?? []).filter(
|
|
4449
|
+
(diagnostic) => diagnostic.category === ts2__default.default.DiagnosticCategory.Error
|
|
4450
|
+
).length;
|
|
4451
|
+
}
|
|
3730
4452
|
function summarizeTypeScriptSource(relativePath, content) {
|
|
3731
4453
|
const summary = {
|
|
3732
4454
|
directives: [],
|
|
@@ -3744,19 +4466,20 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3744
4466
|
routeHandlers: []
|
|
3745
4467
|
};
|
|
3746
4468
|
const lowerPath = relativePath.toLowerCase();
|
|
3747
|
-
const
|
|
3748
|
-
const sourceFile =
|
|
4469
|
+
const scriptKind = /.tsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2__default.default.ScriptKind.JS : ts2__default.default.ScriptKind.TS;
|
|
4470
|
+
const sourceFile = ts2__default.default.createSourceFile(
|
|
3749
4471
|
relativePath,
|
|
3750
4472
|
content,
|
|
3751
|
-
|
|
4473
|
+
ts2__default.default.ScriptTarget.Latest,
|
|
3752
4474
|
/* setParentNodes */
|
|
3753
4475
|
false,
|
|
3754
|
-
|
|
4476
|
+
scriptKind
|
|
3755
4477
|
);
|
|
3756
|
-
const
|
|
4478
|
+
const parsedDiagnostics = sourceFile.parseDiagnostics;
|
|
4479
|
+
const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts2__default.default.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
|
|
3757
4480
|
if (parseErrors > 0) summary.parseErrors = parseErrors;
|
|
3758
4481
|
for (const statement of sourceFile.statements) {
|
|
3759
|
-
if (
|
|
4482
|
+
if (ts2__default.default.isExpressionStatement(statement) && ts2__default.default.isStringLiteral(statement.expression)) {
|
|
3760
4483
|
const text2 = statement.expression.text;
|
|
3761
4484
|
if (text2 === "use client" || text2 === "use server") {
|
|
3762
4485
|
summary.directives.push(text2);
|
|
@@ -3766,26 +4489,26 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3766
4489
|
break;
|
|
3767
4490
|
}
|
|
3768
4491
|
const isExported = (node) => {
|
|
3769
|
-
const modifiers =
|
|
3770
|
-
return Boolean(modifiers?.some((m) => m.kind ===
|
|
4492
|
+
const modifiers = ts2__default.default.canHaveModifiers(node) ? ts2__default.default.getModifiers(node) : void 0;
|
|
4493
|
+
return Boolean(modifiers?.some((m) => m.kind === ts2__default.default.SyntaxKind.ExportKeyword));
|
|
3771
4494
|
};
|
|
3772
4495
|
const isDefault = (node) => {
|
|
3773
|
-
const modifiers =
|
|
3774
|
-
return Boolean(modifiers?.some((m) => m.kind ===
|
|
4496
|
+
const modifiers = ts2__default.default.canHaveModifiers(node) ? ts2__default.default.getModifiers(node) : void 0;
|
|
4497
|
+
return Boolean(modifiers?.some((m) => m.kind === ts2__default.default.SyntaxKind.DefaultKeyword));
|
|
3775
4498
|
};
|
|
3776
4499
|
const rendersJsx = (node) => {
|
|
3777
4500
|
const pending = [node];
|
|
3778
4501
|
while (pending.length > 0) {
|
|
3779
4502
|
const current = pending.pop();
|
|
3780
|
-
if (
|
|
4503
|
+
if (ts2__default.default.isJsxElement(current) || ts2__default.default.isJsxSelfClosingElement(current) || ts2__default.default.isJsxFragment(current)) {
|
|
3781
4504
|
return true;
|
|
3782
4505
|
}
|
|
3783
|
-
if (
|
|
4506
|
+
if (ts2__default.default.isCallExpression(current)) {
|
|
3784
4507
|
const callee = current.expression;
|
|
3785
|
-
const calleeName =
|
|
4508
|
+
const calleeName = ts2__default.default.isIdentifier(callee) ? callee.text : ts2__default.default.isPropertyAccessExpression(callee) ? callee.name.text : "";
|
|
3786
4509
|
if (calleeName === "createElement") return true;
|
|
3787
4510
|
}
|
|
3788
|
-
|
|
4511
|
+
ts2__default.default.forEachChild(current, (child) => {
|
|
3789
4512
|
pending.push(child);
|
|
3790
4513
|
});
|
|
3791
4514
|
}
|
|
@@ -3794,11 +4517,11 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3794
4517
|
const REACT_BASE_CLASS = /(?:^|\.)(?:PureComponent|Component)$/;
|
|
3795
4518
|
const extendsReactBase = (node) => {
|
|
3796
4519
|
const heritage = (node.heritageClauses ?? []).find(
|
|
3797
|
-
(clause) => clause.token ===
|
|
4520
|
+
(clause) => clause.token === ts2__default.default.SyntaxKind.ExtendsKeyword
|
|
3798
4521
|
);
|
|
3799
4522
|
const expression = heritage?.types[0]?.expression;
|
|
3800
4523
|
if (!expression) return false;
|
|
3801
|
-
const text2 =
|
|
4524
|
+
const text2 = ts2__default.default.isIdentifier(expression) ? expression.text : expression.getText(sourceFile);
|
|
3802
4525
|
return REACT_BASE_CLASS.test(text2);
|
|
3803
4526
|
};
|
|
3804
4527
|
const recordFunctionLike = (name, exported, node) => {
|
|
@@ -3810,32 +4533,37 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3810
4533
|
if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
|
|
3811
4534
|
if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
|
|
3812
4535
|
};
|
|
4536
|
+
const cjsExports = [];
|
|
3813
4537
|
const stack = [sourceFile];
|
|
3814
4538
|
while (stack.length > 0) {
|
|
3815
4539
|
const node = stack.pop();
|
|
3816
|
-
if (
|
|
4540
|
+
if (ts2__default.default.isImportDeclaration(node) && ts2__default.default.isStringLiteral(node.moduleSpecifier)) {
|
|
3817
4541
|
summary.imports.push(node.moduleSpecifier.text);
|
|
3818
4542
|
}
|
|
3819
|
-
if (
|
|
4543
|
+
if (ts2__default.default.isImportEqualsDeclaration(node) && ts2__default.default.isExternalModuleReference(node.moduleReference) && node.moduleReference.expression !== void 0 && ts2__default.default.isStringLiteral(node.moduleReference.expression)) {
|
|
3820
4544
|
summary.imports.push(node.moduleReference.expression.text);
|
|
3821
4545
|
}
|
|
3822
|
-
if (
|
|
4546
|
+
if (ts2__default.default.isCallExpression(node) && node.arguments.length >= 1) {
|
|
3823
4547
|
const firstArgument = node.arguments[0];
|
|
3824
|
-
if (firstArgument !== void 0 &&
|
|
3825
|
-
const isDynamicImport = node.expression.kind ===
|
|
3826
|
-
const isRequire =
|
|
4548
|
+
if (firstArgument !== void 0 && ts2__default.default.isStringLiteral(firstArgument)) {
|
|
4549
|
+
const isDynamicImport = node.expression.kind === ts2__default.default.SyntaxKind.ImportKeyword;
|
|
4550
|
+
const isRequire = ts2__default.default.isIdentifier(node.expression) && node.expression.text === "require";
|
|
3827
4551
|
if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
|
|
3828
4552
|
}
|
|
4553
|
+
const callee = node.expression;
|
|
4554
|
+
if (ts2__default.default.isPropertyAccessExpression(callee) && ts2__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts2__default.default.isStringLiteral(firstArgument)) {
|
|
4555
|
+
summary.routeHandlers.push(callee.name.text.toUpperCase());
|
|
4556
|
+
}
|
|
3829
4557
|
}
|
|
3830
|
-
if (
|
|
3831
|
-
if (node.moduleSpecifier &&
|
|
4558
|
+
if (ts2__default.default.isExportDeclaration(node)) {
|
|
4559
|
+
if (node.moduleSpecifier && ts2__default.default.isStringLiteral(node.moduleSpecifier)) {
|
|
3832
4560
|
summary.imports.push(node.moduleSpecifier.text);
|
|
3833
4561
|
summary.reExports.push(node.moduleSpecifier.text);
|
|
3834
|
-
if (node.exportClause &&
|
|
4562
|
+
if (node.exportClause && ts2__default.default.isNamespaceExport(node.exportClause)) {
|
|
3835
4563
|
summary.exports.push(node.exportClause.name.text);
|
|
3836
4564
|
}
|
|
3837
4565
|
}
|
|
3838
|
-
if (node.exportClause &&
|
|
4566
|
+
if (node.exportClause && ts2__default.default.isNamedExports(node.exportClause)) {
|
|
3839
4567
|
for (const element of node.exportClause.elements) {
|
|
3840
4568
|
const exported = element.name.text;
|
|
3841
4569
|
summary.exports.push(exported);
|
|
@@ -3843,11 +4571,15 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3843
4571
|
}
|
|
3844
4572
|
}
|
|
3845
4573
|
}
|
|
3846
|
-
if (
|
|
4574
|
+
if (ts2__default.default.isExpressionStatement(node) && ts2__default.default.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts2__default.default.SyntaxKind.EqualsToken) {
|
|
4575
|
+
const cjsNames = cjsExportedNames(node.expression);
|
|
4576
|
+
if (cjsNames !== null) cjsExports.push(...cjsNames);
|
|
4577
|
+
}
|
|
4578
|
+
if (ts2__default.default.isExportAssignment(node)) {
|
|
3847
4579
|
summary.exports.push("default");
|
|
3848
4580
|
if (rendersJsx(node.expression)) summary.reactComponents.push("default");
|
|
3849
4581
|
}
|
|
3850
|
-
if (
|
|
4582
|
+
if (ts2__default.default.isFunctionDeclaration(node)) {
|
|
3851
4583
|
const exported = isExported(node);
|
|
3852
4584
|
if (node.name) {
|
|
3853
4585
|
recordFunctionLike(node.name.text, exported, node);
|
|
@@ -3856,7 +4588,7 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3856
4588
|
summary.exports.push("default");
|
|
3857
4589
|
}
|
|
3858
4590
|
}
|
|
3859
|
-
if (
|
|
4591
|
+
if (ts2__default.default.isClassDeclaration(node)) {
|
|
3860
4592
|
if (node.name) {
|
|
3861
4593
|
summary.classes.push(node.name.text);
|
|
3862
4594
|
if (isExported(node)) summary.exports.push(node.name.text);
|
|
@@ -3868,19 +4600,19 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3868
4600
|
summary.exports.push("default");
|
|
3869
4601
|
}
|
|
3870
4602
|
}
|
|
3871
|
-
if (
|
|
4603
|
+
if (ts2__default.default.isInterfaceDeclaration(node)) {
|
|
3872
4604
|
summary.interfaces.push(node.name.text);
|
|
3873
4605
|
if (isExported(node)) summary.exports.push(node.name.text);
|
|
3874
4606
|
}
|
|
3875
|
-
if (
|
|
4607
|
+
if (ts2__default.default.isTypeAliasDeclaration(node)) {
|
|
3876
4608
|
summary.types.push(node.name.text);
|
|
3877
4609
|
if (isExported(node)) summary.exports.push(node.name.text);
|
|
3878
4610
|
}
|
|
3879
|
-
if (
|
|
4611
|
+
if (ts2__default.default.isEnumDeclaration(node)) {
|
|
3880
4612
|
summary.enums.push(node.name.text);
|
|
3881
4613
|
if (isExported(node)) summary.exports.push(node.name.text);
|
|
3882
4614
|
}
|
|
3883
|
-
if (
|
|
4615
|
+
if (ts2__default.default.isVariableStatement(node)) {
|
|
3884
4616
|
const exported = isExported(node);
|
|
3885
4617
|
for (const declaration of node.declarationList.declarations) {
|
|
3886
4618
|
const bound = [];
|
|
@@ -3899,13 +4631,17 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
3899
4631
|
}
|
|
3900
4632
|
}
|
|
3901
4633
|
const children = [];
|
|
3902
|
-
|
|
4634
|
+
ts2__default.default.forEachChild(node, (child) => {
|
|
3903
4635
|
children.push(child);
|
|
3904
4636
|
});
|
|
3905
4637
|
for (let index = children.length - 1; index >= 0; index--) {
|
|
3906
4638
|
stack.push(children[index]);
|
|
3907
4639
|
}
|
|
3908
4640
|
}
|
|
4641
|
+
if (cjsExports.length > 0) {
|
|
4642
|
+
summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
|
|
4643
|
+
summary.exports.push(...cjsExports);
|
|
4644
|
+
}
|
|
3909
4645
|
const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
3910
4646
|
summary.directives = dedupeSorted2(summary.directives);
|
|
3911
4647
|
summary.imports = dedupeSorted2(summary.imports);
|
|
@@ -4469,9 +5205,9 @@ var rubyProfile = {
|
|
|
4469
5205
|
eachLine(content, (line) => {
|
|
4470
5206
|
const trimmed = line.trim();
|
|
4471
5207
|
if (!trimmed || trimmed.startsWith("#")) return;
|
|
4472
|
-
const
|
|
4473
|
-
if (
|
|
4474
|
-
summary.imports.push(`./${
|
|
5208
|
+
const relative14 = REQUIRE_RELATIVE.exec(trimmed);
|
|
5209
|
+
if (relative14) {
|
|
5210
|
+
summary.imports.push(`./${relative14[1]}`);
|
|
4475
5211
|
return;
|
|
4476
5212
|
}
|
|
4477
5213
|
const required = REQUIRE.exec(trimmed);
|
|
@@ -4998,13 +5734,13 @@ function isBinaryFile(absolutePath) {
|
|
|
4998
5734
|
if (isBinaryExtension(absolutePath)) return true;
|
|
4999
5735
|
let fd;
|
|
5000
5736
|
try {
|
|
5001
|
-
fd =
|
|
5737
|
+
fd = fs15__namespace.openSync(absolutePath, "r");
|
|
5002
5738
|
const buffer = Buffer.alloc(CHUNK);
|
|
5003
5739
|
let sample;
|
|
5004
5740
|
let position = 0;
|
|
5005
5741
|
while (position < BINARY_SCAN_BYTES) {
|
|
5006
5742
|
const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
|
|
5007
|
-
const bytesRead =
|
|
5743
|
+
const bytesRead = fs15__namespace.readSync(fd, buffer, 0, wanted, position);
|
|
5008
5744
|
if (bytesRead === 0) return false;
|
|
5009
5745
|
const chunk = buffer.subarray(0, bytesRead);
|
|
5010
5746
|
if (sample === void 0) {
|
|
@@ -5022,7 +5758,7 @@ function isBinaryFile(absolutePath) {
|
|
|
5022
5758
|
} finally {
|
|
5023
5759
|
if (fd !== void 0) {
|
|
5024
5760
|
try {
|
|
5025
|
-
|
|
5761
|
+
fs15__namespace.closeSync(fd);
|
|
5026
5762
|
} catch {
|
|
5027
5763
|
}
|
|
5028
5764
|
}
|
|
@@ -5044,9 +5780,9 @@ function importsOfText(relativePath, text2) {
|
|
|
5044
5780
|
function importsOfFile(relativePath, absolutePath) {
|
|
5045
5781
|
let buffer;
|
|
5046
5782
|
try {
|
|
5047
|
-
const stats =
|
|
5783
|
+
const stats = fs15__namespace.statSync(absolutePath);
|
|
5048
5784
|
if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
|
|
5049
|
-
buffer =
|
|
5785
|
+
buffer = fs15__namespace.readFileSync(absolutePath);
|
|
5050
5786
|
} catch {
|
|
5051
5787
|
return [];
|
|
5052
5788
|
}
|
|
@@ -5073,7 +5809,7 @@ function findStagingDirectory(config) {
|
|
|
5073
5809
|
const tmpDir = path16__namespace.resolve(config.cwd, config.tmpDir);
|
|
5074
5810
|
let entries;
|
|
5075
5811
|
try {
|
|
5076
|
-
entries =
|
|
5812
|
+
entries = fs15__namespace.readdirSync(tmpDir);
|
|
5077
5813
|
} catch {
|
|
5078
5814
|
return null;
|
|
5079
5815
|
}
|
|
@@ -5086,8 +5822,8 @@ function describeMissingManifest(config, manifestPath) {
|
|
|
5086
5822
|
const markerPath = path16__namespace.join(outDir, ".codebase-snapshot");
|
|
5087
5823
|
let marker2 = null;
|
|
5088
5824
|
try {
|
|
5089
|
-
if (
|
|
5090
|
-
const parsed = JSON.parse(
|
|
5825
|
+
if (fs15__namespace.existsSync(markerPath)) {
|
|
5826
|
+
const parsed = JSON.parse(fs15__namespace.readFileSync(markerPath, "utf8"));
|
|
5091
5827
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
5092
5828
|
marker2 = parsed;
|
|
5093
5829
|
}
|
|
@@ -5124,11 +5860,11 @@ function sha256Hex(buffer) {
|
|
|
5124
5860
|
function wouldNowBeIncluded(cwd, relativePath) {
|
|
5125
5861
|
const absolutePath = path16__namespace.join(cwd, relativePath);
|
|
5126
5862
|
try {
|
|
5127
|
-
const stats =
|
|
5863
|
+
const stats = fs15__namespace.statSync(absolutePath);
|
|
5128
5864
|
if (!stats.isFile()) return false;
|
|
5129
5865
|
if (isBinaryExtension(absolutePath)) return false;
|
|
5130
5866
|
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
|
|
5131
|
-
return !decodeText(
|
|
5867
|
+
return !decodeText(fs15__namespace.readFileSync(absolutePath)).binary;
|
|
5132
5868
|
} catch {
|
|
5133
5869
|
return false;
|
|
5134
5870
|
}
|
|
@@ -5159,14 +5895,71 @@ function describeManifestShapeProblem(value) {
|
|
|
5159
5895
|
if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
|
|
5160
5896
|
return 'missing "totals" object';
|
|
5161
5897
|
}
|
|
5898
|
+
const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
|
|
5899
|
+
if (currentSchema) {
|
|
5900
|
+
const generator = candidate.generator;
|
|
5901
|
+
if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
|
|
5902
|
+
return 'missing "generator" object';
|
|
5903
|
+
}
|
|
5904
|
+
const generatorFields = generator;
|
|
5905
|
+
if (!isOurGeneratorName(generatorFields.name)) {
|
|
5906
|
+
return "`generator.name` is not this generator";
|
|
5907
|
+
}
|
|
5908
|
+
if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
|
|
5909
|
+
return "`generator.version` must be a non-empty string";
|
|
5910
|
+
}
|
|
5911
|
+
const git = candidate.git;
|
|
5912
|
+
if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
|
|
5913
|
+
const gitFields = git;
|
|
5914
|
+
if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
|
|
5915
|
+
if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
|
|
5916
|
+
if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
|
|
5917
|
+
const config = candidate.config;
|
|
5918
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
5919
|
+
return 'missing "config" object';
|
|
5920
|
+
}
|
|
5921
|
+
const budgets = candidate.budgets;
|
|
5922
|
+
if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
|
|
5923
|
+
return 'missing "budgets" object';
|
|
5924
|
+
}
|
|
5925
|
+
for (const key of ["maxPartBytes", "largeFileBytes"]) {
|
|
5926
|
+
const value2 = budgets[key];
|
|
5927
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
5928
|
+
return `\`budgets.${key}\` must be a non-negative integer`;
|
|
5929
|
+
}
|
|
5930
|
+
}
|
|
5931
|
+
if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
|
|
5932
|
+
return 'missing "indexes" object';
|
|
5933
|
+
}
|
|
5934
|
+
if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
|
|
5935
|
+
return 'missing "kinds" object';
|
|
5936
|
+
}
|
|
5937
|
+
}
|
|
5162
5938
|
if (!Array.isArray(candidate.files)) return 'missing "files" array';
|
|
5163
5939
|
for (const entry of candidate.files) {
|
|
5164
5940
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
5165
5941
|
return 'a "files" entry is not an object';
|
|
5166
5942
|
}
|
|
5167
|
-
|
|
5943
|
+
const fields = entry;
|
|
5944
|
+
if (typeof fields.relativePath !== "string") {
|
|
5168
5945
|
return 'a "files" entry has no "relativePath"';
|
|
5169
5946
|
}
|
|
5947
|
+
if (!currentSchema) continue;
|
|
5948
|
+
if (typeof fields.part !== "string" || fields.part.length === 0) {
|
|
5949
|
+
return 'a "files" entry records no "part"';
|
|
5950
|
+
}
|
|
5951
|
+
if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
|
|
5952
|
+
return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
|
|
5953
|
+
}
|
|
5954
|
+
for (const key of ["sizeBytes", "lines"]) {
|
|
5955
|
+
const value2 = fields[key];
|
|
5956
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
5957
|
+
return `a "files" entry "${key}" must be a non-negative integer`;
|
|
5958
|
+
}
|
|
5959
|
+
}
|
|
5960
|
+
if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
|
|
5961
|
+
return 'a "files" entry has an unknown "inclusionMode"';
|
|
5962
|
+
}
|
|
5170
5963
|
}
|
|
5171
5964
|
if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
|
|
5172
5965
|
if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
|
|
@@ -5174,13 +5967,28 @@ function describeManifestShapeProblem(value) {
|
|
|
5174
5967
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
5175
5968
|
return 'a "parts" entry is not an object';
|
|
5176
5969
|
}
|
|
5177
|
-
const
|
|
5970
|
+
const fields = entry;
|
|
5971
|
+
const filename = fields.filename;
|
|
5178
5972
|
if (typeof filename !== "string" || filename.trim() === "") {
|
|
5179
5973
|
return 'a "parts" entry has no "filename"';
|
|
5180
5974
|
}
|
|
5181
5975
|
if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16__namespace.isAbsolute(filename)) {
|
|
5182
5976
|
return 'a "parts" entry "filename" must be a bare filename inside parts/';
|
|
5183
5977
|
}
|
|
5978
|
+
if (currentSchema) {
|
|
5979
|
+
if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
|
|
5980
|
+
return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
|
|
5981
|
+
}
|
|
5982
|
+
if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
|
|
5983
|
+
return 'a "parts" entry "byteSize" must be a non-negative integer';
|
|
5984
|
+
}
|
|
5985
|
+
if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
|
|
5986
|
+
return 'a "parts" entry "index" must be a positive integer';
|
|
5987
|
+
}
|
|
5988
|
+
if (!Array.isArray(fields.includedFiles)) {
|
|
5989
|
+
return 'a "parts" entry has no "includedFiles" array';
|
|
5990
|
+
}
|
|
5991
|
+
}
|
|
5184
5992
|
}
|
|
5185
5993
|
if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
|
|
5186
5994
|
return 'missing "layers" object';
|
|
@@ -5191,7 +5999,7 @@ function validateSnapshot(configInput) {
|
|
|
5191
5999
|
assertUsableConfigInput(configInput);
|
|
5192
6000
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
|
|
5193
6001
|
const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
|
|
5194
|
-
if (!
|
|
6002
|
+
if (!fs15__namespace.existsSync(manifestPath)) {
|
|
5195
6003
|
return {
|
|
5196
6004
|
valid: false,
|
|
5197
6005
|
manifestPresent: false,
|
|
@@ -5202,7 +6010,7 @@ function validateSnapshot(configInput) {
|
|
|
5202
6010
|
}
|
|
5203
6011
|
let manifest;
|
|
5204
6012
|
try {
|
|
5205
|
-
manifest = JSON.parse(
|
|
6013
|
+
manifest = JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
|
|
5206
6014
|
} catch (err) {
|
|
5207
6015
|
return {
|
|
5208
6016
|
valid: false,
|
|
@@ -5225,6 +6033,19 @@ function validateSnapshot(configInput) {
|
|
|
5225
6033
|
const drift = emptyDrift();
|
|
5226
6034
|
const warnings = [];
|
|
5227
6035
|
const snapshotDir = path16__namespace.resolve(config.cwd, config.outDir);
|
|
6036
|
+
const unreadableSkips = manifest.skipped.filter(
|
|
6037
|
+
(entry) => entry.reason === "missing" || entry.reason === "read-error"
|
|
6038
|
+
);
|
|
6039
|
+
if (unreadableSkips.length > 0) {
|
|
6040
|
+
warnings.push(
|
|
6041
|
+
`${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.`
|
|
6042
|
+
);
|
|
6043
|
+
}
|
|
6044
|
+
if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
|
|
6045
|
+
warnings.push(
|
|
6046
|
+
"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."
|
|
6047
|
+
);
|
|
6048
|
+
}
|
|
5228
6049
|
const manifestFileMap = /* @__PURE__ */ new Map();
|
|
5229
6050
|
for (const file of manifest.files) {
|
|
5230
6051
|
if (file && typeof file.relativePath === "string") {
|
|
@@ -5287,7 +6108,7 @@ function validateSnapshot(configInput) {
|
|
|
5287
6108
|
// snapshot was reported as drifting.
|
|
5288
6109
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
5289
6110
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
5290
|
-
).filter((
|
|
6111
|
+
).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
|
|
5291
6112
|
});
|
|
5292
6113
|
for (const diskFile of collection.files) {
|
|
5293
6114
|
const snapshotHash = manifestFileMap.get(diskFile);
|
|
@@ -5312,7 +6133,7 @@ function validateSnapshot(configInput) {
|
|
|
5312
6133
|
}
|
|
5313
6134
|
let diskHash;
|
|
5314
6135
|
try {
|
|
5315
|
-
diskHash = sha256Hex(
|
|
6136
|
+
diskHash = sha256Hex(fs15__namespace.readFileSync(path16__namespace.join(config.cwd, diskFile)));
|
|
5316
6137
|
} catch (err) {
|
|
5317
6138
|
if (err.code === "ENOENT") {
|
|
5318
6139
|
drift.missingOnDisk.push(diskFile);
|
|
@@ -5336,7 +6157,7 @@ function validateSnapshot(configInput) {
|
|
|
5336
6157
|
}
|
|
5337
6158
|
let statFailure = null;
|
|
5338
6159
|
try {
|
|
5339
|
-
|
|
6160
|
+
fs15__namespace.statSync(confined);
|
|
5340
6161
|
} catch (err) {
|
|
5341
6162
|
statFailure = err;
|
|
5342
6163
|
}
|
|
@@ -5371,7 +6192,7 @@ function validateSnapshot(configInput) {
|
|
|
5371
6192
|
}
|
|
5372
6193
|
let buffer;
|
|
5373
6194
|
try {
|
|
5374
|
-
buffer =
|
|
6195
|
+
buffer = fs15__namespace.readFileSync(partPath);
|
|
5375
6196
|
} catch {
|
|
5376
6197
|
drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
|
|
5377
6198
|
continue;
|
|
@@ -5393,24 +6214,85 @@ function validateSnapshot(configInput) {
|
|
|
5393
6214
|
});
|
|
5394
6215
|
}
|
|
5395
6216
|
}
|
|
5396
|
-
const
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
)
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
6217
|
+
const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
6218
|
+
const includedByPart = /* @__PURE__ */ new Map();
|
|
6219
|
+
const partIndexes = /* @__PURE__ */ new Set();
|
|
6220
|
+
for (const part of manifest.parts) {
|
|
6221
|
+
if (includedByPart.has(part.filename)) {
|
|
6222
|
+
drift.partIssues.push({
|
|
6223
|
+
part: maskDriftPath(part.filename),
|
|
6224
|
+
issue: "appears more than once in parts[]"
|
|
6225
|
+
});
|
|
6226
|
+
}
|
|
6227
|
+
if (typeof part.index === "number") {
|
|
6228
|
+
if (partIndexes.has(part.index)) {
|
|
6229
|
+
drift.partIssues.push({
|
|
6230
|
+
part: maskDriftPath(part.filename),
|
|
6231
|
+
issue: `reuses part index ${part.index}`
|
|
6232
|
+
});
|
|
6233
|
+
}
|
|
6234
|
+
partIndexes.add(part.index);
|
|
6235
|
+
}
|
|
6236
|
+
const listed = /* @__PURE__ */ new Set();
|
|
6237
|
+
for (const included of part.includedFiles ?? []) {
|
|
6238
|
+
if (typeof included?.relativePath !== "string") continue;
|
|
6239
|
+
if (listed.has(included.relativePath)) {
|
|
6240
|
+
drift.partIssues.push({
|
|
6241
|
+
part: maskDriftPath(part.filename),
|
|
6242
|
+
issue: `lists ${maskDriftPath(included.relativePath)} twice`
|
|
6243
|
+
});
|
|
6244
|
+
}
|
|
6245
|
+
listed.add(included.relativePath);
|
|
6246
|
+
}
|
|
6247
|
+
includedByPart.set(part.filename, listed);
|
|
6248
|
+
if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
|
|
6249
|
+
drift.partIssues.push({
|
|
6250
|
+
part: maskDriftPath(part.filename),
|
|
6251
|
+
issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
|
|
6252
|
+
});
|
|
6253
|
+
}
|
|
5405
6254
|
}
|
|
6255
|
+
const filePaths = /* @__PURE__ */ new Set();
|
|
5406
6256
|
for (const file of manifest.files) {
|
|
5407
|
-
if (
|
|
6257
|
+
if (filePaths.has(file.relativePath)) {
|
|
6258
|
+
drift.partIssues.push({
|
|
6259
|
+
part: "(files)",
|
|
6260
|
+
issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
|
|
6261
|
+
});
|
|
6262
|
+
continue;
|
|
6263
|
+
}
|
|
6264
|
+
filePaths.add(file.relativePath);
|
|
6265
|
+
if (typeof file.part !== "string" || file.part.length === 0) {
|
|
6266
|
+
drift.partIssues.push({
|
|
6267
|
+
part: "(files)",
|
|
6268
|
+
issue: `${maskDriftPath(file.relativePath)} records no part`
|
|
6269
|
+
});
|
|
6270
|
+
continue;
|
|
6271
|
+
}
|
|
6272
|
+
if (!partNames.has(file.part)) {
|
|
5408
6273
|
drift.partIssues.push({
|
|
5409
|
-
part: file.part,
|
|
5410
|
-
issue: `${file.relativePath} points at a part that is not in the manifest`
|
|
6274
|
+
part: maskDriftPath(file.part),
|
|
6275
|
+
issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
|
|
6276
|
+
});
|
|
6277
|
+
continue;
|
|
6278
|
+
}
|
|
6279
|
+
if (!includedByPart.get(file.part)?.has(file.relativePath)) {
|
|
6280
|
+
drift.partIssues.push({
|
|
6281
|
+
part: maskDriftPath(file.part),
|
|
6282
|
+
issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
|
|
5411
6283
|
});
|
|
5412
6284
|
}
|
|
5413
6285
|
}
|
|
6286
|
+
for (const [partName, listed] of includedByPart) {
|
|
6287
|
+
for (const relativePath of listed) {
|
|
6288
|
+
if (!filePaths.has(relativePath)) {
|
|
6289
|
+
drift.partIssues.push({
|
|
6290
|
+
part: maskDriftPath(partName),
|
|
6291
|
+
issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
|
|
6292
|
+
});
|
|
6293
|
+
}
|
|
6294
|
+
}
|
|
6295
|
+
}
|
|
5414
6296
|
const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
5415
6297
|
const currentExcludes = config.excludePatterns.map(maskValue);
|
|
5416
6298
|
const currentInclude = config.include.map(maskValue);
|
|
@@ -5566,6 +6448,13 @@ function validateSnapshot(configInput) {
|
|
|
5566
6448
|
0
|
|
5567
6449
|
);
|
|
5568
6450
|
expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
|
|
6451
|
+
if (manifest.files.every((file) => typeof file?.lines === "number")) {
|
|
6452
|
+
expectEqual(
|
|
6453
|
+
"counts.totalLines",
|
|
6454
|
+
counts.totalLines,
|
|
6455
|
+
manifest.files.reduce((total, file) => total + file.lines, 0)
|
|
6456
|
+
);
|
|
6457
|
+
}
|
|
5569
6458
|
expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
|
|
5570
6459
|
expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
|
|
5571
6460
|
expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
|
|
@@ -5589,6 +6478,37 @@ function validateSnapshot(configInput) {
|
|
|
5589
6478
|
`totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
|
|
5590
6479
|
);
|
|
5591
6480
|
}
|
|
6481
|
+
const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
|
|
6482
|
+
if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
|
|
6483
|
+
const settingsLine = `settings:${recordedSettingsDigest}`;
|
|
6484
|
+
const currentDefinition = sha256Hex(
|
|
6485
|
+
Buffer.from(
|
|
6486
|
+
[
|
|
6487
|
+
...manifest.files.map(
|
|
6488
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
6489
|
+
),
|
|
6490
|
+
settingsLine
|
|
6491
|
+
].join("\n"),
|
|
6492
|
+
"utf8"
|
|
6493
|
+
)
|
|
6494
|
+
);
|
|
6495
|
+
const legacyDefinition = sha256Hex(
|
|
6496
|
+
Buffer.from(
|
|
6497
|
+
[
|
|
6498
|
+
...manifest.files.map(
|
|
6499
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
|
|
6500
|
+
),
|
|
6501
|
+
settingsLine
|
|
6502
|
+
].join("\n"),
|
|
6503
|
+
"utf8"
|
|
6504
|
+
)
|
|
6505
|
+
);
|
|
6506
|
+
if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
|
|
6507
|
+
totalsMismatches.push(
|
|
6508
|
+
"fingerprint: does not match the files and settings recorded in this manifest"
|
|
6509
|
+
);
|
|
6510
|
+
}
|
|
6511
|
+
}
|
|
5592
6512
|
if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
|
|
5593
6513
|
totalsMismatches.push(
|
|
5594
6514
|
`budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
|
|
@@ -5616,26 +6536,49 @@ function validateSnapshot(configInput) {
|
|
|
5616
6536
|
drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
|
|
5617
6537
|
}
|
|
5618
6538
|
}
|
|
5619
|
-
|
|
6539
|
+
const declaredArtifacts = [
|
|
6540
|
+
["README.md", manifest.artifacts?.readme],
|
|
6541
|
+
["reports/navigation.md", manifest.artifacts?.navigation],
|
|
6542
|
+
["reports/project-tree.md", manifest.artifacts?.projectTree],
|
|
6543
|
+
["reports/audit.md", manifest.artifacts?.audit],
|
|
5620
6544
|
["full-codebase.json", manifest.artifacts?.fullJson],
|
|
5621
6545
|
["full-codebase.md", manifest.artifacts?.fullMarkdown]
|
|
5622
|
-
]
|
|
6546
|
+
];
|
|
6547
|
+
for (const [key, artifact] of declaredArtifacts) {
|
|
5623
6548
|
if (!artifact) continue;
|
|
5624
|
-
const artifactPath = path16__namespace.join(snapshotDir, key);
|
|
6549
|
+
const artifactPath = path16__namespace.join(snapshotDir, ...key.split("/"));
|
|
6550
|
+
let buffer;
|
|
5625
6551
|
try {
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
5629
|
-
}
|
|
6552
|
+
if (!fs15__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
|
|
6553
|
+
buffer = fs15__namespace.readFileSync(artifactPath);
|
|
5630
6554
|
} catch {
|
|
5631
6555
|
drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
|
|
6556
|
+
continue;
|
|
6557
|
+
}
|
|
6558
|
+
if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
|
|
6559
|
+
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
6560
|
+
continue;
|
|
6561
|
+
}
|
|
6562
|
+
if (key === "reports/navigation.md") {
|
|
6563
|
+
for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
|
|
6564
|
+
const target = match[1].split("#")[0];
|
|
6565
|
+
if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
|
|
6566
|
+
const resolved = path16__namespace.resolve(snapshotDir, "reports", target);
|
|
6567
|
+
const relative14 = path16__namespace.relative(snapshotDir, resolved);
|
|
6568
|
+
if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14) || !fs15__namespace.existsSync(resolved)) {
|
|
6569
|
+
drift.partIssues.push({
|
|
6570
|
+
part: key,
|
|
6571
|
+
issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
|
|
6572
|
+
});
|
|
6573
|
+
}
|
|
6574
|
+
}
|
|
5632
6575
|
}
|
|
5633
6576
|
}
|
|
5634
6577
|
const sarifArtifact = manifest.artifacts?.sarif;
|
|
5635
6578
|
if (sarifArtifact) {
|
|
5636
6579
|
const sarifKey = "reports/audit.sarif";
|
|
5637
6580
|
try {
|
|
5638
|
-
const buffer =
|
|
6581
|
+
const buffer = fs15__namespace.readFileSync(path16__namespace.join(snapshotDir, "reports", "audit.sarif"));
|
|
5639
6582
|
if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
|
|
5640
6583
|
drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
|
|
5641
6584
|
}
|
|
@@ -5644,8 +6587,11 @@ function validateSnapshot(configInput) {
|
|
|
5644
6587
|
}
|
|
5645
6588
|
}
|
|
5646
6589
|
if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
|
|
6590
|
+
const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
6591
|
+
const generatedOn = maskBranch(manifest.git.branch);
|
|
6592
|
+
const configuredAs = maskBranch(config.branch);
|
|
5647
6593
|
warnings.push(
|
|
5648
|
-
`Snapshot was generated on branch "${
|
|
6594
|
+
`Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
|
|
5649
6595
|
);
|
|
5650
6596
|
}
|
|
5651
6597
|
const errors = [];
|
|
@@ -5896,14 +6842,14 @@ function compareManifests(before, after) {
|
|
|
5896
6842
|
function loadManifest(target) {
|
|
5897
6843
|
let isDirectory;
|
|
5898
6844
|
try {
|
|
5899
|
-
isDirectory =
|
|
6845
|
+
isDirectory = fs15__namespace.statSync(target).isDirectory();
|
|
5900
6846
|
} catch {
|
|
5901
6847
|
throw new Error(`No snapshot found at ${target}: the path does not exist.`);
|
|
5902
6848
|
}
|
|
5903
6849
|
const manifestPath = isDirectory ? path16__namespace.join(target, "manifest.json") : target;
|
|
5904
6850
|
let raw;
|
|
5905
6851
|
try {
|
|
5906
|
-
raw =
|
|
6852
|
+
raw = fs15__namespace.readFileSync(manifestPath, "utf8");
|
|
5907
6853
|
} catch {
|
|
5908
6854
|
throw new Error(`Could not read a manifest at ${manifestPath}.`);
|
|
5909
6855
|
}
|
|
@@ -5957,6 +6903,68 @@ function renderDiffText(diff) {
|
|
|
5957
6903
|
}
|
|
5958
6904
|
return lines.join("\n");
|
|
5959
6905
|
}
|
|
6906
|
+
function hasCollapsibleBody(node) {
|
|
6907
|
+
if (!("body" in node)) return false;
|
|
6908
|
+
const body = node.body;
|
|
6909
|
+
return body !== void 0 && ts2__default.default.isBlock(body);
|
|
6910
|
+
}
|
|
6911
|
+
function scriptKindFor(fileName) {
|
|
6912
|
+
const lower = fileName.toLowerCase();
|
|
6913
|
+
if (lower.endsWith(".tsx")) return ts2__default.default.ScriptKind.TSX;
|
|
6914
|
+
if (lower.endsWith(".jsx")) return ts2__default.default.ScriptKind.JSX;
|
|
6915
|
+
if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
|
|
6916
|
+
return ts2__default.default.ScriptKind.JS;
|
|
6917
|
+
}
|
|
6918
|
+
return ts2__default.default.ScriptKind.TS;
|
|
6919
|
+
}
|
|
6920
|
+
function skeletonizeTypeScript(source, fileName = "file.ts") {
|
|
6921
|
+
const sourceFile = ts2__default.default.createSourceFile(
|
|
6922
|
+
fileName,
|
|
6923
|
+
source,
|
|
6924
|
+
ts2__default.default.ScriptTarget.Latest,
|
|
6925
|
+
// `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
|
|
6926
|
+
// source file explicitly, which is the reason that argument exists. Asking for parent pointers
|
|
6927
|
+
// makes the parser run a second full pass over every node in the file to set them, on top of
|
|
6928
|
+
// the summary parse this same file already pays for.
|
|
6929
|
+
false,
|
|
6930
|
+
scriptKindFor(fileName)
|
|
6931
|
+
);
|
|
6932
|
+
const spans = [];
|
|
6933
|
+
const visit = (node) => {
|
|
6934
|
+
if ((ts2__default.default.isFunctionDeclaration(node) || ts2__default.default.isMethodDeclaration(node) || ts2__default.default.isConstructorDeclaration(node) || ts2__default.default.isGetAccessorDeclaration(node) || ts2__default.default.isSetAccessorDeclaration(node) || ts2__default.default.isFunctionExpression(node) || ts2__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
|
|
6935
|
+
const body = node.body;
|
|
6936
|
+
if (body.statements.length > 0) {
|
|
6937
|
+
const start = body.getStart(sourceFile);
|
|
6938
|
+
const end = body.getEnd();
|
|
6939
|
+
if (end > start) spans.push({ start, end });
|
|
6940
|
+
}
|
|
6941
|
+
}
|
|
6942
|
+
ts2__default.default.forEachChild(node, visit);
|
|
6943
|
+
};
|
|
6944
|
+
visit(sourceFile);
|
|
6945
|
+
if (spans.length === 0) return { text: source, collapsed: 0 };
|
|
6946
|
+
const outermost = [];
|
|
6947
|
+
for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
|
|
6948
|
+
const last = outermost[outermost.length - 1];
|
|
6949
|
+
if (last && span.start < last.end) continue;
|
|
6950
|
+
outermost.push(span);
|
|
6951
|
+
}
|
|
6952
|
+
const chunks = [];
|
|
6953
|
+
let cursor = 0;
|
|
6954
|
+
for (const span of outermost) {
|
|
6955
|
+
chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
|
|
6956
|
+
cursor = span.end;
|
|
6957
|
+
}
|
|
6958
|
+
chunks.push(source.slice(cursor));
|
|
6959
|
+
return { text: chunks.join(""), collapsed: outermost.length };
|
|
6960
|
+
}
|
|
6961
|
+
function isSkeletonizable(filePath) {
|
|
6962
|
+
const lower = filePath.toLowerCase();
|
|
6963
|
+
if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
|
|
6964
|
+
return false;
|
|
6965
|
+
}
|
|
6966
|
+
return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
|
|
6967
|
+
}
|
|
5960
6968
|
|
|
5961
6969
|
// src/partitioner/preview.ts
|
|
5962
6970
|
var LINE_ENDINGS = /\r\n|\r/g;
|
|
@@ -5979,9 +6987,9 @@ function truncateToBytes(content, maxBytes) {
|
|
|
5979
6987
|
if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
|
|
5980
6988
|
const buffer = Buffer.from(content, "utf8");
|
|
5981
6989
|
if (buffer.length <= maxBytes) return { content, isTruncated: false };
|
|
5982
|
-
let
|
|
5983
|
-
while (
|
|
5984
|
-
return { content:
|
|
6990
|
+
let end = maxBytes;
|
|
6991
|
+
while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
|
|
6992
|
+
return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
|
|
5985
6993
|
}
|
|
5986
6994
|
function truncatePreview(content, headLines, tailLines) {
|
|
5987
6995
|
const normalised = normaliseLineEndings(content);
|
|
@@ -6117,23 +7125,23 @@ function describeMatcher(matcher) {
|
|
|
6117
7125
|
function normalizeTarget(cwd, target) {
|
|
6118
7126
|
const resolvedCwd = path16__namespace.resolve(cwd);
|
|
6119
7127
|
const absolute = path16__namespace.resolve(resolvedCwd, target);
|
|
6120
|
-
const
|
|
6121
|
-
if (
|
|
7128
|
+
const relative14 = path16__namespace.relative(resolvedCwd, absolute);
|
|
7129
|
+
if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
|
|
6122
7130
|
return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
|
|
6123
7131
|
}
|
|
6124
|
-
return { relative:
|
|
7132
|
+
return { relative: relative14.split(path16__namespace.sep).join("/"), outsideRoot: false };
|
|
6125
7133
|
}
|
|
6126
7134
|
function findRuleMatch(rules, relativePath) {
|
|
6127
7135
|
return rules.find(
|
|
6128
7136
|
(rule) => matchRule(relativePath, rule.match)
|
|
6129
7137
|
);
|
|
6130
7138
|
}
|
|
6131
|
-
function findRecordedAncestor(skipped,
|
|
7139
|
+
function findRecordedAncestor(skipped, relative14, maskedPath2) {
|
|
6132
7140
|
let nearest;
|
|
6133
7141
|
for (const record of skipped) {
|
|
6134
7142
|
const ancestorPath = record.path;
|
|
6135
7143
|
if (ancestorPath.length === 0) continue;
|
|
6136
|
-
const isAncestor =
|
|
7144
|
+
const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
|
|
6137
7145
|
if (!isAncestor) continue;
|
|
6138
7146
|
if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
|
|
6139
7147
|
}
|
|
@@ -6142,15 +7150,15 @@ function findRecordedAncestor(skipped, relative12, maskedPath2) {
|
|
|
6142
7150
|
function readManifest2(config) {
|
|
6143
7151
|
const manifestPath = path16__namespace.resolve(config.cwd, config.outDir, "manifest.json");
|
|
6144
7152
|
try {
|
|
6145
|
-
return JSON.parse(
|
|
7153
|
+
return JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
|
|
6146
7154
|
} catch {
|
|
6147
7155
|
return null;
|
|
6148
7156
|
}
|
|
6149
7157
|
}
|
|
6150
7158
|
function explainPath(config, target) {
|
|
6151
7159
|
const normalized = normalizeTarget(config.cwd, target);
|
|
6152
|
-
const
|
|
6153
|
-
const maskedPath2 = findSecretInPath(
|
|
7160
|
+
const relative14 = normalized.relative;
|
|
7161
|
+
const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
|
|
6154
7162
|
if (normalized.outsideRoot) {
|
|
6155
7163
|
return {
|
|
6156
7164
|
path: maskedPath2,
|
|
@@ -6160,10 +7168,10 @@ function explainPath(config, target) {
|
|
|
6160
7168
|
detail: "path resolves outside the configured repository root and was not inspected"
|
|
6161
7169
|
};
|
|
6162
7170
|
}
|
|
6163
|
-
const absolute = path16__namespace.join(config.cwd,
|
|
7171
|
+
const absolute = path16__namespace.join(config.cwd, relative14);
|
|
6164
7172
|
const result = {
|
|
6165
7173
|
path: maskedPath2,
|
|
6166
|
-
exists:
|
|
7174
|
+
exists: fs15__namespace.existsSync(absolute),
|
|
6167
7175
|
included: false
|
|
6168
7176
|
};
|
|
6169
7177
|
const collection = collectFiles(config.cwd, {
|
|
@@ -6178,11 +7186,11 @@ function explainPath(config, target) {
|
|
|
6178
7186
|
// that is only missing because the walker dropped the tool's own output directory.
|
|
6179
7187
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
6180
7188
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
6181
|
-
).filter((
|
|
7189
|
+
).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
|
|
6182
7190
|
});
|
|
6183
|
-
if (!collection.files.includes(
|
|
7191
|
+
if (!collection.files.includes(relative14)) {
|
|
6184
7192
|
const record = collection.skipped.find(
|
|
6185
|
-
(entry2) => entry2.path ===
|
|
7193
|
+
(entry2) => entry2.path === relative14 || entry2.path === maskedPath2
|
|
6186
7194
|
);
|
|
6187
7195
|
if (record) {
|
|
6188
7196
|
result.reason = record.reason;
|
|
@@ -6191,7 +7199,7 @@ function explainPath(config, target) {
|
|
|
6191
7199
|
result.reason = "missing";
|
|
6192
7200
|
result.detail = "no such file or directory, relative to the configured cwd";
|
|
6193
7201
|
} else {
|
|
6194
|
-
const ancestor = findRecordedAncestor(collection.skipped,
|
|
7202
|
+
const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
|
|
6195
7203
|
if (ancestor) {
|
|
6196
7204
|
result.reason = ancestor.reason;
|
|
6197
7205
|
result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
|
|
@@ -6211,11 +7219,11 @@ function explainPath(config, target) {
|
|
|
6211
7219
|
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
6212
7220
|
...config.staged === true ? { staged: true } : {}
|
|
6213
7221
|
});
|
|
6214
|
-
inScope = scope.paths.has(
|
|
7222
|
+
inScope = scope.paths.has(relative14);
|
|
6215
7223
|
if (!inScope && config.withDependents === true) {
|
|
6216
7224
|
inScope = importsChangedFile(
|
|
6217
|
-
|
|
6218
|
-
importsOfFile(
|
|
7225
|
+
relative14,
|
|
7226
|
+
importsOfFile(relative14, absolute),
|
|
6219
7227
|
scope.paths,
|
|
6220
7228
|
buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
|
|
6221
7229
|
);
|
|
@@ -6242,7 +7250,7 @@ function explainPath(config, target) {
|
|
|
6242
7250
|
}
|
|
6243
7251
|
let sizeOnDisk = null;
|
|
6244
7252
|
try {
|
|
6245
|
-
sizeOnDisk =
|
|
7253
|
+
sizeOnDisk = fs15__namespace.statSync(absolute).size;
|
|
6246
7254
|
} catch {
|
|
6247
7255
|
sizeOnDisk = null;
|
|
6248
7256
|
}
|
|
@@ -6252,8 +7260,16 @@ function explainPath(config, target) {
|
|
|
6252
7260
|
result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
|
|
6253
7261
|
return result;
|
|
6254
7262
|
}
|
|
6255
|
-
if (
|
|
6256
|
-
|
|
7263
|
+
if (fs15__namespace.existsSync(absolute) && fs15__namespace.statSync(absolute).isFile()) {
|
|
7264
|
+
let buffer;
|
|
7265
|
+
try {
|
|
7266
|
+
buffer = fs15__namespace.readFileSync(absolute);
|
|
7267
|
+
} catch (err) {
|
|
7268
|
+
result.included = false;
|
|
7269
|
+
result.reason = "read-error";
|
|
7270
|
+
result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
|
|
7271
|
+
return result;
|
|
7272
|
+
}
|
|
6257
7273
|
const decoded = decodeText(buffer);
|
|
6258
7274
|
if (decoded.binary) {
|
|
6259
7275
|
result.included = false;
|
|
@@ -6265,21 +7281,30 @@ function explainPath(config, target) {
|
|
|
6265
7281
|
result.bytes = buffer.length;
|
|
6266
7282
|
result.lines = countLines(text2);
|
|
6267
7283
|
if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
|
|
6268
|
-
const { findings } = scanAndRedactSecrets(text2, config.secretRules,
|
|
7284
|
+
const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
|
|
6269
7285
|
result.secretCount = findings.length;
|
|
6270
7286
|
result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
|
|
7287
|
+
let inclusionMode = "full";
|
|
7288
|
+
if (config.skeleton === true && isSkeletonizable(relative14)) {
|
|
7289
|
+
const skeleton = skeletonizeTypeScript(text2, relative14);
|
|
7290
|
+
if (skeleton.collapsed > 0) inclusionMode = "signatures";
|
|
7291
|
+
}
|
|
7292
|
+
if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
|
|
7293
|
+
const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
|
|
7294
|
+
inclusionMode = preview.isTruncated ? "preview" : "full";
|
|
7295
|
+
}
|
|
7296
|
+
result.inclusionMode = inclusionMode;
|
|
6271
7297
|
}
|
|
6272
|
-
result.layer = classifyLayer(
|
|
6273
|
-
result.kind = classifyKind(
|
|
6274
|
-
result.language = detectLanguage(
|
|
6275
|
-
const layerRule = findRuleMatch(config.layers,
|
|
7298
|
+
result.layer = classifyLayer(relative14, config.layers);
|
|
7299
|
+
result.kind = classifyKind(relative14, config.kinds);
|
|
7300
|
+
result.language = detectLanguage(relative14);
|
|
7301
|
+
const layerRule = findRuleMatch(config.layers, relative14);
|
|
6276
7302
|
if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
|
|
6277
|
-
const kindRule = findRuleMatch(config.kinds,
|
|
7303
|
+
const kindRule = findRuleMatch(config.kinds, relative14);
|
|
6278
7304
|
if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
|
|
6279
7305
|
const manifest = readManifest2(config);
|
|
6280
|
-
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath ===
|
|
7306
|
+
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
|
|
6281
7307
|
result.part = entry?.part ?? null;
|
|
6282
|
-
result.inclusionMode = entry?.inclusionMode;
|
|
6283
7308
|
return result;
|
|
6284
7309
|
}
|
|
6285
7310
|
function renderExplainText(result) {
|
|
@@ -6488,18 +7513,70 @@ function summarizeMarkdown(content) {
|
|
|
6488
7513
|
frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
|
|
6489
7514
|
};
|
|
6490
7515
|
}
|
|
7516
|
+
function decodeGitignore(buffer) {
|
|
7517
|
+
const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
|
|
7518
|
+
if (startsWith(239, 187, 191)) {
|
|
7519
|
+
const body = buffer.subarray(3);
|
|
7520
|
+
const text3 = body.toString("utf8");
|
|
7521
|
+
if (!Buffer.from(text3, "utf8").equals(body)) return null;
|
|
7522
|
+
return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
|
|
7523
|
+
}
|
|
7524
|
+
if (startsWith(255, 254)) {
|
|
7525
|
+
const body = buffer.subarray(2);
|
|
7526
|
+
if (body.length % 2 !== 0) return null;
|
|
7527
|
+
const text3 = body.toString("utf16le");
|
|
7528
|
+
if (!Buffer.from(text3, "utf16le").equals(body)) return null;
|
|
7529
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
|
|
7530
|
+
}
|
|
7531
|
+
if (startsWith(254, 255)) {
|
|
7532
|
+
const body = buffer.subarray(2);
|
|
7533
|
+
if (body.length % 2 !== 0) return null;
|
|
7534
|
+
const swapped = Buffer.from(body);
|
|
7535
|
+
swapped.swap16();
|
|
7536
|
+
const text3 = swapped.toString("utf16le");
|
|
7537
|
+
if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
|
|
7538
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
|
|
7539
|
+
}
|
|
7540
|
+
const text2 = buffer.toString("utf8");
|
|
7541
|
+
if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
|
|
7542
|
+
return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
|
|
7543
|
+
}
|
|
7544
|
+
function encodeGitignore(decoded, text2) {
|
|
7545
|
+
if (decoded.encoding === "utf8") {
|
|
7546
|
+
return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
|
|
7547
|
+
}
|
|
7548
|
+
const littleEndian = Buffer.from(text2, "utf16le");
|
|
7549
|
+
if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
|
|
7550
|
+
const bigEndian = Buffer.from(littleEndian);
|
|
7551
|
+
bigEndian.swap16();
|
|
7552
|
+
return Buffer.concat([decoded.bom, bigEndian]);
|
|
7553
|
+
}
|
|
7554
|
+
function canonicalIgnorePattern(line) {
|
|
7555
|
+
const trimmed = line.trim();
|
|
7556
|
+
if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
|
|
7557
|
+
const negated = trimmed.startsWith("!");
|
|
7558
|
+
const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
|
|
7559
|
+
return `${negated ? "!" : ""}${body}`;
|
|
7560
|
+
}
|
|
6491
7561
|
function appendGitignoreEntries(cwd, entries) {
|
|
6492
7562
|
const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
|
|
6493
7563
|
if (wanted.length === 0) return { added: [], note: null };
|
|
6494
7564
|
const ignorePath = path16__namespace.join(cwd, ".gitignore");
|
|
6495
7565
|
const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
|
|
6496
|
-
let
|
|
7566
|
+
let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
|
|
6497
7567
|
try {
|
|
6498
|
-
if (
|
|
6499
|
-
if (
|
|
7568
|
+
if (fs15__namespace.existsSync(ignorePath)) {
|
|
7569
|
+
if (fs15__namespace.statSync(ignorePath).isDirectory()) {
|
|
6500
7570
|
return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
|
|
6501
7571
|
}
|
|
6502
|
-
|
|
7572
|
+
const read = decodeGitignore(fs15__namespace.readFileSync(ignorePath));
|
|
7573
|
+
if (read === null) {
|
|
7574
|
+
return {
|
|
7575
|
+
added: [],
|
|
7576
|
+
note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
|
|
7577
|
+
};
|
|
7578
|
+
}
|
|
7579
|
+
decoded = read;
|
|
6503
7580
|
}
|
|
6504
7581
|
} catch (err) {
|
|
6505
7582
|
return {
|
|
@@ -6507,13 +7584,17 @@ function appendGitignoreEntries(cwd, entries) {
|
|
|
6507
7584
|
note: `${ignorePath} could not be read (${err.message}). ${manual}`
|
|
6508
7585
|
};
|
|
6509
7586
|
}
|
|
6510
|
-
const
|
|
6511
|
-
const
|
|
7587
|
+
const existing = decoded.text;
|
|
7588
|
+
const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
|
|
7589
|
+
const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
|
|
6512
7590
|
if (added.length === 0) return { added: [], note: null };
|
|
6513
|
-
const
|
|
7591
|
+
const newline = existing.includes("\r\n") ? "\r\n" : "\n";
|
|
7592
|
+
const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
|
|
6514
7593
|
try {
|
|
6515
|
-
|
|
6516
|
-
|
|
7594
|
+
fs15__namespace.writeFileSync(
|
|
7595
|
+
ignorePath,
|
|
7596
|
+
encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
|
|
7597
|
+
);
|
|
6517
7598
|
} catch (err) {
|
|
6518
7599
|
return { added: [], note: `${err.message}. ${manual}` };
|
|
6519
7600
|
}
|
|
@@ -6523,15 +7604,6 @@ function gitignorePath(cwd, filePath) {
|
|
|
6523
7604
|
return path16__namespace.relative(cwd, filePath).split(path16__namespace.sep).join("/");
|
|
6524
7605
|
}
|
|
6525
7606
|
|
|
6526
|
-
// src/version.ts
|
|
6527
|
-
var GENERATOR_NAME = "codebase-snapshot";
|
|
6528
|
-
var GENERATOR_VERSION = "0.9.16";
|
|
6529
|
-
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
6530
|
-
function isOurGeneratorName(name) {
|
|
6531
|
-
if (typeof name !== "string") return false;
|
|
6532
|
-
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
6533
|
-
}
|
|
6534
|
-
|
|
6535
7607
|
// src/wizard/config-template.ts
|
|
6536
7608
|
var DEFAULT_ANSWERS = {
|
|
6537
7609
|
maxPartBytes: "300k",
|
|
@@ -6836,7 +7908,7 @@ function keyReader(input) {
|
|
|
6836
7908
|
next() {
|
|
6837
7909
|
const queued = queue.shift();
|
|
6838
7910
|
if (queued) return Promise.resolve(queued);
|
|
6839
|
-
return new Promise((
|
|
7911
|
+
return new Promise((resolve11) => waiters.push(resolve11));
|
|
6840
7912
|
},
|
|
6841
7913
|
close() {
|
|
6842
7914
|
input.off("keypress", onKey);
|
|
@@ -7062,7 +8134,7 @@ function parsePackageJson(raw) {
|
|
|
7062
8134
|
}
|
|
7063
8135
|
function readPackageJson(cwd) {
|
|
7064
8136
|
try {
|
|
7065
|
-
return parsePackageJson(
|
|
8137
|
+
return parsePackageJson(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
|
|
7066
8138
|
} catch {
|
|
7067
8139
|
return null;
|
|
7068
8140
|
}
|
|
@@ -7099,7 +8171,7 @@ function artifactAnswers(options) {
|
|
|
7099
8171
|
}
|
|
7100
8172
|
function topLevelDirs(cwd) {
|
|
7101
8173
|
try {
|
|
7102
|
-
return
|
|
8174
|
+
return fs15__namespace.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
|
|
7103
8175
|
} catch {
|
|
7104
8176
|
return [];
|
|
7105
8177
|
}
|
|
@@ -7112,10 +8184,38 @@ function describeJsonValue(value) {
|
|
|
7112
8184
|
}
|
|
7113
8185
|
function writeFileOrExplain(target, content) {
|
|
7114
8186
|
try {
|
|
7115
|
-
|
|
8187
|
+
let stats = null;
|
|
8188
|
+
try {
|
|
8189
|
+
stats = fs15__namespace.lstatSync(target);
|
|
8190
|
+
} catch {
|
|
8191
|
+
stats = null;
|
|
8192
|
+
}
|
|
8193
|
+
if (stats !== null && stats.isSymbolicLink()) {
|
|
8194
|
+
throw new Error(
|
|
8195
|
+
`Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
|
|
8196
|
+
);
|
|
8197
|
+
}
|
|
8198
|
+
if (stats !== null && !stats.isFile()) {
|
|
8199
|
+
throw new Error(
|
|
8200
|
+
`Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
|
|
8201
|
+
);
|
|
8202
|
+
}
|
|
8203
|
+
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
8204
|
+
fs15__namespace.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
|
|
8205
|
+
try {
|
|
8206
|
+
fs15__namespace.renameSync(temporary, target);
|
|
8207
|
+
} catch (err) {
|
|
8208
|
+
try {
|
|
8209
|
+
fs15__namespace.unlinkSync(temporary);
|
|
8210
|
+
} catch {
|
|
8211
|
+
}
|
|
8212
|
+
throw err;
|
|
8213
|
+
}
|
|
7116
8214
|
} catch (err) {
|
|
8215
|
+
const message = err.message;
|
|
8216
|
+
if (message.startsWith(`Cannot write ${target}:`)) throw err;
|
|
7117
8217
|
const code = err.code;
|
|
7118
|
-
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" :
|
|
8218
|
+
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
|
|
7119
8219
|
throw new Error(`Cannot write ${target}: ${reason}`);
|
|
7120
8220
|
}
|
|
7121
8221
|
}
|
|
@@ -7159,14 +8259,14 @@ function updatePackageJson(cwd, notes) {
|
|
|
7159
8259
|
scripts: [],
|
|
7160
8260
|
dependency: { name: GENERATOR_NAME, range: null, added: false }
|
|
7161
8261
|
};
|
|
7162
|
-
if (!
|
|
8262
|
+
if (!fs15__namespace.existsSync(packagePath)) {
|
|
7163
8263
|
notes.push("No package.json found, so npm scripts and the devDependency were not added.");
|
|
7164
8264
|
return unchanged;
|
|
7165
8265
|
}
|
|
7166
8266
|
let raw;
|
|
7167
8267
|
let parsed;
|
|
7168
8268
|
try {
|
|
7169
|
-
raw =
|
|
8269
|
+
raw = fs15__namespace.readFileSync(packagePath, "utf8");
|
|
7170
8270
|
parsed = parsePackageJson(raw);
|
|
7171
8271
|
} catch {
|
|
7172
8272
|
notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
|
|
@@ -7237,7 +8337,7 @@ function updatePackageJson(cwd, notes) {
|
|
|
7237
8337
|
writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
|
|
7238
8338
|
return { scripts: added, dependency };
|
|
7239
8339
|
}
|
|
7240
|
-
var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
|
|
8340
|
+
var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
|
|
7241
8341
|
function resolvePresetChoice(detectedName, presetName) {
|
|
7242
8342
|
return {
|
|
7243
8343
|
value: presetName,
|
|
@@ -7475,7 +8575,7 @@ async function runInit(options) {
|
|
|
7475
8575
|
const configText = renderConfig(answers);
|
|
7476
8576
|
const preferredName = chooseConfigFileName(options.cwd);
|
|
7477
8577
|
const presentConfigs = CONFIG_CANDIDATES.filter(
|
|
7478
|
-
(name) =>
|
|
8578
|
+
(name) => fs15__namespace.existsSync(path16__namespace.join(options.cwd, name))
|
|
7479
8579
|
);
|
|
7480
8580
|
const present = presentConfigs[0] ?? null;
|
|
7481
8581
|
if (presentConfigs.length > 1) {
|
|
@@ -7518,7 +8618,7 @@ async function runInit(options) {
|
|
|
7518
8618
|
'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.'
|
|
7519
8619
|
);
|
|
7520
8620
|
}
|
|
7521
|
-
if (
|
|
8621
|
+
if (fs15__namespace.existsSync(configPath) && !options.force && !reused) {
|
|
7522
8622
|
throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
|
|
7523
8623
|
}
|
|
7524
8624
|
if (!reused) writeFileOrExplain(configPath, configText);
|
|
@@ -7541,10 +8641,10 @@ async function runInit(options) {
|
|
|
7541
8641
|
};
|
|
7542
8642
|
}
|
|
7543
8643
|
function describeTarget(cwd) {
|
|
7544
|
-
const
|
|
7545
|
-
if (
|
|
7546
|
-
if (
|
|
7547
|
-
return
|
|
8644
|
+
const relative14 = path16__namespace.relative(process.cwd(), cwd);
|
|
8645
|
+
if (relative14 === "") return "this directory";
|
|
8646
|
+
if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14)) return cwd;
|
|
8647
|
+
return relative14;
|
|
7548
8648
|
}
|
|
7549
8649
|
function firstRunMessage(reason, cwd) {
|
|
7550
8650
|
const where = describeTarget(cwd);
|
|
@@ -7567,7 +8667,7 @@ function planFirstRun(facts) {
|
|
|
7567
8667
|
var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
|
|
7568
8668
|
function isEffectivelyEmpty(cwd) {
|
|
7569
8669
|
try {
|
|
7570
|
-
return
|
|
8670
|
+
return fs15__namespace.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
|
|
7571
8671
|
} catch {
|
|
7572
8672
|
return false;
|
|
7573
8673
|
}
|
|
@@ -7575,7 +8675,7 @@ function isEffectivelyEmpty(cwd) {
|
|
|
7575
8675
|
function hasPriorSnapshot(cwd, outDir) {
|
|
7576
8676
|
let parsed;
|
|
7577
8677
|
try {
|
|
7578
|
-
parsed = JSON.parse(
|
|
8678
|
+
parsed = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
|
|
7579
8679
|
} catch {
|
|
7580
8680
|
return false;
|
|
7581
8681
|
}
|
|
@@ -7640,68 +8740,6 @@ async function runWithStdoutCapture(fn) {
|
|
|
7640
8740
|
release();
|
|
7641
8741
|
}
|
|
7642
8742
|
}
|
|
7643
|
-
function hasCollapsibleBody(node) {
|
|
7644
|
-
if (!("body" in node)) return false;
|
|
7645
|
-
const body = node.body;
|
|
7646
|
-
return body !== void 0 && ts__default.default.isBlock(body);
|
|
7647
|
-
}
|
|
7648
|
-
function scriptKindFor(fileName) {
|
|
7649
|
-
const lower = fileName.toLowerCase();
|
|
7650
|
-
if (lower.endsWith(".tsx")) return ts__default.default.ScriptKind.TSX;
|
|
7651
|
-
if (lower.endsWith(".jsx")) return ts__default.default.ScriptKind.JSX;
|
|
7652
|
-
if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) {
|
|
7653
|
-
return ts__default.default.ScriptKind.JS;
|
|
7654
|
-
}
|
|
7655
|
-
return ts__default.default.ScriptKind.TS;
|
|
7656
|
-
}
|
|
7657
|
-
function skeletonizeTypeScript(source, fileName = "file.ts") {
|
|
7658
|
-
const sourceFile = ts__default.default.createSourceFile(
|
|
7659
|
-
fileName,
|
|
7660
|
-
source,
|
|
7661
|
-
ts__default.default.ScriptTarget.Latest,
|
|
7662
|
-
// `setParentNodes: false`. Nothing here reads `.parent` — the one `getStart` call is given the
|
|
7663
|
-
// source file explicitly, which is the reason that argument exists. Asking for parent pointers
|
|
7664
|
-
// makes the parser run a second full pass over every node in the file to set them, on top of
|
|
7665
|
-
// the summary parse this same file already pays for.
|
|
7666
|
-
false,
|
|
7667
|
-
scriptKindFor(fileName)
|
|
7668
|
-
);
|
|
7669
|
-
const spans = [];
|
|
7670
|
-
const visit = (node) => {
|
|
7671
|
-
if ((ts__default.default.isFunctionDeclaration(node) || ts__default.default.isMethodDeclaration(node) || ts__default.default.isConstructorDeclaration(node) || ts__default.default.isGetAccessorDeclaration(node) || ts__default.default.isSetAccessorDeclaration(node) || ts__default.default.isFunctionExpression(node) || ts__default.default.isArrowFunction(node)) && hasCollapsibleBody(node)) {
|
|
7672
|
-
const body = node.body;
|
|
7673
|
-
if (body.statements.length > 0) {
|
|
7674
|
-
const start = body.getStart(sourceFile);
|
|
7675
|
-
const end = body.getEnd();
|
|
7676
|
-
if (end > start) spans.push({ start, end });
|
|
7677
|
-
}
|
|
7678
|
-
}
|
|
7679
|
-
ts__default.default.forEachChild(node, visit);
|
|
7680
|
-
};
|
|
7681
|
-
visit(sourceFile);
|
|
7682
|
-
if (spans.length === 0) return { text: source, collapsed: 0 };
|
|
7683
|
-
const outermost = [];
|
|
7684
|
-
for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
|
|
7685
|
-
const last = outermost[outermost.length - 1];
|
|
7686
|
-
if (last && span.start < last.end) continue;
|
|
7687
|
-
outermost.push(span);
|
|
7688
|
-
}
|
|
7689
|
-
const chunks = [];
|
|
7690
|
-
let cursor = 0;
|
|
7691
|
-
for (const span of outermost) {
|
|
7692
|
-
chunks.push(source.slice(cursor, span.start), "{ /* ... */ }");
|
|
7693
|
-
cursor = span.end;
|
|
7694
|
-
}
|
|
7695
|
-
chunks.push(source.slice(cursor));
|
|
7696
|
-
return { text: chunks.join(""), collapsed: outermost.length };
|
|
7697
|
-
}
|
|
7698
|
-
function isSkeletonizable(filePath) {
|
|
7699
|
-
const lower = filePath.toLowerCase();
|
|
7700
|
-
if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
|
|
7701
|
-
return false;
|
|
7702
|
-
}
|
|
7703
|
-
return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts") || lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs");
|
|
7704
|
-
}
|
|
7705
8743
|
|
|
7706
8744
|
// src/generator/audit.ts
|
|
7707
8745
|
function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
@@ -7713,8 +8751,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
7713
8751
|
`**Generated:** ${manifest.generatedAt} `,
|
|
7714
8752
|
`**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
|
|
7715
8753
|
`**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
|
|
7716
|
-
`**
|
|
7717
|
-
`**
|
|
8754
|
+
`**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
|
|
8755
|
+
`**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
|
|
8756
|
+
`**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
|
|
7718
8757
|
// This counts the bytes that were *emitted* after redaction, not the bytes
|
|
7719
8758
|
// that were masked: calling it "redacted bytes" made a repository with zero
|
|
7720
8759
|
// secrets report a non-zero redacted-byte figure directly above "no secrets
|
|
@@ -7754,9 +8793,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
7754
8793
|
const parseIssues = manifest.files.filter(
|
|
7755
8794
|
(file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
|
|
7756
8795
|
);
|
|
8796
|
+
const unparsedPreviews = manifest.files.filter(
|
|
8797
|
+
(file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
|
|
8798
|
+
).length;
|
|
7757
8799
|
lines.push("## 2. Parse & AST Diagnostics", "");
|
|
7758
8800
|
if (parseIssues.length === 0) {
|
|
7759
|
-
|
|
8801
|
+
if (unparsedPreviews > 0) {
|
|
8802
|
+
lines.push(
|
|
8803
|
+
`\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.`,
|
|
8804
|
+
""
|
|
8805
|
+
);
|
|
8806
|
+
} else {
|
|
8807
|
+
lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
|
|
8808
|
+
}
|
|
7760
8809
|
} else {
|
|
7761
8810
|
lines.push(
|
|
7762
8811
|
`${parseIssues.length} file(s) produced an incomplete summary:`,
|
|
@@ -7983,19 +9032,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
7983
9032
|
for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
|
|
7984
9033
|
}
|
|
7985
9034
|
if (groups.length === 0) return [];
|
|
7986
|
-
const
|
|
9035
|
+
const assemblies = /* @__PURE__ */ new Map();
|
|
7987
9036
|
const widthOf = (total) => Math.max(3, String(total).length);
|
|
7988
|
-
const
|
|
7989
|
-
const cached = measurements.get(group);
|
|
9037
|
+
const assemble = (group, index, total) => {
|
|
7990
9038
|
const width = widthOf(total);
|
|
9039
|
+
const cached = assemblies.get(group);
|
|
7991
9040
|
if (cached !== void 0 && cached.index === index && cached.width === width) {
|
|
7992
|
-
return cached.
|
|
9041
|
+
return cached.value;
|
|
7993
9042
|
}
|
|
7994
|
-
const
|
|
7995
|
-
|
|
7996
|
-
|
|
7997
|
-
return size2;
|
|
9043
|
+
const value = assembleGroup(group, index, total, contentFingerprint);
|
|
9044
|
+
assemblies.set(group, { index, width, value });
|
|
9045
|
+
return value;
|
|
7998
9046
|
};
|
|
9047
|
+
const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
|
|
7999
9048
|
for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
|
|
8000
9049
|
const total = groups.length;
|
|
8001
9050
|
let oversized = -1;
|
|
@@ -8006,16 +9055,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
8006
9055
|
break;
|
|
8007
9056
|
}
|
|
8008
9057
|
}
|
|
8009
|
-
if (oversized === -1) return renderGroups(groups, contentFingerprint);
|
|
9058
|
+
if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
|
|
8010
9059
|
const group = groups[oversized];
|
|
8011
9060
|
if (group.sections.length > 1) {
|
|
8012
9061
|
const moved = group.sections.pop();
|
|
8013
9062
|
groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
|
|
8014
|
-
|
|
9063
|
+
assemblies.delete(group);
|
|
8015
9064
|
continue;
|
|
8016
9065
|
}
|
|
8017
9066
|
const [section] = group.sections;
|
|
8018
|
-
if (section === void 0) return renderGroups(groups, contentFingerprint);
|
|
9067
|
+
if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
|
|
8019
9068
|
const overflow = measure(group, oversized, total) - group.budget;
|
|
8020
9069
|
const currentContent = section.file.content ?? "";
|
|
8021
9070
|
const shrinkTo = Math.max(
|
|
@@ -8032,10 +9081,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
8032
9081
|
applyTruncatedContent(section.file, shrunk.content);
|
|
8033
9082
|
section.text = renderFileSection(section.file);
|
|
8034
9083
|
section.byteSize = Buffer.byteLength(section.text, "utf8");
|
|
8035
|
-
|
|
9084
|
+
assemblies.delete(group);
|
|
8036
9085
|
continue;
|
|
8037
9086
|
}
|
|
8038
|
-
const rendered = renderGroups(groups, contentFingerprint);
|
|
9087
|
+
const rendered = renderGroups(groups, contentFingerprint, assemble);
|
|
8039
9088
|
const marker2 = TRUNCATION_MARKER;
|
|
8040
9089
|
assertBudgetHoldsMarker(group.budget);
|
|
8041
9090
|
const target = Math.max(
|
|
@@ -8049,7 +9098,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
8049
9098
|
);
|
|
8050
9099
|
return rendered;
|
|
8051
9100
|
}
|
|
8052
|
-
return renderGroups(groups, contentFingerprint).flatMap(
|
|
9101
|
+
return renderGroups(groups, contentFingerprint, assemble).flatMap(
|
|
8053
9102
|
(part) => enforceBudget([part], part.metadata.budgetBytes)
|
|
8054
9103
|
);
|
|
8055
9104
|
}
|
|
@@ -8223,8 +9272,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
8223
9272
|
for (const section of group.sections) {
|
|
8224
9273
|
section.file.part = filename;
|
|
8225
9274
|
}
|
|
8226
|
-
const layerCounts =
|
|
8227
|
-
const kindCounts =
|
|
9275
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
9276
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
8228
9277
|
for (const section of group.sections) {
|
|
8229
9278
|
layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
|
|
8230
9279
|
kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
|
|
@@ -8259,15 +9308,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
8259
9308
|
const estimatedTokens = estimateTokens(assembled);
|
|
8260
9309
|
return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
|
|
8261
9310
|
}
|
|
8262
|
-
function renderGroups(groups, contentFingerprint) {
|
|
9311
|
+
function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
|
|
8263
9312
|
const total = groups.length;
|
|
8264
9313
|
return groups.map((group, index) => {
|
|
8265
|
-
const { filename, content, estimatedTokens } =
|
|
8266
|
-
group,
|
|
8267
|
-
index,
|
|
8268
|
-
total,
|
|
8269
|
-
contentFingerprint
|
|
8270
|
-
);
|
|
9314
|
+
const { filename, content, estimatedTokens } = assemble(group, index, total);
|
|
8271
9315
|
const byteSize = Buffer.byteLength(content, "utf8");
|
|
8272
9316
|
const sha256 = crypto3__namespace.createHash("sha256").update(content).digest("hex");
|
|
8273
9317
|
const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
|
|
@@ -8484,9 +9528,10 @@ function generateReadme(manifest, artifacts) {
|
|
|
8484
9528
|
`- **Schema Version:** \`${manifest.schemaVersion}\``,
|
|
8485
9529
|
`- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
|
|
8486
9530
|
`- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
|
|
8487
|
-
`- **
|
|
8488
|
-
`- **
|
|
8489
|
-
`- **
|
|
9531
|
+
`- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
|
|
9532
|
+
`- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
|
|
9533
|
+
`- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
9534
|
+
`- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
8490
9535
|
`- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
|
|
8491
9536
|
`- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
|
|
8492
9537
|
"",
|
|
@@ -8604,6 +9649,7 @@ function generateProjectTree(filePaths) {
|
|
|
8604
9649
|
}
|
|
8605
9650
|
var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
|
|
8606
9651
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
9652
|
+
var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
8607
9653
|
var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
8608
9654
|
var REQUEST_TIMEOUT_MS = 1200;
|
|
8609
9655
|
function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
|
|
@@ -8672,23 +9718,24 @@ function shouldCheck(argv, env) {
|
|
|
8672
9718
|
for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
|
|
8673
9719
|
if (args.includes(skip)) return false;
|
|
8674
9720
|
}
|
|
9721
|
+
let format = null;
|
|
8675
9722
|
for (let index = 0; index < args.length; index += 1) {
|
|
8676
9723
|
const argument = args[index];
|
|
9724
|
+
if (argument === "--") break;
|
|
8677
9725
|
if (argument === "--format") {
|
|
8678
|
-
|
|
8679
|
-
|
|
8680
|
-
|
|
8681
|
-
if (argument.startsWith("--format=")) {
|
|
8682
|
-
if (argument.slice("--format=".length) === "json") return false;
|
|
8683
|
-
break;
|
|
9726
|
+
format = args[index + 1] ?? null;
|
|
9727
|
+
index += 1;
|
|
9728
|
+
continue;
|
|
8684
9729
|
}
|
|
9730
|
+
if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
|
|
8685
9731
|
}
|
|
9732
|
+
if (format === "json") return false;
|
|
8686
9733
|
return true;
|
|
8687
9734
|
}
|
|
8688
9735
|
function readCache(file) {
|
|
8689
9736
|
let raw;
|
|
8690
9737
|
try {
|
|
8691
|
-
raw =
|
|
9738
|
+
raw = fs15__namespace.readFileSync(file, "utf8");
|
|
8692
9739
|
} catch {
|
|
8693
9740
|
return null;
|
|
8694
9741
|
}
|
|
@@ -8705,21 +9752,21 @@ function readCache(file) {
|
|
|
8705
9752
|
}
|
|
8706
9753
|
function writeCache(file, entry) {
|
|
8707
9754
|
try {
|
|
8708
|
-
|
|
8709
|
-
|
|
9755
|
+
fs15__namespace.mkdirSync(path16__namespace.dirname(file), { recursive: true });
|
|
9756
|
+
fs15__namespace.writeFileSync(file, `${JSON.stringify(entry)}
|
|
8710
9757
|
`, "utf8");
|
|
8711
9758
|
} catch {
|
|
8712
9759
|
}
|
|
8713
9760
|
}
|
|
8714
9761
|
function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
8715
|
-
return new Promise((
|
|
9762
|
+
return new Promise((resolve11) => {
|
|
8716
9763
|
let settled = false;
|
|
8717
9764
|
let request = null;
|
|
8718
9765
|
const finish = (value) => {
|
|
8719
9766
|
if (settled) return;
|
|
8720
9767
|
settled = true;
|
|
8721
9768
|
clearTimeout(deadline);
|
|
8722
|
-
|
|
9769
|
+
resolve11(value);
|
|
8723
9770
|
};
|
|
8724
9771
|
const deadline = setTimeout(() => {
|
|
8725
9772
|
request?.destroy();
|
|
@@ -8777,7 +9824,8 @@ async function checkForUpdate(options) {
|
|
|
8777
9824
|
needsFetch = age >= FAILURE_INTERVAL_MS;
|
|
8778
9825
|
} else {
|
|
8779
9826
|
latest = cached.latest;
|
|
8780
|
-
|
|
9827
|
+
const interval = isNewer(cached.latest, options.current) ? CHECK_INTERVAL_MS : UP_TO_DATE_INTERVAL_MS;
|
|
9828
|
+
needsFetch = age >= interval;
|
|
8781
9829
|
}
|
|
8782
9830
|
}
|
|
8783
9831
|
if (needsFetch) {
|
|
@@ -8814,9 +9862,17 @@ set -e
|
|
|
8814
9862
|
SNAPSHOT_DIR="${dir}"
|
|
8815
9863
|
|
|
8816
9864
|
if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
|
|
8817
|
-
|
|
8818
|
-
|
|
8819
|
-
|
|
9865
|
+
# Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
|
|
9866
|
+
# renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
|
|
9867
|
+
# failure mode a commit gate must not have. The opt-out is explicit and documented.
|
|
9868
|
+
if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
|
|
9869
|
+
echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
|
|
9870
|
+
exit 0
|
|
9871
|
+
fi
|
|
9872
|
+
echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
|
|
9873
|
+
echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
|
|
9874
|
+
echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
|
|
9875
|
+
exit 1
|
|
8820
9876
|
fi
|
|
8821
9877
|
|
|
8822
9878
|
if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
|
|
@@ -8831,26 +9887,69 @@ function gitDirectory(cwd) {
|
|
|
8831
9887
|
const dotGit = path16__namespace.join(cwd, ".git");
|
|
8832
9888
|
let stats;
|
|
8833
9889
|
try {
|
|
8834
|
-
stats =
|
|
9890
|
+
stats = fs15__namespace.statSync(dotGit);
|
|
8835
9891
|
} catch {
|
|
8836
9892
|
return null;
|
|
8837
9893
|
}
|
|
8838
9894
|
if (stats.isDirectory()) return dotGit;
|
|
8839
9895
|
if (!stats.isFile()) return null;
|
|
8840
9896
|
try {
|
|
8841
|
-
const contents =
|
|
9897
|
+
const contents = fs15__namespace.readFileSync(dotGit, "utf8");
|
|
8842
9898
|
const match = /^gitdir:\s*(.+)$/m.exec(contents);
|
|
8843
9899
|
if (!match) return null;
|
|
8844
9900
|
const target = match[1];
|
|
8845
9901
|
const resolved = path16__namespace.isAbsolute(target.trim()) ? target.trim() : path16__namespace.join(cwd, target.trim());
|
|
8846
|
-
|
|
9902
|
+
if (!fs15__namespace.statSync(resolved).isDirectory()) return null;
|
|
9903
|
+
if (isInside2(path16__namespace.resolve(cwd), path16__namespace.resolve(resolved))) return resolved;
|
|
9904
|
+
return isRegisteredWorktree(path16__namespace.resolve(resolved), cwd) ? resolved : null;
|
|
9905
|
+
} catch {
|
|
9906
|
+
return null;
|
|
9907
|
+
}
|
|
9908
|
+
}
|
|
9909
|
+
function isInside2(parent, child) {
|
|
9910
|
+
const relative14 = path16__namespace.relative(parent, child);
|
|
9911
|
+
return relative14 === "" || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14);
|
|
9912
|
+
}
|
|
9913
|
+
function isRegisteredWorktree(gitDir, cwd) {
|
|
9914
|
+
try {
|
|
9915
|
+
const back = fs15__namespace.readFileSync(path16__namespace.join(gitDir, "gitdir"), "utf8").trim();
|
|
9916
|
+
return path16__namespace.resolve(gitDir, back) === path16__namespace.join(path16__namespace.resolve(cwd), ".git");
|
|
9917
|
+
} catch {
|
|
9918
|
+
return false;
|
|
9919
|
+
}
|
|
9920
|
+
}
|
|
9921
|
+
function gitOutput(cwd, args) {
|
|
9922
|
+
try {
|
|
9923
|
+
const output = childProcess__namespace.execFileSync("git", args, {
|
|
9924
|
+
cwd,
|
|
9925
|
+
encoding: "utf8",
|
|
9926
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
9927
|
+
});
|
|
9928
|
+
const trimmed = output.trim();
|
|
9929
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
8847
9930
|
} catch {
|
|
8848
9931
|
return null;
|
|
8849
9932
|
}
|
|
8850
9933
|
}
|
|
9934
|
+
function configuredHooksDirectory(cwd) {
|
|
9935
|
+
const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
|
|
9936
|
+
if (hooks === null) return null;
|
|
9937
|
+
const resolved = path16__namespace.resolve(cwd, hooks);
|
|
9938
|
+
const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
|
|
9939
|
+
const commonDir = common === null ? null : path16__namespace.resolve(cwd, common);
|
|
9940
|
+
if (isInside2(path16__namespace.resolve(cwd), resolved)) return { dir: resolved };
|
|
9941
|
+
if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
|
|
9942
|
+
return {
|
|
9943
|
+
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.`
|
|
9944
|
+
};
|
|
9945
|
+
}
|
|
8851
9946
|
function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
8852
|
-
const
|
|
8853
|
-
if (
|
|
9947
|
+
const configured = configuredHooksDirectory(cwd);
|
|
9948
|
+
if (configured !== null && "refusal" in configured) {
|
|
9949
|
+
return { path: null, written: false, notes: [configured.refusal] };
|
|
9950
|
+
}
|
|
9951
|
+
const gitDir = configured === null ? gitDirectory(cwd) : null;
|
|
9952
|
+
if (configured === null && gitDir === null) {
|
|
8854
9953
|
return {
|
|
8855
9954
|
path: null,
|
|
8856
9955
|
written: false,
|
|
@@ -8859,10 +9958,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8859
9958
|
]
|
|
8860
9959
|
};
|
|
8861
9960
|
}
|
|
8862
|
-
const hooksDir = path16__namespace.join(gitDir, "hooks");
|
|
9961
|
+
const hooksDir = configured === null ? path16__namespace.join(gitDir, "hooks") : configured.dir;
|
|
8863
9962
|
const hookPath = path16__namespace.join(hooksDir, "pre-commit");
|
|
8864
9963
|
try {
|
|
8865
|
-
|
|
9964
|
+
fs15__namespace.mkdirSync(hooksDir, { recursive: true });
|
|
8866
9965
|
} catch (err) {
|
|
8867
9966
|
return {
|
|
8868
9967
|
path: hookPath,
|
|
@@ -8872,7 +9971,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8872
9971
|
}
|
|
8873
9972
|
let existing = null;
|
|
8874
9973
|
try {
|
|
8875
|
-
existing =
|
|
9974
|
+
existing = fs15__namespace.readFileSync(hookPath, "utf8");
|
|
8876
9975
|
} catch {
|
|
8877
9976
|
existing = null;
|
|
8878
9977
|
}
|
|
@@ -8887,8 +9986,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8887
9986
|
};
|
|
8888
9987
|
}
|
|
8889
9988
|
try {
|
|
8890
|
-
|
|
8891
|
-
|
|
9989
|
+
fs15__namespace.writeFileSync(hookPath, hookScript(outDir), "utf8");
|
|
9990
|
+
fs15__namespace.chmodSync(hookPath, 493);
|
|
8892
9991
|
} catch (err) {
|
|
8893
9992
|
return {
|
|
8894
9993
|
path: hookPath,
|
|
@@ -8945,14 +10044,14 @@ const { parentPort, workerData } = require("node:worker_threads");
|
|
|
8945
10044
|
})();
|
|
8946
10045
|
`;
|
|
8947
10046
|
function generateInWorker(cwd, cliOptions) {
|
|
8948
|
-
return new Promise((
|
|
10047
|
+
return new Promise((resolve11) => {
|
|
8949
10048
|
let settled = false;
|
|
8950
10049
|
let worker = null;
|
|
8951
10050
|
const finish = (result) => {
|
|
8952
10051
|
if (settled) return;
|
|
8953
10052
|
settled = true;
|
|
8954
10053
|
if (worker !== null) void worker.terminate();
|
|
8955
|
-
|
|
10054
|
+
resolve11(result);
|
|
8956
10055
|
};
|
|
8957
10056
|
const isCjs = typeof __dirname !== "undefined";
|
|
8958
10057
|
const directory = isCjs ? __dirname : path16__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
|
|
@@ -8985,7 +10084,6 @@ function generateInWorker(cwd, cliOptions) {
|
|
|
8985
10084
|
}
|
|
8986
10085
|
|
|
8987
10086
|
// src/index.ts
|
|
8988
|
-
var SCHEMA_VERSION = "3.0.0";
|
|
8989
10087
|
var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
|
|
8990
10088
|
var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
|
|
8991
10089
|
var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
@@ -8993,12 +10091,21 @@ var fileDerivationBytes = 0;
|
|
|
8993
10091
|
function takeDerivation(path22, hash, settings) {
|
|
8994
10092
|
const cached = FILE_DERIVATIONS.get(path22);
|
|
8995
10093
|
if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
|
|
10094
|
+
FILE_DERIVATIONS.delete(path22);
|
|
10095
|
+
FILE_DERIVATIONS.set(path22, cached);
|
|
8996
10096
|
return cached;
|
|
8997
10097
|
}
|
|
8998
10098
|
function rememberDerivation(path22, hash, settings, derivation) {
|
|
8999
10099
|
const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
|
|
9000
10100
|
const bytes = bodyBytes * 2 + 512;
|
|
9001
10101
|
if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
|
|
10102
|
+
const previous = FILE_DERIVATIONS.get(path22);
|
|
10103
|
+
if (previous !== void 0) {
|
|
10104
|
+
FILE_DERIVATIONS.delete(path22);
|
|
10105
|
+
fileDerivationBytes -= previous.bytes;
|
|
10106
|
+
} else {
|
|
10107
|
+
FILE_DERIVATIONS.delete(path22);
|
|
10108
|
+
}
|
|
9002
10109
|
while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
|
|
9003
10110
|
const oldest = FILE_DERIVATIONS.keys().next();
|
|
9004
10111
|
if (oldest.done === true) break;
|
|
@@ -9019,11 +10126,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9019
10126
|
const lineCount = countLines(rawContent);
|
|
9020
10127
|
const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
|
|
9021
10128
|
const isLarge = sizeBytes > config.largeFileBytes;
|
|
10129
|
+
const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
|
|
9022
10130
|
let finalContent = redacted;
|
|
9023
10131
|
let isPreviewTruncated = false;
|
|
9024
10132
|
let includedLines = lineCount;
|
|
9025
10133
|
let inclusionMode = "full";
|
|
9026
|
-
if (config.skeleton === true && isSkeletonizable(relativePath)) {
|
|
10134
|
+
if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
|
|
9027
10135
|
const skeleton = skeletonizeTypeScript(redacted, relativePath);
|
|
9028
10136
|
if (skeleton.collapsed > 0) {
|
|
9029
10137
|
finalContent = skeleton.text;
|
|
@@ -9043,7 +10151,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9043
10151
|
let summarySkip = null;
|
|
9044
10152
|
let summaryWarning = null;
|
|
9045
10153
|
let dependentImports = null;
|
|
9046
|
-
if (
|
|
10154
|
+
if (oversizeForSummary) {
|
|
9047
10155
|
summarySkip = "oversize";
|
|
9048
10156
|
dependentImports = [];
|
|
9049
10157
|
} else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
|
|
@@ -9130,8 +10238,8 @@ function retain(items, keep) {
|
|
|
9130
10238
|
}
|
|
9131
10239
|
items.length = write;
|
|
9132
10240
|
}
|
|
9133
|
-
function buildIndexes(files) {
|
|
9134
|
-
const resolver = buildImportResolver(files);
|
|
10241
|
+
function buildIndexes(files, tsconfigPaths) {
|
|
10242
|
+
const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
|
|
9135
10243
|
const importerCounts = /* @__PURE__ */ new Map();
|
|
9136
10244
|
const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
|
|
9137
10245
|
const summary = file.summary;
|
|
@@ -9274,20 +10382,20 @@ function listEntries(dir) {
|
|
|
9274
10382
|
const walk = (absolute, prefix) => {
|
|
9275
10383
|
let children;
|
|
9276
10384
|
try {
|
|
9277
|
-
children =
|
|
10385
|
+
children = fs15__namespace.readdirSync(absolute, { withFileTypes: true });
|
|
9278
10386
|
} catch {
|
|
9279
10387
|
return;
|
|
9280
10388
|
}
|
|
9281
10389
|
for (const child of children) {
|
|
9282
|
-
const
|
|
9283
|
-
entries.push(
|
|
9284
|
-
if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name),
|
|
10390
|
+
const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
|
|
10391
|
+
entries.push(relative14);
|
|
10392
|
+
if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative14);
|
|
9285
10393
|
}
|
|
9286
10394
|
};
|
|
9287
10395
|
walk(dir, "");
|
|
9288
10396
|
return entries.sort();
|
|
9289
10397
|
}
|
|
9290
|
-
function markerInventory(dir) {
|
|
10398
|
+
function markerInventory(dir, written) {
|
|
9291
10399
|
const entries = listEntries(dir);
|
|
9292
10400
|
const files = [];
|
|
9293
10401
|
for (const entry of entries) {
|
|
@@ -9296,14 +10404,19 @@ function markerInventory(dir) {
|
|
|
9296
10404
|
const full = path16__namespace.join(dir, ...entry.split("/"));
|
|
9297
10405
|
let stats;
|
|
9298
10406
|
try {
|
|
9299
|
-
stats =
|
|
10407
|
+
stats = fs15__namespace.lstatSync(full);
|
|
9300
10408
|
} catch {
|
|
9301
10409
|
continue;
|
|
9302
10410
|
}
|
|
9303
10411
|
if (!stats.isFile()) continue;
|
|
10412
|
+
const recorded = written?.get(entry);
|
|
10413
|
+
if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
|
|
10414
|
+
files.push(recorded.digest);
|
|
10415
|
+
continue;
|
|
10416
|
+
}
|
|
9304
10417
|
let digest;
|
|
9305
10418
|
try {
|
|
9306
|
-
digest = sha256Hex2(
|
|
10419
|
+
digest = sha256Hex2(fs15__namespace.readFileSync(full));
|
|
9307
10420
|
} catch {
|
|
9308
10421
|
continue;
|
|
9309
10422
|
}
|
|
@@ -9311,8 +10424,8 @@ function markerInventory(dir) {
|
|
|
9311
10424
|
}
|
|
9312
10425
|
return { entries, files };
|
|
9313
10426
|
}
|
|
9314
|
-
function markerPayload(dir, state, id, createdAt) {
|
|
9315
|
-
const { entries, files } = markerInventory(dir);
|
|
10427
|
+
function markerPayload(dir, state, id, createdAt, written) {
|
|
10428
|
+
const { entries, files } = markerInventory(dir, written);
|
|
9316
10429
|
const marker2 = {
|
|
9317
10430
|
generator: GENERATOR_NAME,
|
|
9318
10431
|
version: GENERATOR_VERSION,
|
|
@@ -9325,13 +10438,13 @@ function markerPayload(dir, state, id, createdAt) {
|
|
|
9325
10438
|
files
|
|
9326
10439
|
};
|
|
9327
10440
|
const manifestPath = path16__namespace.join(dir, "manifest.json");
|
|
9328
|
-
if (
|
|
9329
|
-
marker2.manifestSha256 = sha256Hex2(
|
|
10441
|
+
if (fs15__namespace.existsSync(manifestPath)) {
|
|
10442
|
+
marker2.manifestSha256 = sha256Hex2(fs15__namespace.readFileSync(manifestPath));
|
|
9330
10443
|
}
|
|
9331
10444
|
return marker2;
|
|
9332
10445
|
}
|
|
9333
10446
|
function writeOwnershipMarker(dir, marker2) {
|
|
9334
|
-
|
|
10447
|
+
fs15__namespace.writeFileSync(
|
|
9335
10448
|
path16__namespace.join(dir, OWNERSHIP_MARKER),
|
|
9336
10449
|
`${JSON.stringify(marker2, null, 2)}
|
|
9337
10450
|
`,
|
|
@@ -9345,12 +10458,12 @@ function markerBelongsTo(dir, id) {
|
|
|
9345
10458
|
}
|
|
9346
10459
|
function readOwnershipMarker(dir) {
|
|
9347
10460
|
const markerPath = path16__namespace.join(dir, OWNERSHIP_MARKER);
|
|
9348
|
-
if (!
|
|
10461
|
+
if (!fs15__namespace.existsSync(markerPath)) {
|
|
9349
10462
|
return { marker: null, problem: "it holds no .codebase-snapshot marker" };
|
|
9350
10463
|
}
|
|
9351
10464
|
let raw;
|
|
9352
10465
|
try {
|
|
9353
|
-
raw =
|
|
10466
|
+
raw = fs15__namespace.readFileSync(markerPath, "utf8");
|
|
9354
10467
|
} catch {
|
|
9355
10468
|
return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
|
|
9356
10469
|
}
|
|
@@ -9453,7 +10566,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9453
10566
|
const full = path16__namespace.join(dir, ...entry.split("/"));
|
|
9454
10567
|
let stats;
|
|
9455
10568
|
try {
|
|
9456
|
-
stats =
|
|
10569
|
+
stats = fs15__namespace.lstatSync(full);
|
|
9457
10570
|
} catch {
|
|
9458
10571
|
return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
|
|
9459
10572
|
}
|
|
@@ -9478,7 +10591,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9478
10591
|
}
|
|
9479
10592
|
let digest;
|
|
9480
10593
|
try {
|
|
9481
|
-
digest = sha256Hex2(
|
|
10594
|
+
digest = sha256Hex2(fs15__namespace.readFileSync(full));
|
|
9482
10595
|
} catch {
|
|
9483
10596
|
return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
|
|
9484
10597
|
}
|
|
@@ -9500,11 +10613,11 @@ function assessSnapshotDirectory(dir) {
|
|
|
9500
10613
|
};
|
|
9501
10614
|
}
|
|
9502
10615
|
const manifestPath = path16__namespace.join(dir, "manifest.json");
|
|
9503
|
-
const hasManifest =
|
|
10616
|
+
const hasManifest = fs15__namespace.existsSync(manifestPath);
|
|
9504
10617
|
if (hasManifest) {
|
|
9505
10618
|
let raw;
|
|
9506
10619
|
try {
|
|
9507
|
-
raw =
|
|
10620
|
+
raw = fs15__namespace.readFileSync(manifestPath, "utf8");
|
|
9508
10621
|
} catch {
|
|
9509
10622
|
return {
|
|
9510
10623
|
owned: false,
|
|
@@ -9599,7 +10712,7 @@ function containsNoFiles(dir) {
|
|
|
9599
10712
|
const current = pending.pop();
|
|
9600
10713
|
let entries;
|
|
9601
10714
|
try {
|
|
9602
|
-
entries =
|
|
10715
|
+
entries = fs15__namespace.readdirSync(current, { withFileTypes: true });
|
|
9603
10716
|
} catch {
|
|
9604
10717
|
return false;
|
|
9605
10718
|
}
|
|
@@ -9614,13 +10727,13 @@ function containsNoFiles(dir) {
|
|
|
9614
10727
|
return true;
|
|
9615
10728
|
}
|
|
9616
10729
|
function assertReplaceable(target, label, secretRules) {
|
|
9617
|
-
if (!
|
|
9618
|
-
if (!
|
|
10730
|
+
if (!fs15__namespace.existsSync(target)) return;
|
|
10731
|
+
if (!fs15__namespace.statSync(target).isDirectory()) {
|
|
9619
10732
|
throw new Error(
|
|
9620
10733
|
`Refusing to write into ${label} ${target}: it exists but is not a directory.`
|
|
9621
10734
|
);
|
|
9622
10735
|
}
|
|
9623
|
-
const entries =
|
|
10736
|
+
const entries = fs15__namespace.readdirSync(target);
|
|
9624
10737
|
if (entries.length === 0) return;
|
|
9625
10738
|
if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
|
|
9626
10739
|
if (containsNoFiles(target)) return;
|
|
@@ -9640,18 +10753,18 @@ function assertReplaceable(target, label, secretRules) {
|
|
|
9640
10753
|
);
|
|
9641
10754
|
}
|
|
9642
10755
|
function assertStagingRootUsable(tmpDir, secretRules) {
|
|
9643
|
-
if (!
|
|
9644
|
-
if (!
|
|
10756
|
+
if (!fs15__namespace.existsSync(tmpDir)) return;
|
|
10757
|
+
if (!fs15__namespace.statSync(tmpDir).isDirectory()) {
|
|
9645
10758
|
throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
|
|
9646
10759
|
}
|
|
9647
|
-
const entries =
|
|
10760
|
+
const entries = fs15__namespace.readdirSync(tmpDir);
|
|
9648
10761
|
if (entries.length === 0) return;
|
|
9649
10762
|
const foreign = entries.filter((name) => {
|
|
9650
10763
|
const full = path16__namespace.join(tmpDir, name);
|
|
9651
10764
|
if (!name.startsWith(RUN_DIR_PREFIX)) return true;
|
|
9652
10765
|
let stats;
|
|
9653
10766
|
try {
|
|
9654
|
-
stats =
|
|
10767
|
+
stats = fs15__namespace.statSync(full);
|
|
9655
10768
|
} catch {
|
|
9656
10769
|
return true;
|
|
9657
10770
|
}
|
|
@@ -9659,7 +10772,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9659
10772
|
const { marker: marker2 } = readOwnershipMarker(full);
|
|
9660
10773
|
if (marker2) return false;
|
|
9661
10774
|
try {
|
|
9662
|
-
return
|
|
10775
|
+
return fs15__namespace.readdirSync(full).length > 0;
|
|
9663
10776
|
} catch {
|
|
9664
10777
|
return true;
|
|
9665
10778
|
}
|
|
@@ -9674,7 +10787,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9674
10787
|
function cleanStaleRunDirs(tmpDir) {
|
|
9675
10788
|
let entries;
|
|
9676
10789
|
try {
|
|
9677
|
-
entries =
|
|
10790
|
+
entries = fs15__namespace.readdirSync(tmpDir);
|
|
9678
10791
|
} catch {
|
|
9679
10792
|
return;
|
|
9680
10793
|
}
|
|
@@ -9688,58 +10801,101 @@ function cleanStaleRunDirs(tmpDir) {
|
|
|
9688
10801
|
const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
|
|
9689
10802
|
if (aged || abandoned) {
|
|
9690
10803
|
try {
|
|
9691
|
-
|
|
10804
|
+
fs15__namespace.rmSync(full, { recursive: true, force: true });
|
|
9692
10805
|
} catch {
|
|
9693
10806
|
}
|
|
9694
10807
|
}
|
|
9695
10808
|
continue;
|
|
9696
10809
|
}
|
|
9697
10810
|
try {
|
|
9698
|
-
if (
|
|
10811
|
+
if (fs15__namespace.readdirSync(full).length === 0) fs15__namespace.rmSync(full, { recursive: true, force: true });
|
|
9699
10812
|
} catch {
|
|
9700
10813
|
}
|
|
9701
10814
|
}
|
|
9702
10815
|
}
|
|
9703
10816
|
function removeIfEmpty(dir) {
|
|
9704
10817
|
try {
|
|
9705
|
-
if (
|
|
10818
|
+
if (fs15__namespace.readdirSync(dir).length === 0) fs15__namespace.rmSync(dir, { recursive: true, force: true });
|
|
9706
10819
|
} catch {
|
|
9707
10820
|
}
|
|
9708
10821
|
}
|
|
9709
10822
|
function ensureParentDirectory(target, label) {
|
|
9710
10823
|
const parent = path16__namespace.dirname(target);
|
|
9711
|
-
if (
|
|
10824
|
+
if (fs15__namespace.existsSync(parent) && !fs15__namespace.statSync(parent).isDirectory()) {
|
|
9712
10825
|
throw new Error(
|
|
9713
10826
|
`Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
|
|
9714
10827
|
);
|
|
9715
10828
|
}
|
|
9716
10829
|
try {
|
|
9717
|
-
|
|
10830
|
+
fs15__namespace.mkdirSync(parent, { recursive: true });
|
|
9718
10831
|
} catch (err) {
|
|
9719
10832
|
throw new Error(
|
|
9720
10833
|
`Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
|
|
9721
10834
|
);
|
|
9722
10835
|
}
|
|
9723
10836
|
}
|
|
10837
|
+
var LOCK_HEARTBEAT_MS = 5e3;
|
|
10838
|
+
var LOCK_STALE_HEARTBEAT_MS = 12e4;
|
|
10839
|
+
var LOCK_HEARTBEAT_SOURCE = `
|
|
10840
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
10841
|
+
const fs = require("node:fs");
|
|
10842
|
+
const { lockPath, intervalMs } = workerData;
|
|
10843
|
+
const timer = setInterval(() => {
|
|
10844
|
+
try {
|
|
10845
|
+
const now = new Date();
|
|
10846
|
+
fs.utimesSync(lockPath, now, now);
|
|
10847
|
+
} catch (err) {
|
|
10848
|
+
// The lock was reclaimed or removed; nothing left to keep alive.
|
|
10849
|
+
}
|
|
10850
|
+
}, intervalMs);
|
|
10851
|
+
timer.unref();
|
|
10852
|
+
if (parentPort) {
|
|
10853
|
+
parentPort.on("message", (message) => {
|
|
10854
|
+
if (message === "stop") {
|
|
10855
|
+
clearInterval(timer);
|
|
10856
|
+
process.exit(0);
|
|
10857
|
+
}
|
|
10858
|
+
});
|
|
10859
|
+
}
|
|
10860
|
+
`;
|
|
10861
|
+
function startLockHeartbeat(lockPath) {
|
|
10862
|
+
try {
|
|
10863
|
+
const worker = new worker_threads.Worker(LOCK_HEARTBEAT_SOURCE, {
|
|
10864
|
+
eval: true,
|
|
10865
|
+
workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
|
|
10866
|
+
});
|
|
10867
|
+
worker.unref();
|
|
10868
|
+
return () => {
|
|
10869
|
+
void worker.terminate().catch(() => void 0);
|
|
10870
|
+
};
|
|
10871
|
+
} catch {
|
|
10872
|
+
return () => void 0;
|
|
10873
|
+
}
|
|
10874
|
+
}
|
|
9724
10875
|
function acquireRunLock(stagingRoot) {
|
|
9725
10876
|
const lockPath = lockPathFor(stagingRoot);
|
|
9726
10877
|
const payload = `${JSON.stringify({
|
|
9727
10878
|
pid: process.pid,
|
|
9728
10879
|
stagingRoot,
|
|
10880
|
+
host: os__namespace.hostname(),
|
|
10881
|
+
runId: crypto3__namespace.randomUUID(),
|
|
10882
|
+
heartbeatMs: LOCK_HEARTBEAT_MS,
|
|
9729
10883
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
9730
10884
|
})}
|
|
9731
10885
|
`;
|
|
9732
10886
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9733
10887
|
try {
|
|
9734
|
-
const handle =
|
|
10888
|
+
const handle = fs15__namespace.openSync(lockPath, "wx");
|
|
9735
10889
|
try {
|
|
9736
|
-
|
|
10890
|
+
fs15__namespace.writeSync(handle, payload);
|
|
9737
10891
|
} finally {
|
|
9738
|
-
|
|
10892
|
+
fs15__namespace.closeSync(handle);
|
|
9739
10893
|
}
|
|
10894
|
+
const stopHeartbeat = startLockHeartbeat(lockPath);
|
|
9740
10895
|
return () => {
|
|
10896
|
+
stopHeartbeat();
|
|
9741
10897
|
try {
|
|
9742
|
-
|
|
10898
|
+
fs15__namespace.rmSync(lockPath, { force: true });
|
|
9743
10899
|
} catch {
|
|
9744
10900
|
}
|
|
9745
10901
|
};
|
|
@@ -9747,7 +10903,7 @@ function acquireRunLock(stagingRoot) {
|
|
|
9747
10903
|
if (err.code !== "EEXIST") throw err;
|
|
9748
10904
|
if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
|
|
9749
10905
|
throw new Error(
|
|
9750
|
-
`Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete
|
|
10906
|
+
`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.`
|
|
9751
10907
|
);
|
|
9752
10908
|
}
|
|
9753
10909
|
}
|
|
@@ -9764,7 +10920,7 @@ function canonicalLockTarget(targetPath2) {
|
|
|
9764
10920
|
const tail = [];
|
|
9765
10921
|
for (; ; ) {
|
|
9766
10922
|
try {
|
|
9767
|
-
return path16__namespace.join(
|
|
10923
|
+
return path16__namespace.join(fs15__namespace.realpathSync(existing), ...tail);
|
|
9768
10924
|
} catch {
|
|
9769
10925
|
const parent = path16__namespace.dirname(existing);
|
|
9770
10926
|
if (parent === existing) return resolved;
|
|
@@ -9776,10 +10932,17 @@ function canonicalLockTarget(targetPath2) {
|
|
|
9776
10932
|
function lockPathFor(stagingRoot) {
|
|
9777
10933
|
return path16__namespace.join(os__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
|
|
9778
10934
|
}
|
|
10935
|
+
function lockHeartbeatAgeMs(lockPath) {
|
|
10936
|
+
try {
|
|
10937
|
+
return Date.now() - fs15__namespace.statSync(lockPath).mtimeMs;
|
|
10938
|
+
} catch {
|
|
10939
|
+
return Number.POSITIVE_INFINITY;
|
|
10940
|
+
}
|
|
10941
|
+
}
|
|
9779
10942
|
function lockOwnerIsGone(lockPath) {
|
|
9780
10943
|
let raw;
|
|
9781
10944
|
try {
|
|
9782
|
-
raw =
|
|
10945
|
+
raw = fs15__namespace.readFileSync(lockPath, "utf8");
|
|
9783
10946
|
} catch {
|
|
9784
10947
|
return false;
|
|
9785
10948
|
}
|
|
@@ -9792,96 +10955,120 @@ function lockOwnerIsGone(lockPath) {
|
|
|
9792
10955
|
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
|
|
9793
10956
|
try {
|
|
9794
10957
|
process.kill(pid, 0);
|
|
9795
|
-
return
|
|
10958
|
+
return lockFileIsAncient(lockPath);
|
|
9796
10959
|
} catch (err) {
|
|
9797
|
-
|
|
10960
|
+
if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
|
|
10961
|
+
return true;
|
|
9798
10962
|
}
|
|
9799
10963
|
}
|
|
9800
10964
|
function reclaimStaleLock(lockPath) {
|
|
9801
10965
|
let before;
|
|
9802
10966
|
try {
|
|
9803
|
-
before =
|
|
10967
|
+
before = fs15__namespace.statSync(lockPath);
|
|
9804
10968
|
} catch {
|
|
9805
10969
|
return true;
|
|
9806
10970
|
}
|
|
9807
10971
|
if (!lockOwnerIsGone(lockPath)) return false;
|
|
9808
10972
|
try {
|
|
9809
|
-
const current =
|
|
10973
|
+
const current = fs15__namespace.statSync(lockPath);
|
|
9810
10974
|
const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
|
|
9811
10975
|
if (!sameFile) return false;
|
|
9812
|
-
|
|
10976
|
+
fs15__namespace.rmSync(lockPath, { force: true });
|
|
9813
10977
|
return true;
|
|
9814
10978
|
} catch {
|
|
9815
10979
|
return false;
|
|
9816
10980
|
}
|
|
9817
10981
|
}
|
|
9818
10982
|
function lockFileIsAncient(lockPath) {
|
|
9819
|
-
|
|
9820
|
-
return Date.now() - fs14__namespace.statSync(lockPath).mtimeMs > STALE_RUN_MS;
|
|
9821
|
-
} catch {
|
|
9822
|
-
return false;
|
|
9823
|
-
}
|
|
10983
|
+
return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
|
|
9824
10984
|
}
|
|
9825
10985
|
function writeManifestAtomically(manifestPath, manifest) {
|
|
9826
10986
|
const tempPath = `${manifestPath}.${process.pid}.tmp`;
|
|
9827
|
-
|
|
10987
|
+
fs15__namespace.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
|
|
9828
10988
|
try {
|
|
9829
|
-
|
|
10989
|
+
fs15__namespace.renameSync(tempPath, manifestPath);
|
|
9830
10990
|
} catch (err) {
|
|
9831
10991
|
try {
|
|
9832
|
-
|
|
10992
|
+
fs15__namespace.rmSync(tempPath, { force: true });
|
|
9833
10993
|
} catch {
|
|
9834
10994
|
}
|
|
9835
10995
|
throw err;
|
|
9836
10996
|
}
|
|
9837
10997
|
}
|
|
9838
|
-
function swapIntoPlace(stagingDir, outDir) {
|
|
10998
|
+
function swapIntoPlace(stagingDir, outDir, beforeSwap) {
|
|
9839
10999
|
ensureParentDirectory(outDir, "outDir");
|
|
9840
11000
|
const deadline = Date.now() + 3e3;
|
|
9841
|
-
|
|
11001
|
+
let delay = 25;
|
|
11002
|
+
for (; ; ) {
|
|
9842
11003
|
try {
|
|
9843
|
-
swapOnce(stagingDir, outDir);
|
|
11004
|
+
swapOnce(stagingDir, outDir, beforeSwap);
|
|
9844
11005
|
return;
|
|
9845
11006
|
} catch (err) {
|
|
9846
11007
|
const code = err.code;
|
|
9847
|
-
const
|
|
9848
|
-
|
|
9849
|
-
|
|
11008
|
+
const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
|
|
11009
|
+
const remaining = deadline - Date.now();
|
|
11010
|
+
if (!retryable || remaining <= 0) throw err;
|
|
11011
|
+
sleepSync(Math.min(delay, remaining));
|
|
11012
|
+
delay = Math.min(delay * 2, 400);
|
|
9850
11013
|
}
|
|
9851
11014
|
}
|
|
9852
11015
|
}
|
|
9853
|
-
function
|
|
11016
|
+
function recoverInterruptedPublish(outDir) {
|
|
11017
|
+
if (fs15__namespace.existsSync(outDir)) return;
|
|
11018
|
+
const parent = path16__namespace.dirname(outDir);
|
|
11019
|
+
const base = path16__namespace.basename(outDir);
|
|
11020
|
+
let backups;
|
|
11021
|
+
try {
|
|
11022
|
+
backups = fs15__namespace.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
|
|
11023
|
+
} catch {
|
|
11024
|
+
return;
|
|
11025
|
+
}
|
|
11026
|
+
if (backups.length !== 1) return;
|
|
11027
|
+
const backupDir = path16__namespace.join(parent, backups[0]);
|
|
11028
|
+
const { marker: marker2, problem } = readOwnershipMarker(backupDir);
|
|
11029
|
+
if (problem !== null || marker2 === null || marker2.state !== "complete") return;
|
|
11030
|
+
try {
|
|
11031
|
+
fs15__namespace.renameSync(backupDir, outDir);
|
|
11032
|
+
process.stderr.write(
|
|
11033
|
+
`\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
|
|
11034
|
+
`
|
|
11035
|
+
);
|
|
11036
|
+
} catch {
|
|
11037
|
+
}
|
|
11038
|
+
}
|
|
11039
|
+
function swapOnce(stagingDir, outDir, beforeSwap) {
|
|
9854
11040
|
const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
|
|
9855
|
-
const hadPrevious =
|
|
9856
|
-
if (hadPrevious)
|
|
11041
|
+
const hadPrevious = fs15__namespace.existsSync(outDir);
|
|
11042
|
+
if (hadPrevious) beforeSwap?.();
|
|
11043
|
+
if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
|
|
9857
11044
|
try {
|
|
9858
11045
|
try {
|
|
9859
|
-
|
|
11046
|
+
fs15__namespace.renameSync(stagingDir, outDir);
|
|
9860
11047
|
} catch (err) {
|
|
9861
11048
|
if (err.code !== "EXDEV") throw err;
|
|
9862
11049
|
const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
|
|
9863
11050
|
try {
|
|
9864
|
-
|
|
9865
|
-
|
|
9866
|
-
|
|
11051
|
+
fs15__namespace.cpSync(stagingDir, partialDir, { recursive: true });
|
|
11052
|
+
fs15__namespace.renameSync(partialDir, outDir);
|
|
11053
|
+
fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
|
|
9867
11054
|
} catch (copyErr) {
|
|
9868
11055
|
try {
|
|
9869
|
-
|
|
11056
|
+
fs15__namespace.rmSync(partialDir, { recursive: true, force: true });
|
|
9870
11057
|
} catch {
|
|
9871
11058
|
}
|
|
9872
11059
|
throw copyErr;
|
|
9873
11060
|
}
|
|
9874
11061
|
}
|
|
9875
11062
|
} catch (err) {
|
|
9876
|
-
if (hadPrevious &&
|
|
9877
|
-
if (
|
|
9878
|
-
|
|
11063
|
+
if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
|
|
11064
|
+
if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
|
|
11065
|
+
fs15__namespace.renameSync(backupDir, outDir);
|
|
9879
11066
|
}
|
|
9880
11067
|
throw err;
|
|
9881
11068
|
}
|
|
9882
11069
|
if (hadPrevious) {
|
|
9883
11070
|
try {
|
|
9884
|
-
|
|
11071
|
+
fs15__namespace.rmSync(backupDir, { recursive: true, force: true });
|
|
9885
11072
|
} catch (err) {
|
|
9886
11073
|
process.stderr.write(
|
|
9887
11074
|
`\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.
|
|
@@ -9958,6 +11145,13 @@ function generateSnapshot(configInput, options) {
|
|
|
9958
11145
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
|
|
9959
11146
|
const dryRun = options?.dryRun ?? false;
|
|
9960
11147
|
const gitInfo = getGitInfo(config.cwd, config.branch);
|
|
11148
|
+
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
11149
|
+
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
11150
|
+
...config.staged === true ? { staged: true } : {}
|
|
11151
|
+
}) : null;
|
|
11152
|
+
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
11153
|
+
const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
|
|
11154
|
+
const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
|
|
9961
11155
|
const collection = collectFiles(config.cwd, {
|
|
9962
11156
|
includePatterns: config.include,
|
|
9963
11157
|
excludePatterns: [...config.excludePatterns, ...config.presetExclude],
|
|
@@ -9969,13 +11163,11 @@ function generateSnapshot(configInput, options) {
|
|
|
9969
11163
|
// output — but only at these exact paths, not at every directory that shares the name.
|
|
9970
11164
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
9971
11165
|
(directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
9972
|
-
).filter((
|
|
11166
|
+
).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
|
|
11167
|
+
// A staged path can be absent from the working tree while its index blob exists. Discovery
|
|
11168
|
+
// lists the working tree, so those paths would never reach the scan at all.
|
|
11169
|
+
...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
|
|
9973
11170
|
});
|
|
9974
|
-
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
9975
|
-
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
9976
|
-
...config.staged === true ? { staged: true } : {}
|
|
9977
|
-
}) : null;
|
|
9978
|
-
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
9979
11171
|
const unchangedPaths = [];
|
|
9980
11172
|
const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
|
|
9981
11173
|
if (changedPaths.has(relativePath)) return true;
|
|
@@ -9997,45 +11189,92 @@ function generateSnapshot(configInput, options) {
|
|
|
9997
11189
|
const oversizeSummaryPaths = [];
|
|
9998
11190
|
const previewSummaryPaths = [];
|
|
9999
11191
|
const skippedSummaryImports = /* @__PURE__ */ new Map();
|
|
10000
|
-
const layerCounts =
|
|
10001
|
-
const kindCounts =
|
|
11192
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
11193
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
10002
11194
|
let totalLines = 0;
|
|
10003
11195
|
let totalSizeBytes = 0;
|
|
10004
11196
|
let largeFileCount = 0;
|
|
10005
11197
|
for (const relativePath of candidateFiles) {
|
|
10006
11198
|
const absolutePath = path16__namespace.join(config.cwd, relativePath);
|
|
10007
|
-
|
|
10008
|
-
|
|
10009
|
-
|
|
10010
|
-
|
|
10011
|
-
|
|
10012
|
-
|
|
10013
|
-
|
|
11199
|
+
const fromIndex = stagedPaths.has(relativePath);
|
|
11200
|
+
let buffer;
|
|
11201
|
+
let sizeBytes;
|
|
11202
|
+
if (fromIndex && stagedDeletedPaths.has(relativePath)) {
|
|
11203
|
+
skipped.push({
|
|
11204
|
+
path: relativePath,
|
|
11205
|
+
reason: "deleted",
|
|
11206
|
+
detail: "staged for deletion; it is not part of the next commit"
|
|
11207
|
+
});
|
|
11208
|
+
continue;
|
|
11209
|
+
}
|
|
11210
|
+
if (fromIndex) {
|
|
11211
|
+
const staged = readStagedBlob(config.cwd, relativePath);
|
|
11212
|
+
if (staged === null) {
|
|
11213
|
+
skipped.push({
|
|
11214
|
+
path: relativePath,
|
|
11215
|
+
reason: "deleted",
|
|
11216
|
+
detail: "staged path has no blob in the index; it is not part of the next commit"
|
|
11217
|
+
});
|
|
11218
|
+
continue;
|
|
11219
|
+
}
|
|
11220
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11221
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
|
|
11222
|
+
continue;
|
|
11223
|
+
}
|
|
11224
|
+
buffer = staged;
|
|
11225
|
+
sizeBytes = staged.length;
|
|
11226
|
+
} else {
|
|
11227
|
+
let stats;
|
|
11228
|
+
try {
|
|
11229
|
+
stats = fs15__namespace.statSync(absolutePath);
|
|
11230
|
+
if (!stats.isFile()) {
|
|
11231
|
+
const nestedRepository = stats.isDirectory() && fs15__namespace.existsSync(path16__namespace.join(absolutePath, ".git"));
|
|
11232
|
+
skipped.push(
|
|
11233
|
+
nestedRepository ? {
|
|
11234
|
+
path: relativePath,
|
|
11235
|
+
reason: "nested-repository",
|
|
11236
|
+
detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
|
|
11237
|
+
} : { path: relativePath, reason: "not-file" }
|
|
11238
|
+
);
|
|
11239
|
+
continue;
|
|
11240
|
+
}
|
|
11241
|
+
} catch (err) {
|
|
11242
|
+
const code = err.code;
|
|
11243
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
11244
|
+
skipped.push({
|
|
10014
11245
|
path: relativePath,
|
|
10015
|
-
reason: "
|
|
10016
|
-
detail: "
|
|
10017
|
-
}
|
|
10018
|
-
|
|
11246
|
+
reason: "missing",
|
|
11247
|
+
detail: "tracked but absent from disk (deleted without staging)"
|
|
11248
|
+
});
|
|
11249
|
+
} else {
|
|
11250
|
+
skipped.push({
|
|
11251
|
+
path: relativePath,
|
|
11252
|
+
reason: "read-error",
|
|
11253
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11254
|
+
});
|
|
11255
|
+
}
|
|
10019
11256
|
continue;
|
|
10020
11257
|
}
|
|
10021
|
-
|
|
10022
|
-
|
|
10023
|
-
|
|
10024
|
-
|
|
10025
|
-
|
|
10026
|
-
|
|
10027
|
-
|
|
10028
|
-
|
|
10029
|
-
|
|
10030
|
-
|
|
10031
|
-
|
|
10032
|
-
|
|
10033
|
-
|
|
10034
|
-
|
|
10035
|
-
|
|
10036
|
-
|
|
10037
|
-
|
|
10038
|
-
|
|
11258
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11259
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11260
|
+
continue;
|
|
11261
|
+
}
|
|
11262
|
+
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
|
|
11263
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11264
|
+
continue;
|
|
11265
|
+
}
|
|
11266
|
+
try {
|
|
11267
|
+
buffer = fs15__namespace.readFileSync(absolutePath);
|
|
11268
|
+
} catch (err) {
|
|
11269
|
+
const code = err.code;
|
|
11270
|
+
skipped.push({
|
|
11271
|
+
path: relativePath,
|
|
11272
|
+
reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
|
|
11273
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11274
|
+
});
|
|
11275
|
+
continue;
|
|
11276
|
+
}
|
|
11277
|
+
sizeBytes = stats.size;
|
|
10039
11278
|
}
|
|
10040
11279
|
let decoded;
|
|
10041
11280
|
try {
|
|
@@ -10044,7 +11283,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10044
11283
|
skipped.push({
|
|
10045
11284
|
path: relativePath,
|
|
10046
11285
|
reason: "read-error",
|
|
10047
|
-
detail: `Size: ${
|
|
11286
|
+
detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
|
|
10048
11287
|
/\s+/g,
|
|
10049
11288
|
" "
|
|
10050
11289
|
)
|
|
@@ -10055,13 +11294,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10055
11294
|
skipped.push({
|
|
10056
11295
|
path: relativePath,
|
|
10057
11296
|
reason: "binary",
|
|
10058
|
-
detail: `Size: ${
|
|
11297
|
+
detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
|
|
10059
11298
|
});
|
|
10060
11299
|
continue;
|
|
10061
11300
|
}
|
|
10062
11301
|
const hashSha256 = sha256Hex2(buffer);
|
|
10063
11302
|
const rawContent = decoded.text;
|
|
10064
|
-
totalSizeBytes +=
|
|
11303
|
+
totalSizeBytes += sizeBytes;
|
|
10065
11304
|
if (decoded.encoding !== "utf-8") {
|
|
10066
11305
|
encodingNotes.push({
|
|
10067
11306
|
path: relativePath,
|
|
@@ -10075,7 +11314,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10075
11314
|
bump(layerCounts, layer2);
|
|
10076
11315
|
bump(kindCounts, kind);
|
|
10077
11316
|
const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
|
|
10078
|
-
const fresh = deriveFile(relativePath, rawContent,
|
|
11317
|
+
const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
|
|
10079
11318
|
rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
|
|
10080
11319
|
return fresh;
|
|
10081
11320
|
})();
|
|
@@ -10096,7 +11335,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10096
11335
|
}
|
|
10097
11336
|
files.push({
|
|
10098
11337
|
relativePath,
|
|
10099
|
-
sizeBytes
|
|
11338
|
+
sizeBytes,
|
|
10100
11339
|
lines: lineCount,
|
|
10101
11340
|
hashSha256,
|
|
10102
11341
|
part: "",
|
|
@@ -10117,7 +11356,10 @@ function generateSnapshot(configInput, options) {
|
|
|
10117
11356
|
}
|
|
10118
11357
|
if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
|
|
10119
11358
|
const keep = new Set(changedPaths);
|
|
10120
|
-
const resolver = buildImportResolver(files
|
|
11359
|
+
const resolver = buildImportResolver(files, {
|
|
11360
|
+
extraPaths: changedPaths,
|
|
11361
|
+
tsconfig: tsconfigPathsFor(config.cwd)
|
|
11362
|
+
});
|
|
10121
11363
|
for (const file of files) {
|
|
10122
11364
|
const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
|
|
10123
11365
|
if (fileImports.length === 0) continue;
|
|
@@ -10211,7 +11453,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10211
11453
|
const fingerprint = sha256Hex2(
|
|
10212
11454
|
[
|
|
10213
11455
|
...files.map(
|
|
10214
|
-
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}
|
|
11456
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
10215
11457
|
),
|
|
10216
11458
|
`settings:${configDigest(config)}`
|
|
10217
11459
|
].join("\n")
|
|
@@ -10298,6 +11540,8 @@ function generateSnapshot(configInput, options) {
|
|
|
10298
11540
|
skippedFiles: skipped.length,
|
|
10299
11541
|
totalSourceBytes: totalSizeBytes,
|
|
10300
11542
|
totalContentBytes,
|
|
11543
|
+
sourceLines: totalLines,
|
|
11544
|
+
emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
|
|
10301
11545
|
// The parts are what a model is handed, so the estimate is over the parts rather than
|
|
10302
11546
|
// over the sources: previews and the byte budget both shrink the number.
|
|
10303
11547
|
estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
|
|
@@ -10316,7 +11560,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10316
11560
|
},
|
|
10317
11561
|
layers: layerCounts,
|
|
10318
11562
|
kinds: kindCounts,
|
|
10319
|
-
indexes: buildIndexes(files),
|
|
11563
|
+
indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
|
|
10320
11564
|
parts: parts.map((part) => part.metadata),
|
|
10321
11565
|
files: files.map((file) => {
|
|
10322
11566
|
const { content: _content, ...rest } = file;
|
|
@@ -10333,6 +11577,23 @@ function generateSnapshot(configInput, options) {
|
|
|
10333
11577
|
);
|
|
10334
11578
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10335
11579
|
}
|
|
11580
|
+
if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
|
|
11581
|
+
manifest.warnings.push(
|
|
11582
|
+
`${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.`
|
|
11583
|
+
);
|
|
11584
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11585
|
+
}
|
|
11586
|
+
if (config.maxPartTokens !== void 0) {
|
|
11587
|
+
const overTokenBudget = parts.filter(
|
|
11588
|
+
(part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
|
|
11589
|
+
);
|
|
11590
|
+
if (overTokenBudget.length > 0) {
|
|
11591
|
+
manifest.warnings.push(
|
|
11592
|
+
`${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.`
|
|
11593
|
+
);
|
|
11594
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11595
|
+
}
|
|
11596
|
+
}
|
|
10336
11597
|
if (secretFindings.length > 0 && !config.artifacts.audit) {
|
|
10337
11598
|
manifest.warnings.push(
|
|
10338
11599
|
`${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
|
|
@@ -10361,6 +11622,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10361
11622
|
sha256: sha256Hex2(sarifText)
|
|
10362
11623
|
};
|
|
10363
11624
|
}
|
|
11625
|
+
const artifacts = config.artifacts;
|
|
11626
|
+
const artifactRecord = (text2) => ({
|
|
11627
|
+
byteSize: Buffer.byteLength(text2, "utf8"),
|
|
11628
|
+
sha256: sha256Hex2(text2)
|
|
11629
|
+
});
|
|
11630
|
+
const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
|
|
11631
|
+
if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
|
|
11632
|
+
const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
|
|
11633
|
+
if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
|
|
11634
|
+
const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
|
|
11635
|
+
if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
|
|
11636
|
+
if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
|
|
10364
11637
|
let monolithJson = null;
|
|
10365
11638
|
let monolithMarkdown = null;
|
|
10366
11639
|
if (config.includeMonolith) {
|
|
@@ -10375,26 +11648,33 @@ function generateSnapshot(configInput, options) {
|
|
|
10375
11648
|
includedLines: countLines(content)
|
|
10376
11649
|
};
|
|
10377
11650
|
});
|
|
10378
|
-
const
|
|
10379
|
-
const
|
|
10380
|
-
if (
|
|
11651
|
+
const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
|
|
11652
|
+
const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
|
|
11653
|
+
if (definitelyTooLarge) {
|
|
11654
|
+
const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
|
|
11655
|
+
manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
|
|
11656
|
+
manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
|
|
11657
|
+
}
|
|
11658
|
+
const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
|
|
11659
|
+
const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
|
|
11660
|
+
if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
|
|
10381
11661
|
monolithMarkdown = markdown;
|
|
10382
11662
|
manifest.artifacts.fullMarkdown = {
|
|
10383
11663
|
byteSize: markdownBytes,
|
|
10384
11664
|
sha256: sha256Hex2(markdown)
|
|
10385
11665
|
};
|
|
10386
|
-
} else {
|
|
11666
|
+
} else if (!definitelyTooLarge) {
|
|
10387
11667
|
manifest.warnings.push(
|
|
10388
11668
|
`full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10389
11669
|
);
|
|
10390
11670
|
}
|
|
10391
11671
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10392
|
-
const json = generateMonolithJson(manifest, fullFiles);
|
|
10393
|
-
const jsonBytes = Buffer.byteLength(json, "utf8");
|
|
10394
|
-
if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
|
|
11672
|
+
const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
|
|
11673
|
+
const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
|
|
11674
|
+
if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
|
|
10395
11675
|
monolithJson = json;
|
|
10396
11676
|
manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
|
|
10397
|
-
} else {
|
|
11677
|
+
} else if (!definitelyTooLarge) {
|
|
10398
11678
|
manifest.warnings.push(
|
|
10399
11679
|
`full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10400
11680
|
);
|
|
@@ -10402,7 +11682,6 @@ function generateSnapshot(configInput, options) {
|
|
|
10402
11682
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10403
11683
|
}
|
|
10404
11684
|
const { outDir, tmpDir } = resolveSafeOutputDirs(config);
|
|
10405
|
-
const { artifacts } = config;
|
|
10406
11685
|
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10407
11686
|
assertStagingRootUsable(tmpDir, config.secretRules);
|
|
10408
11687
|
if (dryRun) {
|
|
@@ -10419,15 +11698,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10419
11698
|
const releaseLock = () => {
|
|
10420
11699
|
for (const release of [...releases].reverse()) release();
|
|
10421
11700
|
};
|
|
11701
|
+
recoverInterruptedPublish(outDir);
|
|
11702
|
+
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10422
11703
|
let stagingDir = null;
|
|
11704
|
+
let releaseDeferred = false;
|
|
10423
11705
|
try {
|
|
10424
11706
|
ensureParentDirectory(outDir, "outDir");
|
|
10425
|
-
|
|
11707
|
+
fs15__namespace.mkdirSync(tmpDir, { recursive: true });
|
|
10426
11708
|
cleanStaleRunDirs(tmpDir);
|
|
10427
11709
|
const snapshotId = crypto3__namespace.randomUUID();
|
|
10428
11710
|
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
10429
11711
|
stagingDir = path16__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
|
|
10430
|
-
|
|
11712
|
+
fs15__namespace.mkdirSync(stagingDir);
|
|
10431
11713
|
writeOwnershipMarker(stagingDir, {
|
|
10432
11714
|
generator: GENERATOR_NAME,
|
|
10433
11715
|
version: GENERATOR_VERSION,
|
|
@@ -10439,45 +11721,66 @@ function generateSnapshot(configInput, options) {
|
|
|
10439
11721
|
});
|
|
10440
11722
|
const partsDir = path16__namespace.join(stagingDir, "parts");
|
|
10441
11723
|
const reportsDir = path16__namespace.join(stagingDir, "reports");
|
|
10442
|
-
if (artifacts.parts)
|
|
11724
|
+
if (artifacts.parts) fs15__namespace.mkdirSync(partsDir, { recursive: true });
|
|
10443
11725
|
if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
|
|
10444
|
-
|
|
10445
|
-
}
|
|
11726
|
+
fs15__namespace.mkdirSync(reportsDir, { recursive: true });
|
|
11727
|
+
}
|
|
11728
|
+
const writtenArtifacts = /* @__PURE__ */ new Map();
|
|
11729
|
+
const writeArtifact = (targetDir, relativeEntry, data) => {
|
|
11730
|
+
const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
|
|
11731
|
+
fs15__namespace.writeFileSync(full, data, "utf8");
|
|
11732
|
+
const stats = fs15__namespace.statSync(full);
|
|
11733
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11734
|
+
digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
|
|
11735
|
+
mtimeMs: stats.mtimeMs
|
|
11736
|
+
});
|
|
11737
|
+
};
|
|
11738
|
+
const recordArtifact = (targetDir, relativeEntry) => {
|
|
11739
|
+
const full = path16__namespace.join(targetDir, ...relativeEntry.split("/"));
|
|
11740
|
+
const stats = fs15__namespace.statSync(full);
|
|
11741
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11742
|
+
digest: {
|
|
11743
|
+
path: relativeEntry,
|
|
11744
|
+
bytes: stats.size,
|
|
11745
|
+
sha256: sha256Hex2(fs15__namespace.readFileSync(full))
|
|
11746
|
+
},
|
|
11747
|
+
mtimeMs: stats.mtimeMs
|
|
11748
|
+
});
|
|
11749
|
+
};
|
|
10446
11750
|
if (artifacts.parts) {
|
|
10447
11751
|
for (const part of parts) {
|
|
10448
|
-
|
|
11752
|
+
writeArtifact(partsDir, part.filename, part.markdown);
|
|
10449
11753
|
}
|
|
10450
11754
|
}
|
|
10451
11755
|
if (projectTree !== null) {
|
|
10452
|
-
|
|
11756
|
+
writeArtifact(reportsDir, "project-tree.md", projectTree);
|
|
10453
11757
|
}
|
|
10454
|
-
if (
|
|
10455
|
-
|
|
11758
|
+
if (navigationText !== null) {
|
|
11759
|
+
writeArtifact(reportsDir, "navigation.md", navigationText);
|
|
10456
11760
|
}
|
|
10457
|
-
if (
|
|
10458
|
-
|
|
10459
|
-
path16__namespace.join(reportsDir, "audit.md"),
|
|
10460
|
-
generateAuditReport(manifest, secretFindings, config.secretRules),
|
|
10461
|
-
"utf8"
|
|
10462
|
-
);
|
|
11761
|
+
if (auditText !== null) {
|
|
11762
|
+
writeArtifact(reportsDir, "audit.md", auditText);
|
|
10463
11763
|
}
|
|
10464
11764
|
if (sarifText !== null) {
|
|
10465
|
-
|
|
11765
|
+
writeArtifact(reportsDir, "audit.sarif", sarifText);
|
|
10466
11766
|
}
|
|
10467
|
-
if (
|
|
10468
|
-
|
|
11767
|
+
if (readmeText !== null) {
|
|
11768
|
+
writeArtifact(stagingDir, "README.md", readmeText);
|
|
10469
11769
|
}
|
|
10470
11770
|
if (artifacts.manifest) {
|
|
10471
|
-
|
|
11771
|
+
writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
|
|
10472
11772
|
}
|
|
10473
11773
|
if (monolithJson !== null) {
|
|
10474
|
-
|
|
11774
|
+
writeArtifact(stagingDir, "full-codebase.json", monolithJson);
|
|
10475
11775
|
}
|
|
10476
11776
|
if (monolithMarkdown !== null) {
|
|
10477
|
-
|
|
11777
|
+
writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
|
|
10478
11778
|
}
|
|
10479
|
-
writeOwnershipMarker(
|
|
10480
|
-
|
|
11779
|
+
writeOwnershipMarker(
|
|
11780
|
+
stagingDir,
|
|
11781
|
+
markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11782
|
+
);
|
|
11783
|
+
swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
|
|
10481
11784
|
stagingDir = null;
|
|
10482
11785
|
const warningsBeforeHook = manifest.warnings.length;
|
|
10483
11786
|
const pendingHook = runAfterGenerate(config, manifest);
|
|
@@ -10485,8 +11788,12 @@ function generateSnapshot(configInput, options) {
|
|
|
10485
11788
|
if (!markerBelongsTo(outDir, snapshotId)) return;
|
|
10486
11789
|
if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
|
|
10487
11790
|
writeManifestAtomically(path16__namespace.join(outDir, "manifest.json"), manifest);
|
|
11791
|
+
recordArtifact(outDir, "manifest.json");
|
|
10488
11792
|
}
|
|
10489
|
-
writeOwnershipMarker(
|
|
11793
|
+
writeOwnershipMarker(
|
|
11794
|
+
outDir,
|
|
11795
|
+
markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11796
|
+
);
|
|
10490
11797
|
};
|
|
10491
11798
|
if (config.hooks.afterGenerate) shipHookState();
|
|
10492
11799
|
if (pendingHook) {
|
|
@@ -10513,19 +11820,26 @@ function generateSnapshot(configInput, options) {
|
|
|
10513
11820
|
if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
|
|
10514
11821
|
});
|
|
10515
11822
|
pendingHooks.set(outDir, tracked);
|
|
11823
|
+
releaseDeferred = true;
|
|
11824
|
+
void tracked.finally(() => {
|
|
11825
|
+
removeIfEmpty(tmpDir);
|
|
11826
|
+
releaseLock();
|
|
11827
|
+
});
|
|
10516
11828
|
}
|
|
10517
11829
|
return manifest;
|
|
10518
11830
|
} catch (err) {
|
|
10519
11831
|
if (stagingDir !== null) {
|
|
10520
11832
|
try {
|
|
10521
|
-
|
|
11833
|
+
fs15__namespace.rmSync(stagingDir, { recursive: true, force: true });
|
|
10522
11834
|
} catch {
|
|
10523
11835
|
}
|
|
10524
11836
|
}
|
|
10525
11837
|
throw err;
|
|
10526
11838
|
} finally {
|
|
10527
|
-
|
|
10528
|
-
|
|
11839
|
+
if (!releaseDeferred) {
|
|
11840
|
+
removeIfEmpty(tmpDir);
|
|
11841
|
+
releaseLock();
|
|
11842
|
+
}
|
|
10529
11843
|
}
|
|
10530
11844
|
}
|
|
10531
11845
|
var pendingHooks = /* @__PURE__ */ new Map();
|
|
@@ -10639,12 +11953,12 @@ function foldForComparison(value) {
|
|
|
10639
11953
|
function canonicalPath(value) {
|
|
10640
11954
|
const absolute = path16__namespace.resolve(value);
|
|
10641
11955
|
try {
|
|
10642
|
-
return
|
|
11956
|
+
return fs15__namespace.realpathSync(absolute);
|
|
10643
11957
|
} catch {
|
|
10644
11958
|
return absolute;
|
|
10645
11959
|
}
|
|
10646
11960
|
}
|
|
10647
|
-
function
|
|
11961
|
+
function isInside3(parent, child) {
|
|
10648
11962
|
const foldedParent = foldForComparison(parent);
|
|
10649
11963
|
const foldedChild = foldForComparison(child);
|
|
10650
11964
|
return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path16__namespace.sep}`);
|
|
@@ -10652,7 +11966,7 @@ function isInside2(parent, child) {
|
|
|
10652
11966
|
function resolveThroughExistingAncestor(target) {
|
|
10653
11967
|
let existing = target;
|
|
10654
11968
|
const missing = [];
|
|
10655
|
-
while (!
|
|
11969
|
+
while (!fs15__namespace.existsSync(existing)) {
|
|
10656
11970
|
missing.unshift(path16__namespace.basename(existing));
|
|
10657
11971
|
const parent = path16__namespace.dirname(existing);
|
|
10658
11972
|
if (parent === existing) break;
|
|
@@ -10669,7 +11983,7 @@ function resolveRoot(requested, context) {
|
|
|
10669
11983
|
const absolute = path16__namespace.resolve(context.cwd, wanted);
|
|
10670
11984
|
let stats;
|
|
10671
11985
|
try {
|
|
10672
|
-
stats =
|
|
11986
|
+
stats = fs15__namespace.statSync(absolute);
|
|
10673
11987
|
} catch {
|
|
10674
11988
|
return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
|
|
10675
11989
|
}
|
|
@@ -10678,7 +11992,7 @@ function resolveRoot(requested, context) {
|
|
|
10678
11992
|
}
|
|
10679
11993
|
const resolved = canonicalPath(absolute);
|
|
10680
11994
|
for (const allowed of context.roots) {
|
|
10681
|
-
if (
|
|
11995
|
+
if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
|
|
10682
11996
|
}
|
|
10683
11997
|
const shown = context.roots.join(", ");
|
|
10684
11998
|
return {
|
|
@@ -10686,8 +12000,8 @@ function resolveRoot(requested, context) {
|
|
|
10686
12000
|
message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
|
|
10687
12001
|
};
|
|
10688
12002
|
}
|
|
10689
|
-
async function openWorkspace(root, overrides = {}, allowedRoots) {
|
|
10690
|
-
const loaded = await loadConfigFileDetailed(root);
|
|
12003
|
+
async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
|
|
12004
|
+
const loaded = await loadConfigFileDetailed(root, options);
|
|
10691
12005
|
if (loaded.errors.length > 0) {
|
|
10692
12006
|
return {
|
|
10693
12007
|
ok: false,
|
|
@@ -10722,7 +12036,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
|
|
|
10722
12036
|
const requested = overrides.outDir.trim();
|
|
10723
12037
|
const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
|
|
10724
12038
|
const resolved = resolveThroughExistingAncestor(path16__namespace.resolve(root, requested));
|
|
10725
|
-
if (!permitted.some((allowed) =>
|
|
12039
|
+
if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
|
|
10726
12040
|
const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
|
|
10727
12041
|
return {
|
|
10728
12042
|
ok: false,
|
|
@@ -10751,6 +12065,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots) {
|
|
|
10751
12065
|
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
10752
12066
|
}
|
|
10753
12067
|
}
|
|
12068
|
+
var MANIFEST_CACHE_LIMIT = 8;
|
|
10754
12069
|
var manifestCache = /* @__PURE__ */ new Map();
|
|
10755
12070
|
function manifestPathFor(workspace) {
|
|
10756
12071
|
return path16__namespace.resolve(workspace.root, workspace.config.outDir, "manifest.json");
|
|
@@ -10759,8 +12074,20 @@ function partPathFor(workspace, filename) {
|
|
|
10759
12074
|
if (filename.length === 0 || filename.includes("\0")) return null;
|
|
10760
12075
|
const partsDir = path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
|
|
10761
12076
|
const resolved = path16__namespace.resolve(partsDir, filename);
|
|
10762
|
-
const
|
|
10763
|
-
if (
|
|
12077
|
+
const relative14 = path16__namespace.relative(partsDir, resolved);
|
|
12078
|
+
if (relative14.length === 0 || relative14.includes(path16__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path16__namespace.isAbsolute(relative14)) {
|
|
12079
|
+
return null;
|
|
12080
|
+
}
|
|
12081
|
+
let stats;
|
|
12082
|
+
try {
|
|
12083
|
+
stats = fs15__namespace.lstatSync(resolved);
|
|
12084
|
+
} catch {
|
|
12085
|
+
return null;
|
|
12086
|
+
}
|
|
12087
|
+
if (!stats.isFile()) return null;
|
|
12088
|
+
try {
|
|
12089
|
+
if (path16__namespace.dirname(fs15__namespace.realpathSync(resolved)) !== fs15__namespace.realpathSync(partsDir)) return null;
|
|
12090
|
+
} catch {
|
|
10764
12091
|
return null;
|
|
10765
12092
|
}
|
|
10766
12093
|
return resolved;
|
|
@@ -10770,7 +12097,7 @@ function readManifest3(workspace) {
|
|
|
10770
12097
|
const shown = path16__namespace.relative(workspace.root, file).split(path16__namespace.sep).join("/") || file;
|
|
10771
12098
|
let stats;
|
|
10772
12099
|
try {
|
|
10773
|
-
stats =
|
|
12100
|
+
stats = fs15__namespace.statSync(file);
|
|
10774
12101
|
} catch {
|
|
10775
12102
|
return {
|
|
10776
12103
|
ok: false,
|
|
@@ -10779,12 +12106,12 @@ function readManifest3(workspace) {
|
|
|
10779
12106
|
};
|
|
10780
12107
|
}
|
|
10781
12108
|
const cached = manifestCache.get(file);
|
|
10782
|
-
if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
|
|
12109
|
+
if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
|
|
10783
12110
|
return { ok: true, manifest: cached.manifest, file };
|
|
10784
12111
|
}
|
|
10785
12112
|
let raw;
|
|
10786
12113
|
try {
|
|
10787
|
-
raw =
|
|
12114
|
+
raw = fs15__namespace.readFileSync(file, "utf8");
|
|
10788
12115
|
} catch (error) {
|
|
10789
12116
|
return {
|
|
10790
12117
|
ok: false,
|
|
@@ -10803,7 +12130,18 @@ function readManifest3(workspace) {
|
|
|
10803
12130
|
return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
|
|
10804
12131
|
}
|
|
10805
12132
|
const manifest = parsed;
|
|
10806
|
-
manifestCache.
|
|
12133
|
+
manifestCache.delete(file);
|
|
12134
|
+
manifestCache.set(file, {
|
|
12135
|
+
mtimeMs: stats.mtimeMs,
|
|
12136
|
+
ctimeMs: stats.ctimeMs,
|
|
12137
|
+
size: stats.size,
|
|
12138
|
+
manifest
|
|
12139
|
+
});
|
|
12140
|
+
while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
|
|
12141
|
+
const oldest = manifestCache.keys().next().value;
|
|
12142
|
+
if (oldest === void 0) break;
|
|
12143
|
+
manifestCache.delete(oldest);
|
|
12144
|
+
}
|
|
10807
12145
|
return { ok: true, manifest, file };
|
|
10808
12146
|
}
|
|
10809
12147
|
function forgetManifest(file) {
|
|
@@ -10906,11 +12244,11 @@ function toRelativePath(root, value) {
|
|
|
10906
12244
|
if (cleaned.length === 0 || cleaned.includes("\0")) return null;
|
|
10907
12245
|
const resolvedRoot = path16__namespace.resolve(root);
|
|
10908
12246
|
const absolute = path16__namespace.resolve(resolvedRoot, cleaned);
|
|
10909
|
-
const
|
|
10910
|
-
if (
|
|
12247
|
+
const relative14 = path16__namespace.relative(resolvedRoot, absolute);
|
|
12248
|
+
if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
|
|
10911
12249
|
return null;
|
|
10912
12250
|
}
|
|
10913
|
-
return
|
|
12251
|
+
return relative14.split(path16__namespace.sep).join("/");
|
|
10914
12252
|
}
|
|
10915
12253
|
function symbolsOf(entry) {
|
|
10916
12254
|
const summary = entry.summary;
|
|
@@ -10951,7 +12289,9 @@ function symbolsOf(entry) {
|
|
|
10951
12289
|
async function prepare(args, context, overrides = {}) {
|
|
10952
12290
|
const rootOutcome = resolveRoot(args.root, context);
|
|
10953
12291
|
if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
|
|
10954
|
-
const opened = await openWorkspace(rootOutcome.root, overrides, context.roots
|
|
12292
|
+
const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
|
|
12293
|
+
allowExecutableConfig: false
|
|
12294
|
+
});
|
|
10955
12295
|
if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
|
|
10956
12296
|
return { ok: true, workspace: opened.workspace };
|
|
10957
12297
|
}
|
|
@@ -11307,10 +12647,12 @@ var locateTool = {
|
|
|
11307
12647
|
else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
|
|
11308
12648
|
}
|
|
11309
12649
|
if (wants("route")) {
|
|
12650
|
+
const matchedPaths = new Set(matches.map((match) => match.path));
|
|
11310
12651
|
for (const route of manifest.indexes.routes) {
|
|
11311
12652
|
const method = route.methods.find((name) => name.toLowerCase().includes(needle));
|
|
11312
12653
|
if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
|
|
11313
|
-
if (
|
|
12654
|
+
if (matchedPaths.has(route.path)) continue;
|
|
12655
|
+
matchedPaths.add(route.path);
|
|
11314
12656
|
matches.push({
|
|
11315
12657
|
path: route.path,
|
|
11316
12658
|
part: route.part,
|
|
@@ -11503,7 +12845,9 @@ var readTool = {
|
|
|
11503
12845
|
fromLine: { type: "integer" },
|
|
11504
12846
|
returnedLines: { type: "integer" },
|
|
11505
12847
|
totalLines: { type: "integer" },
|
|
11506
|
-
nextFromLine: { type: "integer" }
|
|
12848
|
+
nextFromLine: { type: "integer" },
|
|
12849
|
+
pageable: { type: "boolean" },
|
|
12850
|
+
reason: { type: "string" }
|
|
11507
12851
|
}
|
|
11508
12852
|
},
|
|
11509
12853
|
annotations: READ_ONLY,
|
|
@@ -11542,7 +12886,7 @@ var readTool = {
|
|
|
11542
12886
|
}
|
|
11543
12887
|
let partText;
|
|
11544
12888
|
try {
|
|
11545
|
-
partText =
|
|
12889
|
+
partText = fs15__namespace.readFileSync(partPath, "utf8");
|
|
11546
12890
|
} catch {
|
|
11547
12891
|
return failure(
|
|
11548
12892
|
`${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
|
|
@@ -11559,15 +12903,20 @@ var readTool = {
|
|
|
11559
12903
|
const window = windowText(section.body, fromLine, lineCount);
|
|
11560
12904
|
let body = window.text;
|
|
11561
12905
|
let truncatedByBytes = false;
|
|
12906
|
+
let clippedInsideLine = false;
|
|
11562
12907
|
if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
|
|
11563
12908
|
const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
|
|
11564
|
-
|
|
11565
|
-
|
|
11566
|
-
|
|
12909
|
+
const lastBreak = clipped.content.lastIndexOf("\n");
|
|
12910
|
+
if (lastBreak > 0) {
|
|
12911
|
+
body = clipped.content.slice(0, lastBreak);
|
|
12912
|
+
} else {
|
|
12913
|
+
body = clipped.content;
|
|
12914
|
+
clippedInsideLine = true;
|
|
12915
|
+
}
|
|
11567
12916
|
truncatedByBytes = true;
|
|
11568
12917
|
}
|
|
11569
12918
|
const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
|
|
11570
|
-
const moreRemain = !window.pastEnd && (window.truncated || truncatedByBytes);
|
|
12919
|
+
const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
|
|
11571
12920
|
const header = [
|
|
11572
12921
|
`${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
|
|
11573
12922
|
// The line range is the answer to "where am I in this file", and it is computed from the
|
|
@@ -11581,12 +12930,17 @@ var readTool = {
|
|
|
11581
12930
|
] : section.inclusion === "signatures" ? [
|
|
11582
12931
|
"Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
|
|
11583
12932
|
] : [],
|
|
11584
|
-
window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
|
|
12933
|
+
window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : clippedInsideLine ? `Line ${window.fromLine} of ${window.totalLines}: this line is longer than one result can carry, so this page ends mid-line.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
|
|
11585
12934
|
];
|
|
11586
12935
|
const lines = [...header, "", body];
|
|
11587
12936
|
if (moreRemain) {
|
|
11588
12937
|
const next = window.fromLine + returnedLines;
|
|
11589
12938
|
lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
|
|
12939
|
+
} else if (clippedInsideLine) {
|
|
12940
|
+
lines.push(
|
|
12941
|
+
"",
|
|
12942
|
+
"Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
|
|
12943
|
+
);
|
|
11590
12944
|
}
|
|
11591
12945
|
return {
|
|
11592
12946
|
text: lines.join("\n"),
|
|
@@ -11600,7 +12954,9 @@ var readTool = {
|
|
|
11600
12954
|
fromLine: window.fromLine,
|
|
11601
12955
|
returnedLines,
|
|
11602
12956
|
totalLines: window.totalLines,
|
|
11603
|
-
truncated: moreRemain,
|
|
12957
|
+
truncated: moreRemain || clippedInsideLine,
|
|
12958
|
+
pageable: !clippedInsideLine,
|
|
12959
|
+
...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
|
|
11604
12960
|
nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
|
|
11605
12961
|
sha256: entry.hashSha256
|
|
11606
12962
|
}
|
|
@@ -11758,6 +13114,13 @@ var ERROR_CODES = {
|
|
|
11758
13114
|
* invent a partial one.
|
|
11759
13115
|
*/
|
|
11760
13116
|
resourceTooLarge: -32e3,
|
|
13117
|
+
/**
|
|
13118
|
+
* The server is at its concurrency limit.
|
|
13119
|
+
*
|
|
13120
|
+
* Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
|
|
13121
|
+
* queueing or a dropped request: the caller can retry, and knows why.
|
|
13122
|
+
*/
|
|
13123
|
+
overloaded: -32001,
|
|
11761
13124
|
unsupportedProtocolVersion: -32022
|
|
11762
13125
|
};
|
|
11763
13126
|
var METHOD3 = {
|
|
@@ -11890,13 +13253,14 @@ var COMMAND_OPTION_SCOPE = {
|
|
|
11890
13253
|
"with-dependents",
|
|
11891
13254
|
"cwd",
|
|
11892
13255
|
"out-dir",
|
|
11893
|
-
|
|
13256
|
+
// `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
|
|
13257
|
+
// `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
|
|
13258
|
+
// `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
|
|
13259
|
+
// whole snapshot is partitioned, and none of them changes whether this file is included.
|
|
13260
|
+
// Removed rather than implemented, because a flag that parses and does nothing is the defect
|
|
13261
|
+
// this table exists to prevent.
|
|
11894
13262
|
"large-file-bytes",
|
|
11895
|
-
"max-monolith-bytes",
|
|
11896
|
-
"include-monolith",
|
|
11897
13263
|
"include-sensitive-files",
|
|
11898
|
-
"skip-artifacts",
|
|
11899
|
-
"only-artifacts",
|
|
11900
13264
|
"no-config",
|
|
11901
13265
|
"discovery",
|
|
11902
13266
|
"no-update-check",
|
|
@@ -12244,7 +13608,7 @@ function buildAgentContract() {
|
|
|
12244
13608
|
type: "string",
|
|
12245
13609
|
default: "unset",
|
|
12246
13610
|
appliesTo: optionAppliesTo("max-part-tokens"),
|
|
12247
|
-
summary: "Ceiling on a part expressed in tokens.
|
|
13611
|
+
summary: "Ceiling on a part expressed in tokens. Converted to bytes at 4 bytes/token and enforced as that byte ceiling \u2014 the estimate in manifest.parts[].estimatedTokens is not a hard bound, and a warning names any part whose estimate exceeds it. Minimum 1024."
|
|
12248
13612
|
},
|
|
12249
13613
|
{
|
|
12250
13614
|
flag: "--large-file-bytes",
|
|
@@ -12279,7 +13643,7 @@ function buildAgentContract() {
|
|
|
12279
13643
|
type: "string",
|
|
12280
13644
|
default: "auto",
|
|
12281
13645
|
appliesTo: optionAppliesTo("discovery"),
|
|
12282
|
-
summary: "How files are discovered: auto (git when usable), git (require git), walk (read
|
|
13646
|
+
summary: "How files are discovered: auto (git when usable), git (require git), walk (read .gitignore files directly, including nested ones; the escape hatch for a .git that cannot be listed)."
|
|
12283
13647
|
},
|
|
12284
13648
|
{
|
|
12285
13649
|
flag: "--skip-artifacts",
|
|
@@ -12300,7 +13664,7 @@ function buildAgentContract() {
|
|
|
12300
13664
|
type: "boolean",
|
|
12301
13665
|
default: false,
|
|
12302
13666
|
appliesTo: optionAppliesTo("skeleton"),
|
|
12303
|
-
summary: 'Replace function and method bodies with `{ /* ... */ }` in
|
|
13667
|
+
summary: 'Replace function and method bodies with `{ /* ... */ }` in JS, JSX, TS and TSX files (including .mjs/.cjs; .d.ts files have nothing to collapse), keeping signatures and comments. The part records inclusionMode "signatures" for each file it touched.'
|
|
12304
13668
|
},
|
|
12305
13669
|
{
|
|
12306
13670
|
flag: "--sarif",
|
|
@@ -12414,7 +13778,7 @@ function buildAgentContract() {
|
|
|
12414
13778
|
type: "boolean",
|
|
12415
13779
|
default: false,
|
|
12416
13780
|
appliesTo: optionAppliesTo("autopilot"),
|
|
12417
|
-
summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
|
|
13781
|
+
summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Autopilot chooses the preset and takes no --preset/--include/--exclude/--install-hook: those belong to `setup` or `init`. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
|
|
12418
13782
|
},
|
|
12419
13783
|
{
|
|
12420
13784
|
flag: "--install",
|
|
@@ -12449,7 +13813,7 @@ function buildAgentContract() {
|
|
|
12449
13813
|
type: "boolean",
|
|
12450
13814
|
default: false,
|
|
12451
13815
|
appliesTo: optionAppliesTo("no-update-check"),
|
|
12452
|
-
summary: "Skip the
|
|
13816
|
+
summary: "Skip the check for a newer published version. The check is already skipped when stdout is not a terminal, in CI, in a JSON invocation, and in `mcp`, which makes no network requests."
|
|
12453
13817
|
}
|
|
12454
13818
|
],
|
|
12455
13819
|
presets: PRESETS.map((preset) => ({
|
|
@@ -12754,11 +14118,11 @@ function targetPath(cwd, target) {
|
|
|
12754
14118
|
}
|
|
12755
14119
|
}
|
|
12756
14120
|
function assertWritableInsideRepository(cwd, filePath) {
|
|
12757
|
-
const root =
|
|
14121
|
+
const root = fs15__namespace.realpathSync(cwd);
|
|
12758
14122
|
const shown = path16__namespace.relative(root, filePath) || filePath;
|
|
12759
14123
|
let stat = null;
|
|
12760
14124
|
try {
|
|
12761
|
-
stat =
|
|
14125
|
+
stat = fs15__namespace.lstatSync(filePath);
|
|
12762
14126
|
} catch {
|
|
12763
14127
|
stat = null;
|
|
12764
14128
|
}
|
|
@@ -12774,13 +14138,13 @@ function assertWritableInsideRepository(cwd, filePath) {
|
|
|
12774
14138
|
}
|
|
12775
14139
|
let existing = filePath;
|
|
12776
14140
|
const missing = [];
|
|
12777
|
-
while (!
|
|
14141
|
+
while (!fs15__namespace.existsSync(existing)) {
|
|
12778
14142
|
missing.unshift(path16__namespace.basename(existing));
|
|
12779
14143
|
const parent = path16__namespace.dirname(existing);
|
|
12780
14144
|
if (parent === existing) break;
|
|
12781
14145
|
existing = parent;
|
|
12782
14146
|
}
|
|
12783
|
-
const realAncestor =
|
|
14147
|
+
const realAncestor = fs15__namespace.realpathSync(existing);
|
|
12784
14148
|
const resolved = missing.length === 0 ? realAncestor : path16__namespace.join(realAncestor, ...missing);
|
|
12785
14149
|
if (resolved !== root && !resolved.startsWith(`${root}${path16__namespace.sep}`)) {
|
|
12786
14150
|
throw new Error(
|
|
@@ -12789,17 +14153,17 @@ function assertWritableInsideRepository(cwd, filePath) {
|
|
|
12789
14153
|
}
|
|
12790
14154
|
}
|
|
12791
14155
|
function writeIfChanged(target, filePath, content) {
|
|
12792
|
-
const existing =
|
|
14156
|
+
const existing = fs15__namespace.existsSync(filePath) ? fs15__namespace.readFileSync(filePath, "utf8") : null;
|
|
12793
14157
|
if (existing === content) return { target, path: filePath, action: "unchanged" };
|
|
12794
|
-
|
|
12795
|
-
|
|
14158
|
+
fs15__namespace.mkdirSync(path16__namespace.dirname(filePath), { recursive: true });
|
|
14159
|
+
fs15__namespace.writeFileSync(filePath, content, "utf8");
|
|
12796
14160
|
return { target, path: filePath, action: existing === null ? "created" : "updated" };
|
|
12797
14161
|
}
|
|
12798
14162
|
function legacyAgentsNote(cwd) {
|
|
12799
14163
|
const filePath = path16__namespace.join(cwd, "AGENTS.md");
|
|
12800
14164
|
try {
|
|
12801
|
-
if (!
|
|
12802
|
-
if (!
|
|
14165
|
+
if (!fs15__namespace.existsSync(filePath)) return null;
|
|
14166
|
+
if (!fs15__namespace.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
|
|
12803
14167
|
} catch {
|
|
12804
14168
|
return null;
|
|
12805
14169
|
}
|
|
@@ -12811,7 +14175,7 @@ function installSkill(cwd, target = "all") {
|
|
|
12811
14175
|
const notes = [];
|
|
12812
14176
|
const wanted = target === "all" ? ["claude", "cursor"] : [target];
|
|
12813
14177
|
for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
|
|
12814
|
-
const createsSomething = wanted.some((item) => !
|
|
14178
|
+
const createsSomething = wanted.some((item) => !fs15__namespace.existsSync(targetPath(cwd, item)));
|
|
12815
14179
|
if (createsSomething) {
|
|
12816
14180
|
assertWritableInsideRepository(cwd, path16__namespace.join(cwd, ".gitignore"));
|
|
12817
14181
|
}
|
|
@@ -12968,13 +14332,13 @@ function formatBytes2(bytes) {
|
|
|
12968
14332
|
async function workspaceFor(context) {
|
|
12969
14333
|
const root = resolveRoot(void 0, context);
|
|
12970
14334
|
if (!root.ok) return { error: root.message };
|
|
12971
|
-
const opened = await openWorkspace(root.root);
|
|
14335
|
+
const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
|
|
12972
14336
|
if (!opened.ok) return { error: opened.message };
|
|
12973
14337
|
return opened.workspace;
|
|
12974
14338
|
}
|
|
12975
14339
|
function readFileIfPresent(file) {
|
|
12976
14340
|
try {
|
|
12977
|
-
return
|
|
14341
|
+
return fs15__namespace.readFileSync(file, "utf8");
|
|
12978
14342
|
} catch {
|
|
12979
14343
|
return null;
|
|
12980
14344
|
}
|
|
@@ -13092,7 +14456,7 @@ function buildResourceProvider() {
|
|
|
13092
14456
|
if (partPath === null) return null;
|
|
13093
14457
|
let partBytes;
|
|
13094
14458
|
try {
|
|
13095
|
-
partBytes =
|
|
14459
|
+
partBytes = fs15__namespace.statSync(partPath).size;
|
|
13096
14460
|
} catch {
|
|
13097
14461
|
return null;
|
|
13098
14462
|
}
|
|
@@ -13508,11 +14872,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
|
|
|
13508
14872
|
function createWriter(output) {
|
|
13509
14873
|
return {
|
|
13510
14874
|
write(value) {
|
|
13511
|
-
return new Promise((
|
|
14875
|
+
return new Promise((resolve11, reject) => {
|
|
13512
14876
|
output.write(`${JSON.stringify(value)}
|
|
13513
14877
|
`, (error) => {
|
|
13514
14878
|
if (error) reject(error);
|
|
13515
|
-
else
|
|
14879
|
+
else resolve11();
|
|
13516
14880
|
});
|
|
13517
14881
|
});
|
|
13518
14882
|
}
|
|
@@ -13645,11 +15009,12 @@ async function runStdioServer(options) {
|
|
|
13645
15009
|
});
|
|
13646
15010
|
return writeChain;
|
|
13647
15011
|
};
|
|
15012
|
+
const MAX_IN_FLIGHT = 4;
|
|
13648
15013
|
let inFlight = 0;
|
|
13649
15014
|
let inputEnded = false;
|
|
13650
15015
|
let resolveDone = () => void 0;
|
|
13651
|
-
const finished = new Promise((
|
|
13652
|
-
resolveDone =
|
|
15016
|
+
const finished = new Promise((resolve11) => {
|
|
15017
|
+
resolveDone = resolve11;
|
|
13653
15018
|
});
|
|
13654
15019
|
const finishIfIdle = () => {
|
|
13655
15020
|
if (inputEnded && inFlight === 0) resolveDone(0);
|
|
@@ -13665,9 +15030,31 @@ async function runStdioServer(options) {
|
|
|
13665
15030
|
const response = await server.handle(message);
|
|
13666
15031
|
if (response) await send(response);
|
|
13667
15032
|
};
|
|
15033
|
+
const rejectOverloaded = (line) => {
|
|
15034
|
+
let id = null;
|
|
15035
|
+
try {
|
|
15036
|
+
const parsed = JSON.parse(line);
|
|
15037
|
+
if (!isJsonObject(parsed)) return;
|
|
15038
|
+
if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
|
|
15039
|
+
else return;
|
|
15040
|
+
} catch {
|
|
15041
|
+
return;
|
|
15042
|
+
}
|
|
15043
|
+
void send(
|
|
15044
|
+
errorResponse(
|
|
15045
|
+
id,
|
|
15046
|
+
ERROR_CODES.overloaded,
|
|
15047
|
+
`The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
|
|
15048
|
+
)
|
|
15049
|
+
);
|
|
15050
|
+
};
|
|
13668
15051
|
const stopReading = createLineReader(process.stdin, {
|
|
13669
15052
|
onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
|
|
13670
15053
|
onLine: (line) => {
|
|
15054
|
+
if (inFlight >= MAX_IN_FLIGHT) {
|
|
15055
|
+
rejectOverloaded(line);
|
|
15056
|
+
return;
|
|
15057
|
+
}
|
|
13671
15058
|
inFlight += 1;
|
|
13672
15059
|
void handleLine(line).finally(() => {
|
|
13673
15060
|
inFlight -= 1;
|
|
@@ -13834,7 +15221,7 @@ Options:
|
|
|
13834
15221
|
--install Write the skill into the repository instead of printing
|
|
13835
15222
|
--target <name> claude | cursor | all (default: all)
|
|
13836
15223
|
|
|
13837
|
-
--no-update-check Skip the
|
|
15224
|
+
--no-update-check Skip the check for a newer published version
|
|
13838
15225
|
|
|
13839
15226
|
-h, --help Display this help message
|
|
13840
15227
|
-v, --version Display version
|
|
@@ -13932,10 +15319,10 @@ function parseCliArgs(argv) {
|
|
|
13932
15319
|
}
|
|
13933
15320
|
if (values.cwd !== void 0) {
|
|
13934
15321
|
const target = String(values.cwd);
|
|
13935
|
-
if (!
|
|
15322
|
+
if (!fs15__namespace.existsSync(target)) {
|
|
13936
15323
|
throw new UsageError(`--cwd directory does not exist: ${target}`);
|
|
13937
15324
|
}
|
|
13938
|
-
if (!
|
|
15325
|
+
if (!fs15__namespace.statSync(target).isDirectory()) {
|
|
13939
15326
|
throw new UsageError(`--cwd is not a directory: ${target}`);
|
|
13940
15327
|
}
|
|
13941
15328
|
}
|
|
@@ -14039,7 +15426,9 @@ function parseCliArgs(argv) {
|
|
|
14039
15426
|
)
|
|
14040
15427
|
)
|
|
14041
15428
|
);
|
|
14042
|
-
const
|
|
15429
|
+
const setupOnly = ["--preset", "--include", "--exclude", "--install-hook"];
|
|
15430
|
+
const autopilotChose = values.autopilot === true && ignored.some((flag) => setupOnly.includes(flag));
|
|
15431
|
+
const hint = autopilotChose ? " --autopilot chooses the preset and takes none of these: name them with `setup` (or `init`) instead." : ignored.some((flag) => ["--preset", "--include", "--exclude"].includes(flag)) ? " To scope a run, set include/excludePatterns/preset in snapshot.config.ts (or run `codebase-snapshot init` to generate one)." : "";
|
|
14043
15432
|
throw new UsageError(
|
|
14044
15433
|
`${ignored.join(", ")} ${ignored.length === 1 ? "does" : "do"} not apply to \`${command}\` and ${ignored.length === 1 ? "was" : "were"} not applied. ${ignored.length === 1 ? "It is" : "They are"} accepted by: ${owners.join(", ")}.${hint}`
|
|
14045
15434
|
);
|
|
@@ -14161,8 +15550,8 @@ function splitList(value) {
|
|
|
14161
15550
|
}
|
|
14162
15551
|
function displayOutPath(cwd, outDir, ...segments) {
|
|
14163
15552
|
const absolute = path16__namespace.resolve(cwd, outDir, ...segments);
|
|
14164
|
-
const
|
|
14165
|
-
if (
|
|
15553
|
+
const relative14 = path16__namespace.relative(cwd, absolute);
|
|
15554
|
+
if (relative14 && !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14)) return relative14;
|
|
14166
15555
|
return absolute;
|
|
14167
15556
|
}
|
|
14168
15557
|
function nextStepHint(cwd, scriptsAddedNow) {
|
|
@@ -14170,7 +15559,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
|
|
|
14170
15559
|
if (!hasScript) {
|
|
14171
15560
|
try {
|
|
14172
15561
|
const parsed = JSON.parse(
|
|
14173
|
-
stripJsonComments2(
|
|
15562
|
+
stripJsonComments2(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
|
|
14174
15563
|
);
|
|
14175
15564
|
hasScript = typeof parsed.scripts?.snapshot === "string";
|
|
14176
15565
|
} catch {
|
|
@@ -14179,7 +15568,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
|
|
|
14179
15568
|
}
|
|
14180
15569
|
if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
|
|
14181
15570
|
const bin = path16__namespace.join(cwd, "node_modules", ".bin", "codebase-snapshot");
|
|
14182
|
-
const installed =
|
|
15571
|
+
const installed = fs15__namespace.existsSync(bin) || fs15__namespace.existsSync(`${bin}.cmd`);
|
|
14183
15572
|
return installed ? "npm run snapshot" : "npm install && npm run snapshot";
|
|
14184
15573
|
}
|
|
14185
15574
|
function presetSummary(init) {
|
|
@@ -14236,16 +15625,25 @@ async function runInitCommand(invocation) {
|
|
|
14236
15625
|
}
|
|
14237
15626
|
}
|
|
14238
15627
|
function detectPackageManager(cwd) {
|
|
14239
|
-
const has = (name) =>
|
|
15628
|
+
const has = (name) => fs15__namespace.existsSync(path16__namespace.join(cwd, name));
|
|
14240
15629
|
if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
|
|
14241
15630
|
if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
|
|
14242
15631
|
if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
|
|
14243
15632
|
return { name: "npm", command: "npm", args: ["install"] };
|
|
14244
15633
|
}
|
|
15634
|
+
var INHERITED_NPM_SETTINGS = /* @__PURE__ */ new Set([
|
|
15635
|
+
"npm_config_registry",
|
|
15636
|
+
"npm_config_proxy",
|
|
15637
|
+
"npm_config_https_proxy",
|
|
15638
|
+
"npm_config_noproxy",
|
|
15639
|
+
"npm_config_cafile",
|
|
15640
|
+
"npm_config_ca",
|
|
15641
|
+
"npm_config_strict_ssl"
|
|
15642
|
+
]);
|
|
14245
15643
|
function cleanInstallEnv(env = process.env) {
|
|
14246
15644
|
const cleaned = {};
|
|
14247
15645
|
for (const [key, value] of Object.entries(env)) {
|
|
14248
|
-
if (/^npm_config_/i.test(key)) continue;
|
|
15646
|
+
if (/^npm_config_/i.test(key) && !INHERITED_NPM_SETTINGS.has(key.toLowerCase())) continue;
|
|
14249
15647
|
if (key === "npm_lifecycle_event" || key === "npm_lifecycle_script") continue;
|
|
14250
15648
|
cleaned[key] = value;
|
|
14251
15649
|
}
|
|
@@ -14669,12 +16067,12 @@ ${USAGE}
|
|
|
14669
16067
|
}
|
|
14670
16068
|
if (invocation.command === "report") {
|
|
14671
16069
|
const manifestPath = path16__namespace.resolve(resolved.cwd, resolved.outDir, "manifest.json");
|
|
14672
|
-
if (!
|
|
16070
|
+
if (!fs15__namespace.existsSync(manifestPath)) {
|
|
14673
16071
|
return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
|
|
14674
16072
|
}
|
|
14675
16073
|
let manifest;
|
|
14676
16074
|
try {
|
|
14677
|
-
manifest = JSON.parse(
|
|
16075
|
+
manifest = JSON.parse(fs15__namespace.readFileSync(manifestPath, "utf8"));
|
|
14678
16076
|
} catch (err) {
|
|
14679
16077
|
return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
|
|
14680
16078
|
}
|
|
@@ -14850,8 +16248,8 @@ function comparablePath(value) {
|
|
|
14850
16248
|
return process.platform === "win32" ? absolute.toLowerCase() : absolute;
|
|
14851
16249
|
}
|
|
14852
16250
|
function isSameOrInside(parent, candidate) {
|
|
14853
|
-
const
|
|
14854
|
-
return
|
|
16251
|
+
const relative14 = path16__namespace.relative(parent, candidate);
|
|
16252
|
+
return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path16__namespace.sep}`) && !path16__namespace.isAbsolute(relative14);
|
|
14855
16253
|
}
|
|
14856
16254
|
function isGeneratedWatchPath(candidate, paths) {
|
|
14857
16255
|
const absolute = comparablePath(path16__namespace.resolve(paths.cwd, candidate));
|
|
@@ -14966,7 +16364,7 @@ async function runWatchLoop(invocation, resolved, options) {
|
|
|
14966
16364
|
info("\u{1F440} Watching for changes. Press Ctrl+C to stop.");
|
|
14967
16365
|
let watcher;
|
|
14968
16366
|
try {
|
|
14969
|
-
watcher =
|
|
16367
|
+
watcher = fs15__namespace.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
|
|
14970
16368
|
const decision = decideWatchEvent(
|
|
14971
16369
|
state,
|
|
14972
16370
|
{
|
|
@@ -14996,12 +16394,12 @@ async function runWatchLoop(invocation, resolved, options) {
|
|
|
14996
16394
|
info(`\u26A0 Watch error: ${err.message}`);
|
|
14997
16395
|
info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
|
|
14998
16396
|
});
|
|
14999
|
-
await new Promise((
|
|
16397
|
+
await new Promise((resolve11) => {
|
|
15000
16398
|
const stop = () => {
|
|
15001
16399
|
stopped = true;
|
|
15002
16400
|
if (timer) clearTimeout(timer);
|
|
15003
16401
|
watcher.close();
|
|
15004
|
-
|
|
16402
|
+
resolve11();
|
|
15005
16403
|
};
|
|
15006
16404
|
process.once("SIGINT", stop);
|
|
15007
16405
|
process.once("SIGTERM", stop);
|