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