screw-up 1.31.0 → 1.33.0

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.
Files changed (35) hide show
  1. package/dist/index.cjs +604 -179
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +4 -4
  4. package/dist/main.cjs +620 -195
  5. package/dist/main.cjs.map +1 -1
  6. package/dist/main.mjs +6 -6
  7. package/dist/{metadata-file-BWd04LhD.js → metadata-file-Case8fsm.js} +603 -177
  8. package/dist/metadata-file-Case8fsm.js.map +1 -0
  9. package/dist/{packageMetadata-BsMXJpMH.js → packageMetadata-4rUlIBjt.js} +6 -6
  10. package/dist/{packageMetadata-BsMXJpMH.js.map → packageMetadata-4rUlIBjt.js.map} +1 -1
  11. package/dist/{packageMetadata-BDGBM3Fx.cjs → packageMetadata-CaaD3Ehh.cjs} +3 -3
  12. package/dist/{packageMetadata-ip0rBTwa.cjs → packageMetadata-k_QXJ2PH.cjs} +5 -5
  13. package/dist/{packageMetadata-ip0rBTwa.cjs.map → packageMetadata-k_QXJ2PH.cjs.map} +1 -1
  14. package/dist/src/analyzer.d.ts +2 -2
  15. package/dist/src/analyzer.d.ts.map +1 -1
  16. package/dist/src/cli-internal.d.ts +2 -2
  17. package/dist/src/cli.d.ts +2 -2
  18. package/dist/src/declaration-import-fix.d.ts +2 -2
  19. package/dist/src/default-import-fix.d.ts +2 -2
  20. package/dist/src/fast-tags.d.ts +2 -2
  21. package/dist/src/fast-tags.d.ts.map +1 -1
  22. package/dist/src/generated/packageMetadata.d.ts +4 -4
  23. package/dist/src/git-operations.d.ts +2 -2
  24. package/dist/src/git-operations.d.ts.map +1 -1
  25. package/dist/src/git-ref-utils.d.ts +46 -4
  26. package/dist/src/git-ref-utils.d.ts.map +1 -1
  27. package/dist/src/index.d.ts +2 -2
  28. package/dist/src/internal.d.ts +2 -2
  29. package/dist/src/main.d.ts +2 -2
  30. package/dist/src/metadata-file.d.ts +2 -2
  31. package/dist/src/text-edits.d.ts +2 -2
  32. package/dist/src/types.d.ts +2 -2
  33. package/dist/src/vite-plugin.d.ts +2 -2
  34. package/package.json +8 -8
  35. package/dist/metadata-file-BWd04LhD.js.map +0 -1
package/dist/main.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  /*!
3
3
  * name: screw-up
4
- * version: 1.31.0
4
+ * version: 1.33.0
5
5
  * description: Simply package metadata inserter on Vite plugin
6
6
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
7
7
  * license: MIT
8
8
  * repository.url: https://github.com/kekyo/screw-up.git
9
- * git.commit.hash: ebb41ebf06ebe1bec39a3770c70a62cb95b4b7d6
9
+ * git.commit.hash: be56ff1901b5073e1b0238a28b80d0c4f3c1e894
10
10
  */
11
11
  //#region \0rolldown/runtime.js
12
12
  var __create = Object.create;
@@ -31,11 +31,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  enumerable: true
32
32
  }) : target, mod));
33
33
  //#endregion
34
- const require_packageMetadata = require("./packageMetadata-ip0rBTwa.cjs");
34
+ const require_packageMetadata = require("./packageMetadata-k_QXJ2PH.cjs");
35
35
  let path = require("path");
36
36
  let fs = require("fs");
37
37
  let fs_promises = require("fs/promises");
38
- fs_promises = __toESM(fs_promises);
38
+ fs_promises = __toESM(fs_promises, 1);
39
39
  let child_process = require("child_process");
40
40
  let os = require("os");
41
41
  let stream = require("stream");
@@ -43,7 +43,8 @@ let zlib = require("zlib");
43
43
  let stream_promises = require("stream/promises");
44
44
  let glob = require("glob");
45
45
  let isomorphic_git = require("isomorphic-git");
46
- isomorphic_git = __toESM(isomorphic_git);
46
+ isomorphic_git = __toESM(isomorphic_git, 1);
47
+ let crypto = require("crypto");
47
48
  //#region node_modules/tar-vern/dist/index.js
48
49
  /*!
49
50
  * name: tar-vern
@@ -62,7 +63,7 @@ var getUName = (candidateName, candidateId, reflectStat) => {
62
63
  var getBuffer = (data) => {
63
64
  return Buffer.isBuffer(data) ? data : Buffer.from(data, "utf8");
64
65
  };
65
- var createDirectoryItem = async (path$3, reflectStat, options, signal) => {
66
+ var createDirectoryItem = async (path$8, reflectStat, options, signal) => {
66
67
  const rs = reflectStat !== null && reflectStat !== void 0 ? reflectStat : "none";
67
68
  if (rs !== "none" && (options === null || options === void 0 ? void 0 : options.directoryPath)) {
68
69
  var _options$mode, _options$uid, _options$gid, _options$date;
@@ -74,7 +75,7 @@ var createDirectoryItem = async (path$3, reflectStat, options, signal) => {
74
75
  const date = (_options$date = options === null || options === void 0 ? void 0 : options.date) !== null && _options$date !== void 0 ? _options$date : stats.mtime;
75
76
  return {
76
77
  kind: "directory",
77
- path: path$3,
78
+ path: path$8,
78
79
  mode,
79
80
  uname: getUName(options === null || options === void 0 ? void 0 : options.uname, stats.uid, rs),
80
81
  gname: getUName(options === null || options === void 0 ? void 0 : options.gname, stats.gid, rs),
@@ -90,7 +91,7 @@ var createDirectoryItem = async (path$3, reflectStat, options, signal) => {
90
91
  const date = (_options$date2 = options === null || options === void 0 ? void 0 : options.date) !== null && _options$date2 !== void 0 ? _options$date2 : /* @__PURE__ */ new Date();
91
92
  return {
92
93
  kind: "directory",
93
- path: path$3,
94
+ path: path$8,
94
95
  mode,
95
96
  uname: getUName(options === null || options === void 0 ? void 0 : options.uname, void 0, rs),
96
97
  gname: getUName(options === null || options === void 0 ? void 0 : options.gname, void 0, rs),
@@ -100,7 +101,7 @@ var createDirectoryItem = async (path$3, reflectStat, options, signal) => {
100
101
  };
101
102
  }
102
103
  };
103
- var createReadableFileItem = async (path$5, readable, options, signal) => {
104
+ var createReadableFileItem = async (path$10, readable, options, signal) => {
104
105
  var _options$mode4, _options$uid4, _options$gid4, _options$date4, _options$uname2, _options$gname2;
105
106
  const mode = (_options$mode4 = options === null || options === void 0 ? void 0 : options.mode) !== null && _options$mode4 !== void 0 ? _options$mode4 : 420;
106
107
  const uid = (_options$uid4 = options === null || options === void 0 ? void 0 : options.uid) !== null && _options$uid4 !== void 0 ? _options$uid4 : 0;
@@ -120,7 +121,7 @@ var createReadableFileItem = async (path$5, readable, options, signal) => {
120
121
  }
121
122
  return {
122
123
  kind: "file",
123
- path: path$5,
124
+ path: path$10,
124
125
  mode,
125
126
  uname,
126
127
  gname,
@@ -135,7 +136,7 @@ var createReadableFileItem = async (path$5, readable, options, signal) => {
135
136
  };
136
137
  } else return {
137
138
  kind: "file",
138
- path: path$5,
139
+ path: path$10,
139
140
  mode,
140
141
  uname,
141
142
  gname,
@@ -149,7 +150,7 @@ var createReadableFileItem = async (path$5, readable, options, signal) => {
149
150
  }
150
151
  };
151
152
  };
152
- var createReadFileItem = async (path$7, filePath, reflectStat, options, signal) => {
153
+ var createReadFileItem = async (path$12, filePath, reflectStat, options, signal) => {
153
154
  var _options$mode6, _options$uid6, _options$gid6, _options$date6;
154
155
  const rs = reflectStat !== null && reflectStat !== void 0 ? reflectStat : "exceptName";
155
156
  signal === null || signal === void 0 || signal.throwIfAborted();
@@ -161,7 +162,7 @@ var createReadFileItem = async (path$7, filePath, reflectStat, options, signal)
161
162
  const date = (_options$date6 = options === null || options === void 0 ? void 0 : options.date) !== null && _options$date6 !== void 0 ? _options$date6 : rs !== "none" ? stats.mtime : void 0;
162
163
  const uname = getUName(options === null || options === void 0 ? void 0 : options.uname, stats.uid, rs);
163
164
  const gname = getUName(options === null || options === void 0 ? void 0 : options.gname, stats.gid, rs);
164
- return await createReadableFileItem(path$7, reader, {
165
+ return await createReadableFileItem(path$12, reader, {
165
166
  length: stats.size,
166
167
  mode,
167
168
  uname,
@@ -171,8 +172,8 @@ var createReadFileItem = async (path$7, filePath, reflectStat, options, signal)
171
172
  date
172
173
  }, signal);
173
174
  };
174
- var storeReaderToFile = async (reader, path$8, signal) => {
175
- await (0, stream_promises.pipeline)(reader, (0, fs.createWriteStream)(path$8, { signal }), { signal });
175
+ var storeReaderToFile = async (reader, path$13, signal) => {
176
+ await (0, stream_promises.pipeline)(reader, (0, fs.createWriteStream)(path$13, { signal }), { signal });
176
177
  };
177
178
  var getAllFilesInDirectory = async (baseDir, signal) => {
178
179
  const collectFiles = async (currentDir, relativePath) => {
@@ -254,13 +255,13 @@ var truncateUtf8Safe = (str, maxBytes) => {
254
255
  }
255
256
  return str.slice(0, i);
256
257
  };
257
- var splitPath = (path$9) => {
258
+ var splitPath = (path$14) => {
258
259
  var _parts$pop;
259
- if (utf8ByteLength(path$9) <= MAX_NAME) return {
260
+ if (utf8ByteLength(path$14) <= MAX_NAME) return {
260
261
  prefix: "",
261
- name: path$9
262
+ name: path$14
262
263
  };
263
- const parts = path$9.split("/");
264
+ const parts = path$14.split("/");
264
265
  let name = (_parts$pop = parts.pop()) !== null && _parts$pop !== void 0 ? _parts$pop : "";
265
266
  let prefix = parts.join("/");
266
267
  if (utf8ByteLength(name) > MAX_NAME) name = truncateUtf8Safe(name, MAX_NAME);
@@ -280,9 +281,9 @@ var getPaddedBytes = (buffer) => {
280
281
  else return Buffer.concat([buffer, Buffer.alloc(512 - extra, 0)]);
281
282
  };
282
283
  var terminatorBytes = Buffer.alloc(1024, 0);
283
- var createTarHeader = (type, path$10, size, mode, uname, gname, uid, gid, date) => {
284
+ var createTarHeader = (type, path$15, size, mode, uname, gname, uid, gid, date) => {
284
285
  const buffer = Buffer.alloc(512, 0);
285
- const { name, prefix } = splitPath(path$10);
286
+ const { name, prefix } = splitPath(path$15);
286
287
  buffer.write(name, 0, 100, "utf8");
287
288
  getOctalBytes(mode & 4095, 8).copy(buffer, 100);
288
289
  getOctalBytes(uid, 8).copy(buffer, 108);
@@ -425,11 +426,11 @@ var parseTarHeader = (buffer) => {
425
426
  for (let i = 0; i < 512; i++) if (i >= 148 && i < 156) calculatedSum += 32;
426
427
  else calculatedSum += buffer[i];
427
428
  if (calculatedSum !== checksum) throw new Error(`Invalid checksum: expected ${checksum}, got ${calculatedSum}`);
428
- let path$11 = prefix ? `${prefix}/${name}` : name;
429
- if (path$11.endsWith("/")) path$11 = path$11.slice(0, -1);
429
+ let path$16 = prefix ? `${prefix}/${name}` : name;
430
+ if (path$16.endsWith("/")) path$16 = path$16.slice(0, -1);
430
431
  return {
431
432
  kind: typeflag === "5" ? "directory" : "file",
432
- path: path$11,
433
+ path: path$16,
433
434
  size,
434
435
  mode,
435
436
  uid,
@@ -2032,10 +2033,10 @@ var require_dayjs_min = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2032
2033
  //#region src/internal.ts
2033
2034
  var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1);
2034
2035
  var import_dayjs_min = /* @__PURE__ */ __toESM(require_dayjs_min(), 1);
2035
- var JSON5$1 = __resolveDefaultExport$4(import_dist.default, false);
2036
- var dayjs$1 = __resolveDefaultExport$4(import_dayjs_min.default, false);
2036
+ var JSON5$1 = __resolveDefaultExport$3(import_dist.default, false);
2037
+ var dayjs$1 = __resolveDefaultExport$3(import_dayjs_min.default, false);
2037
2038
  globalThis.__screwUpIsInCJS_db7919f73ec9 = true;
2038
- function __resolveDefaultExport$4(module, isESM) {
2039
+ function __resolveDefaultExport$3(module, isESM) {
2039
2040
  const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_db7919f73ec9 === true;
2040
2041
  const maybe = module;
2041
2042
  const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
@@ -2405,57 +2406,405 @@ var resolveRawPackageJsonObject = async (projectRoot, fetchGitMetadata, alwaysOv
2405
2406
  };
2406
2407
  //#endregion
2407
2408
  //#region src/git-ref-utils.ts
2408
- var git$1 = __resolveDefaultExport$3(isomorphic_git.default, false);
2409
- globalThis.__screwUpIsInCJS_89cc61422477 = true;
2410
- function __resolveDefaultExport$3(module, isESM) {
2411
- const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_89cc61422477 === true;
2412
- const maybe = module;
2413
- const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
2414
- const unwrapNamespaceDefault = (value) => {
2415
- if (!value || typeof value !== "object") return value;
2416
- const inner = value;
2417
- if ((inner.__esModule === true || typeof Symbol !== "undefined" && inner[Symbol.toStringTag] === "Module") && "default" in inner) return inner.default;
2418
- return value;
2419
- };
2420
- const resolvedDefault = hasDefault ? unwrapNamespaceDefault(maybe.default) : void 0;
2421
- if (__isInCJS) return hasDefault ? resolvedDefault !== null && resolvedDefault !== void 0 ? resolvedDefault : module : module;
2422
- if (isESM) {
2423
- if (hasDefault) return resolvedDefault;
2424
- throw new Error("Default export not found.");
2425
- }
2426
- return hasDefault ? resolvedDefault !== null && resolvedDefault !== void 0 ? resolvedDefault : module : module;
2427
- }
2409
+ var PACK_TRAILER_SIZE = 20;
2410
+ var LOOSE_TAG_RESOLUTION_CONCURRENCY = 4;
2411
+ var PACKED_OBJECT_TYPE_BY_CODE = new Map([
2412
+ [1, "commit"],
2413
+ [2, "tree"],
2414
+ [3, "blob"],
2415
+ [4, "tag"],
2416
+ [6, "ofs-delta"],
2417
+ [7, "ref-delta"]
2418
+ ]);
2428
2419
  /**
2429
- * Resolve the actual Git directory for repositories, worktrees, and submodules.
2420
+ * Resolve Git directory paths for repositories, worktrees, and submodules.
2430
2421
  * @param repoPath - Repository path
2431
- * @returns The resolved Git directory path
2422
+ * @returns The resolved Git directory paths
2432
2423
  */
2433
- var getActualGitDir = async (repoPath) => {
2424
+ var resolveGitDirectoryPaths = async (repoPath) => {
2434
2425
  const gitDir = (0, path.join)(repoPath, ".git");
2435
2426
  const gitStat = await (0, fs_promises.stat)(gitDir).catch(() => null);
2436
- if (!(gitStat === null || gitStat === void 0 ? void 0 : gitStat.isFile())) return gitDir;
2437
- const match = (await (0, fs_promises.readFile)(gitDir, "utf-8")).match(/^gitdir:\s*(.+)$/m);
2438
- if (!match) return gitDir;
2439
- return (0, path.isAbsolute)(match[1]) ? match[1] : (0, path.join)(repoPath, match[1]);
2427
+ const resolvedGitDir = !(gitStat === null || gitStat === void 0 ? void 0 : gitStat.isFile()) ? gitDir : await (async () => {
2428
+ const match = (await (0, fs_promises.readFile)(gitDir, "utf-8")).match(/^gitdir:\s*(.+)$/m);
2429
+ if (!match) return gitDir;
2430
+ return (0, path.isAbsolute)(match[1]) ? match[1] : (0, path.join)(repoPath, match[1]);
2431
+ })();
2432
+ return {
2433
+ gitDir: resolvedGitDir,
2434
+ commonGitDir: await (0, fs_promises.readFile)((0, path.join)(resolvedGitDir, "commondir"), "utf-8").then((content) => {
2435
+ const commondir = content.trim();
2436
+ if (!commondir) return resolvedGitDir;
2437
+ return (0, path.isAbsolute)(commondir) ? commondir : (0, path.join)(resolvedGitDir, commondir);
2438
+ }).catch((error) => {
2439
+ if ((error === null || error === void 0 ? void 0 : error.code) !== "ENOENT") throw error;
2440
+ return resolvedGitDir;
2441
+ })
2442
+ };
2443
+ };
2444
+ /**
2445
+ * Resolve the worktree-specific Git directory.
2446
+ * @param repoPath - Repository path
2447
+ * @returns The resolved worktree-specific Git directory path
2448
+ */
2449
+ var getActualGitDir = async (repoPath) => {
2450
+ return (await resolveGitDirectoryPaths(repoPath)).gitDir;
2440
2451
  };
2441
2452
  /**
2442
- * Resolve a tag object OID to the commit OID it ultimately points to.
2443
- * Lightweight tags are returned unchanged.
2453
+ * Resolve the common Git directory used for refs and objects.
2444
2454
  * @param repoPath - Repository path
2445
- * @param tagOid - Tag or commit OID
2446
- * @returns Commit hash this tag points to
2455
+ * @returns The resolved common Git directory path
2447
2456
  */
2448
- var resolveTagOidToCommit = async (repoPath, tagOid) => {
2457
+ var getCommonGitDir = async (repoPath) => {
2458
+ return (await resolveGitDirectoryPaths(repoPath)).commonGitDir;
2459
+ };
2460
+ var readFixedRange = async (fileHandle, offset, length) => {
2461
+ const buffer = Buffer.alloc(length);
2462
+ const { bytesRead } = await fileHandle.read(buffer, 0, length, offset);
2463
+ if (bytesRead !== length) throw new Error(`Unexpected EOF while reading pack entry at offset ${offset} (expected ${length}, got ${bytesRead})`);
2464
+ return buffer;
2465
+ };
2466
+ var readLooseObject = async (gitDir, oid) => {
2449
2467
  try {
2450
- var _tagObject$tag;
2451
- const tagObject = await git$1.readTag({
2452
- fs: fs_promises.default,
2453
- dir: repoPath,
2454
- oid: tagOid
2468
+ const wrapped = (0, zlib.inflateSync)(await (0, fs_promises.readFile)((0, path.join)(gitDir, "objects", oid.slice(0, 2), oid.slice(2))));
2469
+ const headerEnd = wrapped.indexOf(0);
2470
+ if (headerEnd < 0) throw new Error(`Invalid loose object header: ${oid}`);
2471
+ const header = wrapped.subarray(0, headerEnd).toString("utf-8");
2472
+ const match = header.match(/^(commit|tree|blob|tag) (\d+)$/);
2473
+ if (!match) throw new Error(`Unsupported loose object header: ${header}`);
2474
+ const content = wrapped.subarray(headerEnd + 1);
2475
+ const expectedSize = Number(match[2]);
2476
+ if (content.length !== expectedSize) throw new Error(`Loose object size mismatch: ${oid} (expected ${expectedSize}, got ${content.length})`);
2477
+ return {
2478
+ oid,
2479
+ type: match[1],
2480
+ content
2481
+ };
2482
+ } catch (error) {
2483
+ if (error.code === "ENOENT") return null;
2484
+ throw error;
2485
+ }
2486
+ };
2487
+ var readLargePackOffset = (idxBuffer, largeOffsetsStart, largeOffsetIndex) => {
2488
+ const offset = Number(idxBuffer.readBigUInt64BE(largeOffsetsStart + largeOffsetIndex * 8));
2489
+ if (!Number.isSafeInteger(offset)) throw new Error(`Pack offset exceeds safe integer range: ${offset}`);
2490
+ return offset;
2491
+ };
2492
+ var loadPackIndex = async (idxPath) => {
2493
+ const packPath = idxPath.replace(/\.idx$/, ".pack");
2494
+ const [idxBuffer, packStat, fileHandle] = await Promise.all([
2495
+ (0, fs_promises.readFile)(idxPath),
2496
+ (0, fs_promises.stat)(packPath),
2497
+ (0, fs_promises.open)(packPath, "r")
2498
+ ]);
2499
+ if (idxBuffer.readUInt32BE(0) !== 4285812579) throw new Error(`Unsupported pack index signature: ${idxPath}`);
2500
+ if (idxBuffer.readUInt32BE(4) !== 2) throw new Error(`Unsupported pack index version: ${idxPath}`);
2501
+ const objectCount = idxBuffer.readUInt32BE(1028);
2502
+ const oidStart = 1032;
2503
+ const offsetStart = oidStart + objectCount * 20 + objectCount * 4;
2504
+ const largeOffsetStart = offsetStart + objectCount * 4;
2505
+ const objectByOid = /* @__PURE__ */ new Map();
2506
+ const objectByOffset = /* @__PURE__ */ new Map();
2507
+ const sortedObjects = [];
2508
+ const packIndex = {
2509
+ fileHandle,
2510
+ objectByOid,
2511
+ objectByOffset
2512
+ };
2513
+ for (let index = 0; index < objectCount; index++) {
2514
+ const oidOffset = oidStart + index * 20;
2515
+ const oid = idxBuffer.subarray(oidOffset, oidOffset + 20).toString("hex");
2516
+ const rawOffset = idxBuffer.readUInt32BE(offsetStart + index * 4);
2517
+ const offset = (rawOffset & 2147483648) === 0 ? rawOffset : readLargePackOffset(idxBuffer, largeOffsetStart, rawOffset & 2147483647);
2518
+ sortedObjects.push({
2519
+ oid,
2520
+ offset
2455
2521
  });
2456
- if (tagObject === null || tagObject === void 0 || (_tagObject$tag = tagObject.tag) === null || _tagObject$tag === void 0 ? void 0 : _tagObject$tag.object) return tagObject.tag.object;
2457
- } catch (_unused) {}
2458
- return tagOid;
2522
+ }
2523
+ sortedObjects.sort((left, right) => left.offset - right.offset);
2524
+ const packEndOffset = packStat.size - PACK_TRAILER_SIZE;
2525
+ for (let index = 0; index < sortedObjects.length; index++) {
2526
+ var _sortedObjects$offset, _sortedObjects;
2527
+ const currentObject = sortedObjects[index];
2528
+ const nextOffset = (_sortedObjects$offset = (_sortedObjects = sortedObjects[index + 1]) === null || _sortedObjects === void 0 ? void 0 : _sortedObjects.offset) !== null && _sortedObjects$offset !== void 0 ? _sortedObjects$offset : packEndOffset;
2529
+ const location = {
2530
+ oid: currentObject.oid,
2531
+ offset: currentObject.offset,
2532
+ nextOffset,
2533
+ packIndex
2534
+ };
2535
+ objectByOid.set(currentObject.oid, location);
2536
+ objectByOffset.set(currentObject.offset, location);
2537
+ }
2538
+ return packIndex;
2539
+ };
2540
+ var loadPackStore = async (gitDir) => {
2541
+ try {
2542
+ const packDir = (0, path.join)(gitDir, "objects", "pack");
2543
+ const idxPaths = (await (0, fs_promises.readdir)(packDir)).filter((entryName) => entryName.endsWith(".idx")).map((entryName) => (0, path.join)(packDir, entryName));
2544
+ const packs = await Promise.all(idxPaths.map(loadPackIndex));
2545
+ const objectByOid = /* @__PURE__ */ new Map();
2546
+ for (const pack of packs) for (const [oid, location] of pack.objectByOid.entries()) objectByOid.set(oid, location);
2547
+ return {
2548
+ packs,
2549
+ objectByOid
2550
+ };
2551
+ } catch (error) {
2552
+ if (error.code === "ENOENT") return {
2553
+ packs: [],
2554
+ objectByOid: /* @__PURE__ */ new Map()
2555
+ };
2556
+ throw error;
2557
+ }
2558
+ };
2559
+ var decodeOfsDeltaDistance = (buffer, startOffset) => {
2560
+ let cursor = startOffset;
2561
+ let byte = buffer[cursor++];
2562
+ let distance = byte & 127;
2563
+ while (byte & 128) {
2564
+ byte = buffer[cursor++];
2565
+ distance = distance + 1 << 7 | byte & 127;
2566
+ }
2567
+ return {
2568
+ distance,
2569
+ nextOffset: cursor
2570
+ };
2571
+ };
2572
+ var parsePackedEntryHeader = (entryBuffer, objectOffset) => {
2573
+ let cursor = 0;
2574
+ let byte = entryBuffer[cursor++];
2575
+ const packedType = PACKED_OBJECT_TYPE_BY_CODE.get(byte >> 4 & 7);
2576
+ if (!packedType) throw new Error(`Unsupported packed object type at offset ${objectOffset}`);
2577
+ let declaredSize = byte & 15;
2578
+ let shift = 4;
2579
+ while (byte & 128) {
2580
+ byte = entryBuffer[cursor++];
2581
+ declaredSize |= (byte & 127) << shift;
2582
+ shift += 7;
2583
+ }
2584
+ let baseOffset;
2585
+ let baseOid;
2586
+ if (packedType === "ofs-delta") {
2587
+ const decoded = decodeOfsDeltaDistance(entryBuffer, cursor);
2588
+ cursor = decoded.nextOffset;
2589
+ baseOffset = objectOffset - decoded.distance;
2590
+ } else if (packedType === "ref-delta") {
2591
+ baseOid = entryBuffer.subarray(cursor, cursor + 20).toString("hex");
2592
+ cursor += 20;
2593
+ }
2594
+ return {
2595
+ packedType,
2596
+ declaredSize,
2597
+ headerLength: cursor,
2598
+ baseOffset,
2599
+ baseOid
2600
+ };
2601
+ };
2602
+ var readDeltaSize = (buffer, startOffset) => {
2603
+ let cursor = startOffset;
2604
+ let size = 0;
2605
+ let shift = 0;
2606
+ while (cursor < buffer.length) {
2607
+ const byte = buffer[cursor++];
2608
+ size |= (byte & 127) << shift;
2609
+ if ((byte & 128) === 0) return {
2610
+ size,
2611
+ nextOffset: cursor
2612
+ };
2613
+ shift += 7;
2614
+ }
2615
+ throw new Error("Invalid git delta size encoding");
2616
+ };
2617
+ var applyGitDelta = (baseContent, deltaContent) => {
2618
+ const baseSizeInfo = readDeltaSize(deltaContent, 0);
2619
+ if (baseSizeInfo.size !== baseContent.length) throw new Error(`Git delta base size mismatch: expected ${baseSizeInfo.size}, got ${baseContent.length}`);
2620
+ const targetSizeInfo = readDeltaSize(deltaContent, baseSizeInfo.nextOffset);
2621
+ const result = Buffer.alloc(targetSizeInfo.size);
2622
+ let deltaOffset = targetSizeInfo.nextOffset;
2623
+ let resultOffset = 0;
2624
+ while (deltaOffset < deltaContent.length) {
2625
+ const opcode = deltaContent[deltaOffset++];
2626
+ if ((opcode & 128) !== 0) {
2627
+ let copyOffset = 0;
2628
+ let copySize = 0;
2629
+ if (opcode & 1) copyOffset |= deltaContent[deltaOffset++];
2630
+ if (opcode & 2) copyOffset |= deltaContent[deltaOffset++] << 8;
2631
+ if (opcode & 4) copyOffset |= deltaContent[deltaOffset++] << 16;
2632
+ if (opcode & 8) copyOffset |= deltaContent[deltaOffset++] << 24;
2633
+ if (opcode & 16) copySize |= deltaContent[deltaOffset++];
2634
+ if (opcode & 32) copySize |= deltaContent[deltaOffset++] << 8;
2635
+ if (opcode & 64) copySize |= deltaContent[deltaOffset++] << 16;
2636
+ if (copySize === 0) copySize = 65536;
2637
+ baseContent.copy(result, resultOffset, copyOffset, copyOffset + copySize);
2638
+ resultOffset += copySize;
2639
+ continue;
2640
+ }
2641
+ if (opcode === 0) throw new Error("Invalid git delta opcode");
2642
+ deltaContent.copy(result, resultOffset, deltaOffset, deltaOffset + opcode);
2643
+ deltaOffset += opcode;
2644
+ resultOffset += opcode;
2645
+ }
2646
+ if (resultOffset !== result.length) throw new Error(`Git delta size mismatch: expected ${result.length}, got ${resultOffset}`);
2647
+ return result;
2648
+ };
2649
+ var inflatePackedObject = (compressedContent) => Buffer.from((0, zlib.inflateSync)(compressedContent));
2650
+ var parseTagTargetOid = (tagContent) => {
2651
+ const firstLineEnd = tagContent.indexOf(10);
2652
+ const firstLine = firstLineEnd >= 0 ? tagContent.subarray(0, firstLineEnd).toString("utf-8") : tagContent.toString("utf-8");
2653
+ const match = firstLine.match(/^object ([0-9a-f]{40})$/);
2654
+ if (!match) throw new Error(`Invalid annotated tag payload: ${firstLine}`);
2655
+ return match[1];
2656
+ };
2657
+ var parseTreeEntries = (treeContent) => {
2658
+ const entries = [];
2659
+ let offset = 0;
2660
+ while (offset < treeContent.length) {
2661
+ const modeEnd = treeContent.indexOf(32, offset);
2662
+ if (modeEnd < 0) throw new Error("Invalid tree entry mode");
2663
+ const nameEnd = treeContent.indexOf(0, modeEnd + 1);
2664
+ if (nameEnd < 0 || nameEnd + 21 > treeContent.length) throw new Error("Invalid tree entry name");
2665
+ entries.push({
2666
+ mode: treeContent.subarray(offset, modeEnd).toString("utf-8"),
2667
+ name: treeContent.subarray(modeEnd + 1, nameEnd).toString("utf-8"),
2668
+ oid: treeContent.subarray(nameEnd + 1, nameEnd + 21).toString("hex")
2669
+ });
2670
+ offset = nameEnd + 21;
2671
+ }
2672
+ return entries;
2673
+ };
2674
+ var createGitObjectResolver = async (repoPath) => {
2675
+ const commonGitDir = await getCommonGitDir(repoPath);
2676
+ const resolvedObjects = /* @__PURE__ */ new Map();
2677
+ let packStorePromise;
2678
+ const getPackStore = async () => {
2679
+ if (!packStorePromise) packStorePromise = loadPackStore(commonGitDir);
2680
+ return packStorePromise;
2681
+ };
2682
+ const readPackedObject = async (location) => {
2683
+ var _location$packIndex$o, _location$packIndex$o2, _header$baseOid;
2684
+ const entryLength = location.nextOffset - location.offset;
2685
+ const entryBuffer = await readFixedRange(location.packIndex.fileHandle, location.offset, entryLength);
2686
+ const header = parsePackedEntryHeader(entryBuffer, location.offset);
2687
+ const compressedContent = entryBuffer.subarray(header.headerLength);
2688
+ if (header.packedType === "commit" || header.packedType === "tree" || header.packedType === "blob" || header.packedType === "tag") {
2689
+ const content = inflatePackedObject(compressedContent);
2690
+ if (content.length !== header.declaredSize) throw new Error(`Packed object size mismatch: ${location.oid} (expected ${header.declaredSize}, got ${content.length})`);
2691
+ return {
2692
+ oid: location.oid,
2693
+ type: header.packedType,
2694
+ content
2695
+ };
2696
+ }
2697
+ const deltaContent = inflatePackedObject(compressedContent);
2698
+ if (deltaContent.length !== header.declaredSize) throw new Error(`Packed delta size mismatch: ${location.oid} (expected ${header.declaredSize}, got ${deltaContent.length})`);
2699
+ const baseObject = header.packedType === "ofs-delta" ? await readObject((_location$packIndex$o = (_location$packIndex$o2 = location.packIndex.objectByOffset.get(header.baseOffset)) === null || _location$packIndex$o2 === void 0 ? void 0 : _location$packIndex$o2.oid) !== null && _location$packIndex$o !== void 0 ? _location$packIndex$o : (() => {
2700
+ throw new Error(`Missing ofs-delta base object at offset ${header.baseOffset}`);
2701
+ })()) : await readObject((_header$baseOid = header.baseOid) !== null && _header$baseOid !== void 0 ? _header$baseOid : (() => {
2702
+ throw new Error("Missing ref-delta base object id");
2703
+ })());
2704
+ const content = applyGitDelta(baseObject.content, deltaContent);
2705
+ return {
2706
+ oid: location.oid,
2707
+ type: baseObject.type,
2708
+ content
2709
+ };
2710
+ };
2711
+ const readObject = async (oid) => {
2712
+ const cachedObject = resolvedObjects.get(oid);
2713
+ if (cachedObject) return cachedObject;
2714
+ const objectPromise = (async () => {
2715
+ const looseObject = await readLooseObject(commonGitDir, oid);
2716
+ if (looseObject) return looseObject;
2717
+ const location = (await getPackStore()).objectByOid.get(oid);
2718
+ if (!location) throw new Error(`Git object not found: ${oid}`);
2719
+ return readPackedObject(location);
2720
+ })();
2721
+ resolvedObjects.set(oid, objectPromise);
2722
+ try {
2723
+ return await objectPromise;
2724
+ } catch (error) {
2725
+ resolvedObjects.delete(oid);
2726
+ throw error;
2727
+ }
2728
+ };
2729
+ return {
2730
+ close: async () => {
2731
+ if (!packStorePromise) return;
2732
+ const packStore = await packStorePromise;
2733
+ await Promise.allSettled(packStore.packs.map(async (pack) => {
2734
+ await pack.fileHandle.close();
2735
+ }));
2736
+ },
2737
+ readObject,
2738
+ resolveTagOidToCommit: async (tagOid) => {
2739
+ let currentOid = tagOid;
2740
+ const visitedOids = /* @__PURE__ */ new Set();
2741
+ while (true) {
2742
+ if (visitedOids.has(currentOid)) throw new Error(`Detected cyclic tag reference: ${currentOid}`);
2743
+ visitedOids.add(currentOid);
2744
+ const object = await readObject(currentOid);
2745
+ if (object.type !== "tag") return currentOid;
2746
+ currentOid = parseTagTargetOid(object.content);
2747
+ }
2748
+ }
2749
+ };
2750
+ };
2751
+ var runWithConcurrency = async (values, concurrency, worker) => {
2752
+ let nextIndex = 0;
2753
+ const runWorker = async () => {
2754
+ while (nextIndex < values.length) {
2755
+ const currentIndex = nextIndex;
2756
+ nextIndex += 1;
2757
+ await worker(values[currentIndex]);
2758
+ }
2759
+ };
2760
+ await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(values.length, 1)) }, () => runWorker()));
2761
+ };
2762
+ /**
2763
+ * Resolve multiple tag object OIDs to their peeled commit OIDs.
2764
+ * @param repoPath - Repository path
2765
+ * @param tagOids - Tag or commit OIDs
2766
+ * @returns Map of tag object OID to peeled commit OID
2767
+ */
2768
+ var resolveTagOidsToCommits = async (repoPath, tagOids) => {
2769
+ const resolver = await createGitObjectResolver(repoPath);
2770
+ const result = /* @__PURE__ */ new Map();
2771
+ const uniqueTagOids = Array.from(new Set(tagOids));
2772
+ try {
2773
+ await runWithConcurrency(uniqueTagOids, LOOSE_TAG_RESOLUTION_CONCURRENCY, async (tagOid) => {
2774
+ result.set(tagOid, await resolver.resolveTagOidToCommit(tagOid));
2775
+ });
2776
+ } finally {
2777
+ await resolver.close();
2778
+ }
2779
+ return result;
2780
+ };
2781
+ var collectTreeFiles = async (resolver, treeOid, prefix, files) => {
2782
+ const treeObject = await resolver.readObject(treeOid);
2783
+ if (treeObject.type !== "tree") throw new Error(`Expected tree object: ${treeOid}`);
2784
+ for (const entry of parseTreeEntries(treeObject.content)) {
2785
+ const path$7 = prefix ? `${prefix}/${entry.name}` : entry.name;
2786
+ if (entry.mode === "40000") {
2787
+ await collectTreeFiles(resolver, entry.oid, path$7, files);
2788
+ continue;
2789
+ }
2790
+ if (entry.mode !== "160000") files.set(path$7, entry.oid);
2791
+ }
2792
+ };
2793
+ /**
2794
+ * Collect all tracked file blob OIDs under the specified tree.
2795
+ * @param repoPath - Repository path
2796
+ * @param treeOid - Tree object OID
2797
+ * @returns Map of repository-relative file path to blob OID
2798
+ */
2799
+ var listTreeFiles = async (repoPath, treeOid) => {
2800
+ const resolver = await createGitObjectResolver(repoPath);
2801
+ const files = /* @__PURE__ */ new Map();
2802
+ try {
2803
+ await collectTreeFiles(resolver, treeOid, "", files);
2804
+ } finally {
2805
+ await resolver.close();
2806
+ }
2807
+ return files;
2459
2808
  };
2460
2809
  //#endregion
2461
2810
  //#region src/fast-tags.ts
@@ -2508,8 +2857,8 @@ var readLooseTags = async (refsTagsPath) => {
2508
2857
  * @returns Array of all tag names
2509
2858
  */
2510
2859
  var listTagsFast = async (repoPath) => {
2511
- const actualGitDir = await getActualGitDir(repoPath);
2512
- const [packedTags, looseTags] = await Promise.all([parsePackedRefs((0, path.join)(actualGitDir, "packed-refs")), readLooseTags((0, path.join)(actualGitDir, "refs", "tags"))]);
2860
+ const commonGitDir = await getCommonGitDir(repoPath);
2861
+ const [packedTags, looseTags] = await Promise.all([parsePackedRefs((0, path.join)(commonGitDir, "packed-refs")), readLooseTags((0, path.join)(commonGitDir, "refs", "tags"))]);
2513
2862
  const allTags = new Set([...packedTags, ...looseTags]);
2514
2863
  return Array.from(allTags).sort();
2515
2864
  };
@@ -2522,11 +2871,11 @@ var listTagsFast = async (repoPath) => {
2522
2871
  var resolveTagsBatchWithCommit = async (repoPath, tagNames, logger) => {
2523
2872
  const startTime = Date.now();
2524
2873
  const result = /* @__PURE__ */ new Map();
2525
- const actualGitDir = await getActualGitDir(repoPath);
2874
+ const commonGitDir = await getCommonGitDir(repoPath);
2526
2875
  const tagSet = new Set(tagNames);
2527
2876
  const packedRefsStart = Date.now();
2528
2877
  try {
2529
- const lines = (await (0, fs_promises.readFile)((0, path.join)(actualGitDir, "packed-refs"), "utf-8")).split("\n");
2878
+ const lines = (await (0, fs_promises.readFile)((0, path.join)(commonGitDir, "packed-refs"), "utf-8")).split("\n");
2530
2879
  for (let i = 0; i < lines.length; i++) {
2531
2880
  const line = lines[i];
2532
2881
  if (line.startsWith("#") || !line.trim()) continue;
@@ -2549,19 +2898,28 @@ var resolveTagsBatchWithCommit = async (repoPath, tagNames, logger) => {
2549
2898
  const remainingTags = tagNames.filter((tag) => !result.has(tag));
2550
2899
  if (remainingTags.length > 0) {
2551
2900
  const looseRefsStart = Date.now();
2552
- await Promise.all(remainingTags.map(async (tagName) => {
2553
- const looseRefPath = (0, path.join)(actualGitDir, "refs", "tags", tagName);
2901
+ const looseTagEntries = (await Promise.all(remainingTags.map(async (tagName) => {
2902
+ const looseRefPath = (0, path.join)(commonGitDir, "refs", "tags", tagName);
2554
2903
  try {
2555
- const oid = (await (0, fs_promises.readFile)(looseRefPath, "utf-8")).trim();
2556
- const commitOid = await resolveTagOidToCommit(repoPath, oid);
2904
+ return {
2905
+ tagName,
2906
+ oid: (await (0, fs_promises.readFile)(looseRefPath, "utf-8")).trim()
2907
+ };
2908
+ } catch (error) {
2909
+ if (error.code !== "ENOENT") throw error;
2910
+ return;
2911
+ }
2912
+ }))).filter((entry) => entry !== void 0);
2913
+ if (looseTagEntries.length > 0) {
2914
+ const commitOids = await resolveTagOidsToCommits(repoPath, looseTagEntries.map((entry) => entry.oid));
2915
+ for (const { tagName, oid } of looseTagEntries) {
2916
+ var _commitOids$get;
2557
2917
  result.set(tagName, {
2558
2918
  oid,
2559
- commitOid
2919
+ commitOid: (_commitOids$get = commitOids.get(oid)) !== null && _commitOids$get !== void 0 ? _commitOids$get : oid
2560
2920
  });
2561
- } catch (error) {
2562
- if (error.code !== "ENOENT") throw error;
2563
2921
  }
2564
- }));
2922
+ }
2565
2923
  logger.debug(`[fast-tags] read loose refs: ${Date.now() - looseRefsStart}ms`);
2566
2924
  }
2567
2925
  const totalTime = Date.now() - startTime;
@@ -2757,16 +3115,26 @@ var formatVersion = (version) => {
2757
3115
  return result;
2758
3116
  };
2759
3117
  /**
2760
- * Get a commit by hash
3118
+ * Build a Git read context that can operate correctly inside worktrees.
2761
3119
  * @param repositoryPath - Local Git repository directory
3120
+ * @returns The resolved Git read context
3121
+ */
3122
+ var createGitReadContext = async (repositoryPath) => ({
3123
+ dir: repositoryPath,
3124
+ gitdir: await getCommonGitDir(repositoryPath)
3125
+ });
3126
+ /**
3127
+ * Get a commit by hash
3128
+ * @param context - Git read context
2762
3129
  * @param hash - The hash of the commit
2763
3130
  * @returns The commit or undefined if the commit is not found
2764
3131
  */
2765
- var getCommit = async (repositoryPath, hash) => {
3132
+ var getCommit = async (context, hash) => {
2766
3133
  try {
2767
3134
  const commit = await isomorphic_git.readCommit({
2768
3135
  fs: fs_promises.default,
2769
- dir: repositoryPath,
3136
+ dir: context.dir,
3137
+ gitdir: context.gitdir,
2770
3138
  oid: hash
2771
3139
  });
2772
3140
  return {
@@ -2774,7 +3142,8 @@ var getCommit = async (repositoryPath, hash) => {
2774
3142
  shortHash: commit.oid.substring(0, 7),
2775
3143
  date: (/* @__PURE__ */ new Date(commit.commit.author.timestamp * 1e3)).toISOString(),
2776
3144
  message: commit.commit.message.trim(),
2777
- parents: commit.commit.parent || []
3145
+ parents: commit.commit.parent || [],
3146
+ tree: commit.commit.tree
2778
3147
  };
2779
3148
  } catch (_unused) {
2780
3149
  return;
@@ -2782,19 +3151,20 @@ var getCommit = async (repositoryPath, hash) => {
2782
3151
  };
2783
3152
  /**
2784
3153
  * Get the current commit
2785
- * @param repositoryPath - Local Git repository directory
3154
+ * @param context - Git read context
2786
3155
  * @returns The current commit or undefined if the current commit is not found
2787
3156
  */
2788
- var getCurrentCommit = async (repositoryPath) => {
3157
+ var getCurrentCommit = async (context) => {
2789
3158
  try {
2790
3159
  const currentOid = await isomorphic_git.resolveRef({
2791
3160
  fs: fs_promises.default,
2792
- dir: repositoryPath,
3161
+ dir: context.dir,
2793
3162
  ref: "HEAD"
2794
3163
  });
2795
3164
  const commit = await isomorphic_git.readCommit({
2796
3165
  fs: fs_promises.default,
2797
- dir: repositoryPath,
3166
+ dir: context.dir,
3167
+ gitdir: context.gitdir,
2798
3168
  oid: currentOid
2799
3169
  });
2800
3170
  return {
@@ -2802,7 +3172,8 @@ var getCurrentCommit = async (repositoryPath) => {
2802
3172
  shortHash: commit.oid.substring(0, 7),
2803
3173
  date: (/* @__PURE__ */ new Date(commit.commit.author.timestamp * 1e3)).toISOString(),
2804
3174
  message: commit.commit.message.trim(),
2805
- parents: commit.commit.parent || []
3175
+ parents: commit.commit.parent || [],
3176
+ tree: commit.commit.tree
2806
3177
  };
2807
3178
  } catch (_unused2) {
2808
3179
  return;
@@ -2819,21 +3190,23 @@ var getRelatedTagsFromMap = (commitToTags, commitHash) => {
2819
3190
  };
2820
3191
  /**
2821
3192
  * Get the commit related branch name.
2822
- * @param repositoryPath - Local Git repository directory
3193
+ * @param context - Git read context
2823
3194
  * @param commitHash - The hash of the commit
2824
3195
  * @returns The commit related branch name or undefined if not found
2825
3196
  */
2826
- var getRelatedBranches = async (repositoryPath, commitHash) => {
3197
+ var getRelatedBranches = async (context, commitHash) => {
2827
3198
  try {
2828
3199
  const branches = await isomorphic_git.listBranches({
2829
3200
  fs: fs_promises.default,
2830
- dir: repositoryPath
3201
+ dir: context.dir,
3202
+ gitdir: context.gitdir
2831
3203
  });
2832
3204
  const relatedBranches = [];
2833
3205
  for (const branch of branches) try {
2834
3206
  if (await isomorphic_git.resolveRef({
2835
3207
  fs: fs_promises.default,
2836
- dir: repositoryPath,
3208
+ dir: context.dir,
3209
+ gitdir: context.gitdir,
2837
3210
  ref: branch
2838
3211
  }) === commitHash) relatedBranches.push(branch);
2839
3212
  } catch (_unused3) {}
@@ -2842,94 +3215,133 @@ var getRelatedBranches = async (repositoryPath, commitHash) => {
2842
3215
  return [];
2843
3216
  }
2844
3217
  };
2845
- /**
2846
- * Check if the repository has modified files (following RelaxVersioner logic).
2847
- * Checks for staged files, unstaged files, and untracked files (respecting .gitignore).
2848
- * @param repositoryPath - Local Git repository directory
2849
- * @returns Modified files
2850
- */
2851
- var isModifiedFile = ([, head, workdir, stage]) => {
2852
- return workdir === 2 || stage === 2 || stage === 3 || head === 1 && workdir === 0 || head === 0 && workdir === 1;
2853
- };
2854
- var getStatusRow = async (filepath, entries) => {
2855
- const [head, workdir, stage] = entries;
2856
- const [headType, workdirType, stageType] = await Promise.all([
2857
- head ? head.type() : void 0,
2858
- workdir ? workdir.type() : void 0,
2859
- stage ? stage.type() : void 0
2860
- ]);
2861
- const isBlob = [
2862
- headType,
2863
- workdirType,
2864
- stageType
2865
- ].includes("blob");
2866
- if ((headType === "tree" || headType === "special") && !isBlob) return;
2867
- if (headType === "commit") return;
2868
- if ((workdirType === "tree" || workdirType === "special") && !isBlob) return;
2869
- if (stageType === "commit") return;
2870
- if ((stageType === "tree" || stageType === "special") && !isBlob) return;
2871
- const headOid = headType === "blob" ? await head.oid() : void 0;
2872
- const stageOid = stageType === "blob" ? await stage.oid() : void 0;
2873
- let workdirOid;
2874
- if (headType !== "blob" && workdirType === "blob" && stageType !== "blob") workdirOid = "42";
2875
- else if (workdirType === "blob") workdirOid = await workdir.oid();
2876
- const entry = [
2877
- void 0,
2878
- headOid,
2879
- workdirOid,
2880
- stageOid
2881
- ];
2882
- const statusValues = entry.map((value) => entry.indexOf(value));
2883
- return [
2884
- filepath,
2885
- statusValues[1],
2886
- statusValues[2],
2887
- statusValues[3]
2888
- ];
3218
+ var parseGitIndex = async (gitDir) => {
3219
+ try {
3220
+ const buffer = await fs_promises.default.readFile((0, path.join)(gitDir, "index"));
3221
+ if (buffer.subarray(0, 4).toString("ascii") !== "DIRC") throw new Error("Unsupported git index signature");
3222
+ const version = buffer.readUInt32BE(4);
3223
+ if (version !== 2 && version !== 3) throw new Error(`Unsupported git index version: ${version}`);
3224
+ const entryCount = buffer.readUInt32BE(8);
3225
+ let offset = 12;
3226
+ const entries = /* @__PURE__ */ new Map();
3227
+ for (let index = 0; index < entryCount; index++) {
3228
+ const entryStart = offset;
3229
+ const size = buffer.readUInt32BE(entryStart + 36);
3230
+ const oid = buffer.subarray(entryStart + 40, entryStart + 60).toString("hex");
3231
+ const flags = buffer.readUInt16BE(entryStart + 60);
3232
+ const stage = flags >> 12 & 3;
3233
+ offset = entryStart + 62;
3234
+ if (version >= 3 && (flags & 16384) !== 0) offset += 2;
3235
+ const pathEnd = buffer.indexOf(0, offset);
3236
+ if (pathEnd < 0) throw new Error("Invalid git index path entry");
3237
+ const path$3 = buffer.subarray(offset, pathEnd).toString("utf-8");
3238
+ offset = pathEnd + 1;
3239
+ while ((offset - entryStart) % 8 !== 0) offset += 1;
3240
+ entries.set(path$3, {
3241
+ path: path$3,
3242
+ oid,
3243
+ size,
3244
+ stage
3245
+ });
3246
+ }
3247
+ return entries;
3248
+ } catch (error) {
3249
+ if (error.code === "ENOENT") return /* @__PURE__ */ new Map();
3250
+ throw error;
3251
+ }
3252
+ };
3253
+ var listTrackedDirectories = (indexEntries) => {
3254
+ const directories = new Set([""]);
3255
+ for (const path$4 of indexEntries.keys()) {
3256
+ const segments = path$4.split("/");
3257
+ let currentPath = "";
3258
+ for (let index = 0; index < segments.length - 1; index++) {
3259
+ currentPath = currentPath ? `${currentPath}/${segments[index]}` : segments[index];
3260
+ directories.add(currentPath);
3261
+ }
3262
+ }
3263
+ return directories;
2889
3264
  };
2890
- var reduceModifiedFiles = async (parent, children) => {
2891
- const modifiedFiles = parent ? [parent] : [];
2892
- for (const child of children) modifiedFiles.push(...child);
2893
- return modifiedFiles;
3265
+ var listWorkingDirectoryFiles = async (repositoryPath, trackedDirectories, relativePath = "") => {
3266
+ const directoryPath = relativePath ? (0, path.join)(repositoryPath, relativePath) : repositoryPath;
3267
+ const entries = await fs_promises.default.readdir(directoryPath, { withFileTypes: true });
3268
+ const files = [];
3269
+ for (const entry of entries) {
3270
+ if (entry.name === ".git") continue;
3271
+ const entryPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
3272
+ if (entry.isDirectory()) {
3273
+ if (!trackedDirectories.has(entryPath)) {
3274
+ if (await isomorphic_git.isIgnored({
3275
+ fs: fs_promises.default,
3276
+ dir: repositoryPath,
3277
+ filepath: entryPath
3278
+ })) continue;
3279
+ }
3280
+ files.push(...await listWorkingDirectoryFiles(repositoryPath, trackedDirectories, entryPath));
3281
+ continue;
3282
+ }
3283
+ if (entry.isFile() || entry.isSymbolicLink()) files.push(entryPath);
3284
+ }
3285
+ return files;
2894
3286
  };
2895
- var iterateSequentially = async (walk, children) => {
2896
- const results = [];
2897
- for (const child of children) results.push(await walk(child));
2898
- return results;
3287
+ var calculateBlobOid = async (filePath) => {
3288
+ const content = await fs_promises.default.readFile(filePath);
3289
+ return (0, crypto.createHash)("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
2899
3290
  };
2900
- var getModifiedFiles = async (repositoryPath) => {
3291
+ var getModifiedFiles = async (repositoryPath, headTreeOid) => {
2901
3292
  try {
2902
- return await isomorphic_git.walk({
2903
- fs: fs_promises.default,
2904
- dir: repositoryPath,
2905
- trees: [
2906
- isomorphic_git.TREE({ ref: "HEAD" }),
2907
- isomorphic_git.WORKDIR(),
2908
- isomorphic_git.STAGE()
2909
- ],
2910
- map: async (filepath, entries) => {
2911
- const [head, workdir, stage] = entries;
2912
- if (!head && !stage && workdir) {
2913
- if (await isomorphic_git.isIgnored({
2914
- fs: fs_promises.default,
2915
- dir: repositoryPath,
2916
- filepath
2917
- })) return null;
3293
+ const gitDir = await getActualGitDir(repositoryPath);
3294
+ const [headFiles, indexEntries] = await Promise.all([listTreeFiles(repositoryPath, headTreeOid), parseGitIndex(gitDir)]);
3295
+ const workdirFiles = await listWorkingDirectoryFiles(repositoryPath, listTrackedDirectories(indexEntries));
3296
+ const modifiedFiles = /* @__PURE__ */ new Map();
3297
+ const rememberModifiedFile = (path$5, reason) => {
3298
+ if (!modifiedFiles.has(path$5)) modifiedFiles.set(path$5, {
3299
+ path: path$5,
3300
+ reason
3301
+ });
3302
+ };
3303
+ for (const [path$6, headOid] of headFiles.entries()) {
3304
+ const indexEntry = indexEntries.get(path$6);
3305
+ if (!indexEntry) rememberModifiedFile(path$6, "staged");
3306
+ else if (indexEntry.stage !== 0 || indexEntry.oid !== headOid) rememberModifiedFile(path$6, "staged");
3307
+ }
3308
+ for (const indexEntry of indexEntries.values()) {
3309
+ if (!headFiles.has(indexEntry.path)) rememberModifiedFile(indexEntry.path, "staged");
3310
+ const absolutePath = (0, path.join)(repositoryPath, indexEntry.path);
3311
+ try {
3312
+ const stats = await fs_promises.default.lstat(absolutePath);
3313
+ if (!stats.isFile() && !stats.isSymbolicLink()) {
3314
+ rememberModifiedFile(indexEntry.path, "worktree");
3315
+ continue;
2918
3316
  }
2919
- const statusRow = await getStatusRow(filepath, entries);
2920
- if (!statusRow || !isModifiedFile(statusRow)) return;
2921
- return statusRow;
2922
- },
2923
- reduce: reduceModifiedFiles,
2924
- iterate: iterateSequentially
2925
- });
3317
+ if (indexEntry.stage !== 0) {
3318
+ rememberModifiedFile(indexEntry.path, "staged");
3319
+ continue;
3320
+ }
3321
+ if (indexEntry.size !== stats.size || await calculateBlobOid(absolutePath) !== indexEntry.oid) rememberModifiedFile(indexEntry.path, "worktree");
3322
+ } catch (error) {
3323
+ if (error.code === "ENOENT") {
3324
+ rememberModifiedFile(indexEntry.path, "worktree");
3325
+ continue;
3326
+ }
3327
+ throw error;
3328
+ }
3329
+ }
3330
+ const trackedPaths = new Set(indexEntries.keys());
3331
+ for (const filepath of workdirFiles) {
3332
+ if (trackedPaths.has(filepath)) continue;
3333
+ if (!await isomorphic_git.isIgnored({
3334
+ fs: fs_promises.default,
3335
+ dir: repositoryPath,
3336
+ filepath
3337
+ })) rememberModifiedFile(filepath, "untracked");
3338
+ }
3339
+ return Array.from(modifiedFiles.values());
2926
3340
  } catch (_unused5) {
2927
3341
  return [];
2928
3342
  }
2929
3343
  };
2930
- var formatModifiedFile = (modifiedFile) => {
2931
- return `'${modifiedFile[0]}':${modifiedFile[1]}:${modifiedFile[2]}:${modifiedFile[3]}`;
2932
- };
3344
+ var formatModifiedFile = (modifiedFile) => `'${modifiedFile.path}':${modifiedFile.reason}`;
2933
3345
  /**
2934
3346
  * Lookup version label recursively core analyzer
2935
3347
  * @param cwd - The directory to check
@@ -2938,7 +3350,7 @@ var formatModifiedFile = (modifiedFile) => {
2938
3350
  * @param commitToTags - Map of commit hash to tags for performance
2939
3351
  * @returns The version or undefined if no version is found
2940
3352
  */
2941
- var lookupVersionLabelRecursive = async (cwd, commit, reachedCommits, commitToTags) => {
3353
+ var lookupVersionLabelRecursive = async (context, commit, reachedCommits, commitToTags) => {
2942
3354
  const scheduledStack = [];
2943
3355
  let version = {
2944
3356
  major: 0,
@@ -2962,10 +3374,11 @@ var lookupVersionLabelRecursive = async (cwd, commit, reachedCommits, commitToTa
2962
3374
  try {
2963
3375
  const parentHashes = (await isomorphic_git.readCommit({
2964
3376
  fs: fs_promises.default,
2965
- dir: cwd,
3377
+ dir: context.dir,
3378
+ gitdir: context.gitdir,
2966
3379
  oid: currentCommit.hash
2967
3380
  })).commit.parent || [];
2968
- parentCommits = (await Promise.all(parentHashes.map((parentHash) => getCommit(cwd, parentHash)))).filter((ci) => ci !== void 0);
3381
+ parentCommits = (await Promise.all(parentHashes.map((parentHash) => getCommit(context, parentHash)))).filter((ci) => ci !== void 0);
2969
3382
  } catch (_unused6) {}
2970
3383
  if (parentCommits.length === 0) {
2971
3384
  reachedCommits.set(currentCommit.hash, version);
@@ -2980,7 +3393,7 @@ var lookupVersionLabelRecursive = async (cwd, commit, reachedCommits, commitToTa
2980
3393
  while (scheduledStack.length >= 1) {
2981
3394
  const { commit: scheduledCommit, parents } = scheduledStack.pop();
2982
3395
  if (parents.length >= 2) for (let index = 1; index < parents.length; index++) {
2983
- const alternateParentVersion = await lookupVersionLabelRecursive(cwd, parents[index], reachedCommits, commitToTags);
3396
+ const alternateParentVersion = await lookupVersionLabelRecursive(context, parents[index], reachedCommits, commitToTags);
2984
3397
  if (alternateParentVersion && compareVersions(alternateParentVersion, version) < 0) version = alternateParentVersion;
2985
3398
  }
2986
3399
  version = incrementLastVersionComponent(version);
@@ -3008,12 +3421,31 @@ var getGitMetadata = async (repositoryPath, checkWorkingDirectoryStatus, logger)
3008
3421
  logger.debug(`[screw-up] Total getGitMetadata: ${Date.now() - startTime}ms`);
3009
3422
  return metadata;
3010
3423
  }
3424
+ let gitContext;
3011
3425
  try {
3012
- const currentCommit = await getCurrentCommit(gitRootPath);
3013
- if (!currentCommit) {
3014
- logger.debug(`[screw-up] Total getGitMetadata: ${Date.now() - startTime}ms`);
3015
- return metadata;
3426
+ gitContext = await createGitReadContext(gitRootPath);
3427
+ } catch (error) {
3428
+ logger.warn(`Failed to resolve git metadata context: ${error}`);
3429
+ logger.debug(`[screw-up] Total getGitMetadata: ${Date.now() - startTime}ms`);
3430
+ return metadata;
3431
+ }
3432
+ const currentCommit = await getCurrentCommit(gitContext);
3433
+ if (!currentCommit) {
3434
+ logger.debug(`[screw-up] Total getGitMetadata: ${Date.now() - startTime}ms`);
3435
+ return metadata;
3436
+ }
3437
+ const gitMetadata = {
3438
+ tags: [],
3439
+ branches: [],
3440
+ commit: {
3441
+ hash: currentCommit.hash,
3442
+ shortHash: currentCommit.shortHash,
3443
+ date: dayjs(currentCommit.date).format("YYYY-MM-DDTHH:mm:ssZ"),
3444
+ message: currentCommit.message
3016
3445
  }
3446
+ };
3447
+ metadata.git = gitMetadata;
3448
+ try {
3017
3449
  const buildStart = Date.now();
3018
3450
  const commitToTags = await buildCompleteTagCache(gitRootPath, (tagName) => {
3019
3451
  const version = parseVersion(tagName);
@@ -3021,15 +3453,10 @@ var getGitMetadata = async (repositoryPath, checkWorkingDirectoryStatus, logger)
3021
3453
  }, logger);
3022
3454
  logger.debug(`[screw-up] buildCompleteTagCache: ${Date.now() - buildStart}ms`);
3023
3455
  logger.debug(`Built tag map with ${commitToTags.size} commits`);
3024
- let version = await lookupVersionLabelRecursive(gitRootPath, currentCommit, /* @__PURE__ */ new Map(), commitToTags);
3025
- const gitMetadata = {
3026
- tags: [],
3027
- branches: []
3028
- };
3029
- metadata.git = gitMetadata;
3456
+ let version = await lookupVersionLabelRecursive(gitContext, currentCommit, /* @__PURE__ */ new Map(), commitToTags);
3030
3457
  if (version) {
3031
3458
  if (checkWorkingDirectoryStatus) {
3032
- const modifiedFiles = await getModifiedFiles(gitRootPath);
3459
+ const modifiedFiles = await getModifiedFiles(gitRootPath, currentCommit.tree);
3033
3460
  if (modifiedFiles.length >= 1) {
3034
3461
  const newVersion = incrementLastVersionComponent(version);
3035
3462
  logger.debug(`Increased git version by detected modified items: ${formatVersion(version)} ---> ${formatVersion(newVersion)}, Files=[${modifiedFiles.map(formatModifiedFile).join(", ")}]`);
@@ -3040,16 +3467,14 @@ var getGitMetadata = async (repositoryPath, checkWorkingDirectoryStatus, logger)
3040
3467
  gitMetadata.version = gitVersion;
3041
3468
  metadata.version = gitVersion;
3042
3469
  }
3043
- gitMetadata.commit = {
3044
- hash: currentCommit.hash,
3045
- shortHash: currentCommit.shortHash,
3046
- date: dayjs(currentCommit.date).format("YYYY-MM-DDTHH:mm:ssZ"),
3047
- message: currentCommit.message
3048
- };
3049
3470
  gitMetadata.tags = getRelatedTagsFromMap(commitToTags, currentCommit.hash).map((tag) => tag.name);
3050
- gitMetadata.branches = await getRelatedBranches(gitRootPath, currentCommit.hash);
3051
3471
  } catch (error) {
3052
- logger.warn(`Failed to extract git metadata: ${error}`);
3472
+ logger.warn(`Failed to resolve git versioning metadata: ${error}`);
3473
+ }
3474
+ try {
3475
+ gitMetadata.branches = await getRelatedBranches(gitContext, currentCommit.hash);
3476
+ } catch (error) {
3477
+ logger.warn(`Failed to resolve git branch metadata: ${error}`);
3053
3478
  }
3054
3479
  logger.debug(`[screw-up] Total getGitMetadata: ${Date.now() - startTime}ms`);
3055
3480
  return metadata;
@@ -3946,7 +4371,7 @@ var publishCommand = async (args, logger) => {
3946
4371
  }
3947
4372
  };
3948
4373
  var showHelp = async () => {
3949
- const { author, license, repository_url, version, git_commit_hash } = await Promise.resolve().then(() => require("./packageMetadata-BDGBM3Fx.cjs"));
4374
+ const { author, license, repository_url, version, git_commit_hash } = await Promise.resolve().then(() => require("./packageMetadata-CaaD3Ehh.cjs"));
3950
4375
  console.info(`screw-up [${version}-${git_commit_hash}]
3951
4376
  Easy package metadata inserter CLI
3952
4377
  Copyright (c) ${author}