screw-up 1.29.0 → 1.31.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 (46) hide show
  1. package/dist/index.cjs +561 -100
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +502 -74
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/main.cjs +64 -31
  6. package/dist/main.cjs.map +1 -1
  7. package/dist/main.mjs +5 -5
  8. package/dist/main.mjs.map +1 -1
  9. package/dist/{metadata-file-CyQ2yue9.js → metadata-file-BWd04LhD.js} +63 -34
  10. package/dist/metadata-file-BWd04LhD.js.map +1 -0
  11. package/dist/{packageMetadata-CpakAG0S.cjs → packageMetadata-BDGBM3Fx.cjs} +3 -3
  12. package/dist/{packageMetadata-DnXbVLQ5.js → packageMetadata-BsMXJpMH.js} +6 -6
  13. package/dist/{packageMetadata-DnXbVLQ5.js.map → packageMetadata-BsMXJpMH.js.map} +1 -1
  14. package/dist/{packageMetadata-K_w0Knb7.cjs → packageMetadata-ip0rBTwa.cjs} +5 -5
  15. package/dist/{packageMetadata-K_w0Knb7.cjs.map → packageMetadata-ip0rBTwa.cjs.map} +1 -1
  16. package/dist/src/analyzer.d.ts +2 -2
  17. package/dist/src/analyzer.d.ts.map +1 -1
  18. package/dist/src/cli-internal.d.ts +3 -3
  19. package/dist/src/cli-internal.d.ts.map +1 -1
  20. package/dist/src/cli.d.ts +3 -3
  21. package/dist/src/cli.d.ts.map +1 -1
  22. package/dist/src/declaration-import-fix.d.ts +21 -0
  23. package/dist/src/declaration-import-fix.d.ts.map +1 -0
  24. package/dist/src/default-import-fix.d.ts +2 -2
  25. package/dist/src/default-import-fix.d.ts.map +1 -1
  26. package/dist/src/fast-tags.d.ts +2 -2
  27. package/dist/src/fast-tags.d.ts.map +1 -1
  28. package/dist/src/generated/packageMetadata.d.ts +4 -4
  29. package/dist/src/git-operations.d.ts +3 -3
  30. package/dist/src/git-operations.d.ts.map +1 -1
  31. package/dist/src/git-ref-utils.d.ts +25 -0
  32. package/dist/src/git-ref-utils.d.ts.map +1 -0
  33. package/dist/src/index.d.ts +4 -4
  34. package/dist/src/index.d.ts.map +1 -1
  35. package/dist/src/internal.d.ts +3 -3
  36. package/dist/src/main.d.ts +2 -2
  37. package/dist/src/metadata-file.d.ts +4 -4
  38. package/dist/src/metadata-file.d.ts.map +1 -1
  39. package/dist/src/text-edits.d.ts +24 -0
  40. package/dist/src/text-edits.d.ts.map +1 -0
  41. package/dist/src/types.d.ts +7 -2
  42. package/dist/src/types.d.ts.map +1 -1
  43. package/dist/src/vite-plugin.d.ts +3 -3
  44. package/dist/src/vite-plugin.d.ts.map +1 -1
  45. package/package.json +14 -10
  46. package/dist/metadata-file-CyQ2yue9.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
2
  * name: screw-up
3
- * version: 1.29.0
3
+ * version: 1.31.0
4
4
  * description: Simply package metadata inserter on Vite plugin
5
5
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
6
6
  * license: MIT
7
7
  * repository.url: https://github.com/kekyo/screw-up.git
8
- * git.commit.hash: 3833f6ef842d9e5a0b4f7277ca3b118f26fd4a6b
8
+ * git.commit.hash: ebb41ebf06ebe1bec39a3770c70a62cb95b4b7d6
9
9
  */
10
10
  //#region \0rolldown/runtime.js
11
11
  var __create = Object.create;
@@ -41,12 +41,15 @@ let crypto$1 = require("crypto");
41
41
  //#region node_modules/async-primitives/dist/index.mjs
42
42
  /*!
43
43
  * name: async-primitives
44
- * version: 1.5.0
44
+ * version: 1.7.0
45
45
  * description: A collection of primitive functions for asynchronous operations
46
46
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
47
47
  * license: MIT
48
48
  * repository.url: https://github.com/kekyo/async-primitives.git
49
- * git.commit.hash: cd35465b7e9b9945049186e7eaeecc0bfba65766
49
+ * git.commit.hash: 9472fbd5310b92690d84aaafb897429a04c013c5
50
+ */
51
+ /**
52
+ * A no-op Releasable object that does nothing when released or disposed
50
53
  */
51
54
  var __NOOP_HANDLER = () => {};
52
55
  var __NOOP_RELEASABLE = {
@@ -58,6 +61,12 @@ var toAbortError = (reason) => {
58
61
  if (typeof reason === "string") return new Error(reason);
59
62
  return /* @__PURE__ */ new Error("Operation aborted");
60
63
  };
64
+ /**
65
+ * Hooks up an abort handler to an AbortSignal and returns a handle for early cleanup
66
+ * @param signal - The AbortSignal to hook up to
67
+ * @param callback - The callback to call when the signal is aborted
68
+ * @returns A Releasable handle that can be used to remove the abort listener early
69
+ */
61
70
  var onAbort = (signal, callback) => {
62
71
  if (!signal) return __NOOP_RELEASABLE;
63
72
  if (signal.aborted) {
@@ -92,11 +101,21 @@ var onAbort = (signal, callback) => {
92
101
  [Symbol.dispose]: release
93
102
  };
94
103
  };
104
+ var runtimeGlobal$1 = globalThis;
95
105
  var defer = (fn) => {
96
- if (typeof setImmediate === "function") setImmediate(fn);
97
- else setTimeout(fn, 0);
106
+ const setImmediateHandler = runtimeGlobal$1.setImmediate;
107
+ if (typeof setImmediateHandler === "function") {
108
+ setImmediateHandler(fn);
109
+ return;
110
+ }
111
+ globalThis.setTimeout(fn, 0);
98
112
  };
99
113
  var ABORTED_ERROR$2 = () => /* @__PURE__ */ new Error("Lock acquisition was aborted");
114
+ /**
115
+ * Creates a new LockHandle instance
116
+ * @param releaseCallback Callback function to release the lock
117
+ * @returns A LockHandle object with release and dispose functionality
118
+ */
100
119
  var createLockHandle = (releaseCallback) => {
101
120
  let isActive = true;
102
121
  const release = () => {
@@ -112,15 +131,20 @@ var createLockHandle = (releaseCallback) => {
112
131
  [Symbol.dispose]: release
113
132
  };
114
133
  };
134
+ /**
135
+ * Creates a new Mutex instance
136
+ * @param maxConsecutiveCalls - The maximum number of consecutive calls to the lockAsync method before yielding control to the next item in the queue
137
+ * @returns A new Mutex for promise-based mutex operations
138
+ */
115
139
  var createMutex = (maxConsecutiveCalls = 20) => {
116
140
  let isLocked = false;
117
141
  const queue = [];
118
142
  let count = 0;
119
143
  const processQueue = () => {
120
- var _a;
144
+ var _item$signal;
121
145
  if (isLocked || queue.length === 0) return;
122
146
  const item = queue.shift();
123
- if ((_a = item.signal) == null ? void 0 : _a.aborted) {
147
+ if ((_item$signal = item.signal) === null || _item$signal === void 0 ? void 0 : _item$signal.aborted) {
124
148
  item.reject(ABORTED_ERROR$2());
125
149
  scheduleNextProcess();
126
150
  return;
@@ -198,8 +222,8 @@ createLogicalContext(Symbol("[root]"));
198
222
  //#endregion
199
223
  //#region src/generated/packageMetadata.ts
200
224
  var name = "screw-up";
201
- var version = "1.29.0";
202
- var git_commit_hash = "3833f6ef842d9e5a0b4f7277ca3b118f26fd4a6b";
225
+ var version = "1.31.0";
226
+ var git_commit_hash = "ebb41ebf06ebe1bec39a3770c70a62cb95b4b7d6";
203
227
  //#endregion
204
228
  //#region node_modules/json5/dist/index.js
205
229
  var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -1662,10 +1686,10 @@ var require_dayjs_min = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1662
1686
  //#region src/internal.ts
1663
1687
  var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1);
1664
1688
  var import_dayjs_min = /* @__PURE__ */ __toESM(require_dayjs_min(), 1);
1665
- var JSON5 = __resolveDefaultExport$2(import_dist.default, false);
1666
- var dayjs$1 = __resolveDefaultExport$2(import_dayjs_min.default, false);
1689
+ var JSON5 = __resolveDefaultExport$3(import_dist.default, false);
1690
+ var dayjs$1 = __resolveDefaultExport$3(import_dayjs_min.default, false);
1667
1691
  globalThis.__screwUpIsInCJS_db7919f73ec9 = true;
1668
- function __resolveDefaultExport$2(module, isESM) {
1692
+ function __resolveDefaultExport$3(module, isESM) {
1669
1693
  const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_db7919f73ec9 === true;
1670
1694
  const maybe = module;
1671
1695
  const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
@@ -1826,6 +1850,60 @@ var resolvePackageMetadata = async (projectRoot, fetchGitMetadata, alwaysOverrid
1826
1850
  };
1827
1851
  };
1828
1852
  //#endregion
1853
+ //#region src/git-ref-utils.ts
1854
+ var git$1 = __resolveDefaultExport$2(isomorphic_git.default, false);
1855
+ globalThis.__screwUpIsInCJS_89cc61422477 = true;
1856
+ function __resolveDefaultExport$2(module, isESM) {
1857
+ const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_89cc61422477 === true;
1858
+ const maybe = module;
1859
+ const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
1860
+ const unwrapNamespaceDefault = (value) => {
1861
+ if (!value || typeof value !== "object") return value;
1862
+ const inner = value;
1863
+ if ((inner.__esModule === true || typeof Symbol !== "undefined" && inner[Symbol.toStringTag] === "Module") && "default" in inner) return inner.default;
1864
+ return value;
1865
+ };
1866
+ const resolvedDefault = hasDefault ? unwrapNamespaceDefault(maybe.default) : void 0;
1867
+ if (__isInCJS) return hasDefault ? resolvedDefault !== null && resolvedDefault !== void 0 ? resolvedDefault : module : module;
1868
+ if (isESM) {
1869
+ if (hasDefault) return resolvedDefault;
1870
+ throw new Error("Default export not found.");
1871
+ }
1872
+ return hasDefault ? resolvedDefault !== null && resolvedDefault !== void 0 ? resolvedDefault : module : module;
1873
+ }
1874
+ /**
1875
+ * Resolve the actual Git directory for repositories, worktrees, and submodules.
1876
+ * @param repoPath - Repository path
1877
+ * @returns The resolved Git directory path
1878
+ */
1879
+ var getActualGitDir = async (repoPath) => {
1880
+ const gitDir = (0, path.join)(repoPath, ".git");
1881
+ const gitStat = await (0, fs_promises.stat)(gitDir).catch(() => null);
1882
+ if (!(gitStat === null || gitStat === void 0 ? void 0 : gitStat.isFile())) return gitDir;
1883
+ const match = (await (0, fs_promises.readFile)(gitDir, "utf-8")).match(/^gitdir:\s*(.+)$/m);
1884
+ if (!match) return gitDir;
1885
+ return (0, path.isAbsolute)(match[1]) ? match[1] : (0, path.join)(repoPath, match[1]);
1886
+ };
1887
+ /**
1888
+ * Resolve a tag object OID to the commit OID it ultimately points to.
1889
+ * Lightweight tags are returned unchanged.
1890
+ * @param repoPath - Repository path
1891
+ * @param tagOid - Tag or commit OID
1892
+ * @returns Commit hash this tag points to
1893
+ */
1894
+ var resolveTagOidToCommit = async (repoPath, tagOid) => {
1895
+ try {
1896
+ var _tagObject$tag;
1897
+ const tagObject = await git$1.readTag({
1898
+ fs: fs_promises.default,
1899
+ dir: repoPath,
1900
+ oid: tagOid
1901
+ });
1902
+ if (tagObject === null || tagObject === void 0 || (_tagObject$tag = tagObject.tag) === null || _tagObject$tag === void 0 ? void 0 : _tagObject$tag.object) return tagObject.tag.object;
1903
+ } catch (_unused) {}
1904
+ return tagOid;
1905
+ };
1906
+ //#endregion
1829
1907
  //#region src/fast-tags.ts
1830
1908
  /**
1831
1909
  * Fast tag listing implementation that reads tags directly from filesystem
@@ -1876,13 +1954,7 @@ var readLooseTags = async (refsTagsPath) => {
1876
1954
  * @returns Array of all tag names
1877
1955
  */
1878
1956
  var listTagsFast = async (repoPath) => {
1879
- const gitDir = (0, path.join)(repoPath, ".git");
1880
- const gitStat = await (0, fs_promises.stat)(gitDir).catch(() => null);
1881
- let actualGitDir = gitDir;
1882
- if (gitStat === null || gitStat === void 0 ? void 0 : gitStat.isFile()) {
1883
- const match = (await (0, fs_promises.readFile)(gitDir, "utf-8")).match(/^gitdir:\s*(.+)$/m);
1884
- if (match) actualGitDir = (0, path.isAbsolute)(match[1]) ? match[1] : (0, path.join)(repoPath, match[1]);
1885
- }
1957
+ const actualGitDir = await getActualGitDir(repoPath);
1886
1958
  const [packedTags, looseTags] = await Promise.all([parsePackedRefs((0, path.join)(actualGitDir, "packed-refs")), readLooseTags((0, path.join)(actualGitDir, "refs", "tags"))]);
1887
1959
  const allTags = new Set([...packedTags, ...looseTags]);
1888
1960
  return Array.from(allTags).sort();
@@ -1895,14 +1967,8 @@ var listTagsFast = async (repoPath) => {
1895
1967
  */
1896
1968
  var resolveTagsBatchWithCommit = async (repoPath, tagNames, logger) => {
1897
1969
  const startTime = Date.now();
1898
- const gitDir = (0, path.join)(repoPath, ".git");
1899
1970
  const result = /* @__PURE__ */ new Map();
1900
- const gitStat = await (0, fs_promises.stat)(gitDir).catch(() => null);
1901
- let actualGitDir = gitDir;
1902
- if (gitStat === null || gitStat === void 0 ? void 0 : gitStat.isFile()) {
1903
- const match = (await (0, fs_promises.readFile)(gitDir, "utf-8")).match(/^gitdir:\s*(.+)$/m);
1904
- if (match) actualGitDir = (0, path.isAbsolute)(match[1]) ? match[1] : (0, path.join)(repoPath, match[1]);
1905
- }
1971
+ const actualGitDir = await getActualGitDir(repoPath);
1906
1972
  const tagSet = new Set(tagNames);
1907
1973
  const packedRefsStart = Date.now();
1908
1974
  try {
@@ -1933,16 +1999,7 @@ var resolveTagsBatchWithCommit = async (repoPath, tagNames, logger) => {
1933
1999
  const looseRefPath = (0, path.join)(actualGitDir, "refs", "tags", tagName);
1934
2000
  try {
1935
2001
  const oid = (await (0, fs_promises.readFile)(looseRefPath, "utf-8")).trim();
1936
- let commitOid = oid;
1937
- try {
1938
- const { execSync } = require("child_process");
1939
- if (execSync(`git -C "${repoPath}" cat-file -t ${oid}`, { encoding: "utf-8" }).trim() === "tag") {
1940
- const objectMatch = execSync(`git -C "${repoPath}" cat-file -p ${oid}`, { encoding: "utf-8" }).match(/^object ([0-9a-f]{40})$/m);
1941
- if (objectMatch) commitOid = objectMatch[1];
1942
- }
1943
- } catch (error) {
1944
- logger.debug(`[fast-tags] Could not determine object type for ${tagName}: ${error}`);
1945
- }
2002
+ const commitOid = await resolveTagOidToCommit(repoPath, oid);
1946
2003
  result.set(tagName, {
1947
2004
  oid,
1948
2005
  commitOid
@@ -2458,6 +2515,375 @@ var getFetchGitMetadata = (targetDir, checkWorkingDirectoryStatus, logger) => {
2458
2515
  };
2459
2516
  };
2460
2517
  //#endregion
2518
+ //#region node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
2519
+ var comma = ",".charCodeAt(0);
2520
+ var semicolon = ";".charCodeAt(0);
2521
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2522
+ var intToChar = new Uint8Array(64);
2523
+ var charToInt = new Uint8Array(128);
2524
+ for (let i = 0; i < chars.length; i++) {
2525
+ const c = chars.charCodeAt(i);
2526
+ intToChar[i] = c;
2527
+ charToInt[c] = i;
2528
+ }
2529
+ function decodeInteger(reader, relative) {
2530
+ let value = 0;
2531
+ let shift = 0;
2532
+ let integer = 0;
2533
+ do {
2534
+ integer = charToInt[reader.next()];
2535
+ value |= (integer & 31) << shift;
2536
+ shift += 5;
2537
+ } while (integer & 32);
2538
+ const shouldNegate = value & 1;
2539
+ value >>>= 1;
2540
+ if (shouldNegate) value = -2147483648 | -value;
2541
+ return relative + value;
2542
+ }
2543
+ function encodeInteger(builder, num, relative) {
2544
+ let delta = num - relative;
2545
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
2546
+ do {
2547
+ let clamped = delta & 31;
2548
+ delta >>>= 5;
2549
+ if (delta > 0) clamped |= 32;
2550
+ builder.write(intToChar[clamped]);
2551
+ } while (delta > 0);
2552
+ return num;
2553
+ }
2554
+ function hasMoreVlq(reader, max) {
2555
+ if (reader.pos >= max) return false;
2556
+ return reader.peek() !== comma;
2557
+ }
2558
+ var bufLength = 1024 * 16;
2559
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
2560
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
2561
+ } } : { decode(buf) {
2562
+ let out = "";
2563
+ for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
2564
+ return out;
2565
+ } };
2566
+ var StringWriter = class {
2567
+ constructor() {
2568
+ this.pos = 0;
2569
+ this.out = "";
2570
+ this.buffer = new Uint8Array(bufLength);
2571
+ }
2572
+ write(v) {
2573
+ const { buffer } = this;
2574
+ buffer[this.pos++] = v;
2575
+ if (this.pos === bufLength) {
2576
+ this.out += td.decode(buffer);
2577
+ this.pos = 0;
2578
+ }
2579
+ }
2580
+ flush() {
2581
+ const { buffer, out, pos } = this;
2582
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
2583
+ }
2584
+ };
2585
+ var StringReader = class {
2586
+ constructor(buffer) {
2587
+ this.pos = 0;
2588
+ this.buffer = buffer;
2589
+ }
2590
+ next() {
2591
+ return this.buffer.charCodeAt(this.pos++);
2592
+ }
2593
+ peek() {
2594
+ return this.buffer.charCodeAt(this.pos);
2595
+ }
2596
+ indexOf(char) {
2597
+ const { buffer, pos } = this;
2598
+ const idx = buffer.indexOf(char, pos);
2599
+ return idx === -1 ? buffer.length : idx;
2600
+ }
2601
+ };
2602
+ function decode(mappings) {
2603
+ const { length } = mappings;
2604
+ const reader = new StringReader(mappings);
2605
+ const decoded = [];
2606
+ let genColumn = 0;
2607
+ let sourcesIndex = 0;
2608
+ let sourceLine = 0;
2609
+ let sourceColumn = 0;
2610
+ let namesIndex = 0;
2611
+ do {
2612
+ const semi = reader.indexOf(";");
2613
+ const line = [];
2614
+ let sorted = true;
2615
+ let lastCol = 0;
2616
+ genColumn = 0;
2617
+ while (reader.pos < semi) {
2618
+ let seg;
2619
+ genColumn = decodeInteger(reader, genColumn);
2620
+ if (genColumn < lastCol) sorted = false;
2621
+ lastCol = genColumn;
2622
+ if (hasMoreVlq(reader, semi)) {
2623
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
2624
+ sourceLine = decodeInteger(reader, sourceLine);
2625
+ sourceColumn = decodeInteger(reader, sourceColumn);
2626
+ if (hasMoreVlq(reader, semi)) {
2627
+ namesIndex = decodeInteger(reader, namesIndex);
2628
+ seg = [
2629
+ genColumn,
2630
+ sourcesIndex,
2631
+ sourceLine,
2632
+ sourceColumn,
2633
+ namesIndex
2634
+ ];
2635
+ } else seg = [
2636
+ genColumn,
2637
+ sourcesIndex,
2638
+ sourceLine,
2639
+ sourceColumn
2640
+ ];
2641
+ } else seg = [genColumn];
2642
+ line.push(seg);
2643
+ reader.pos++;
2644
+ }
2645
+ if (!sorted) sort(line);
2646
+ decoded.push(line);
2647
+ reader.pos = semi + 1;
2648
+ } while (reader.pos <= length);
2649
+ return decoded;
2650
+ }
2651
+ function sort(line) {
2652
+ line.sort(sortComparator);
2653
+ }
2654
+ function sortComparator(a, b) {
2655
+ return a[0] - b[0];
2656
+ }
2657
+ function encode(decoded) {
2658
+ const writer = new StringWriter();
2659
+ let sourcesIndex = 0;
2660
+ let sourceLine = 0;
2661
+ let sourceColumn = 0;
2662
+ let namesIndex = 0;
2663
+ for (let i = 0; i < decoded.length; i++) {
2664
+ const line = decoded[i];
2665
+ if (i > 0) writer.write(semicolon);
2666
+ if (line.length === 0) continue;
2667
+ let genColumn = 0;
2668
+ for (let j = 0; j < line.length; j++) {
2669
+ const segment = line[j];
2670
+ if (j > 0) writer.write(comma);
2671
+ genColumn = encodeInteger(writer, segment[0], genColumn);
2672
+ if (segment.length === 1) continue;
2673
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
2674
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
2675
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
2676
+ if (segment.length === 4) continue;
2677
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
2678
+ }
2679
+ }
2680
+ return writer.flush();
2681
+ }
2682
+ //#endregion
2683
+ //#region src/text-edits.ts
2684
+ var readNewlineAt = (value, index) => {
2685
+ if (index < 0 || index >= value.length) return;
2686
+ if (value.startsWith("\r\n", index)) return "\r\n";
2687
+ const char = value[index];
2688
+ if (char === "\n" || char === "\r") return char;
2689
+ };
2690
+ var findFirstNewline = (value) => {
2691
+ for (let index = 0; index < value.length; index++) {
2692
+ const newline = readNewlineAt(value, index);
2693
+ if (newline) return newline;
2694
+ }
2695
+ };
2696
+ var findPreviousNewline = (value, index) => {
2697
+ for (let current = index - 1; current >= 0; current--) {
2698
+ if (value[current] === "\n") return current > 0 && value[current - 1] === "\r" ? "\r\n" : "\n";
2699
+ if (value[current] === "\r") return "\r";
2700
+ }
2701
+ };
2702
+ var applyTextEdits = (value, edits) => {
2703
+ if (edits.length === 0) return value;
2704
+ const sorted = [...edits].sort((lhs, rhs) => rhs.start - lhs.start);
2705
+ let result = value;
2706
+ let previousStart = value.length;
2707
+ for (const edit of sorted) {
2708
+ if (edit.start > edit.end) throw new Error(`Invalid text edit range: ${edit.start} > ${edit.end}`);
2709
+ if (edit.end > previousStart) throw new Error("Overlapping text edits are not supported");
2710
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
2711
+ previousStart = edit.start;
2712
+ }
2713
+ return result;
2714
+ };
2715
+ var detectPreferredNewline = (value, start, end) => {
2716
+ var _findFirstNewline;
2717
+ const within = findFirstNewline(value.slice(start, end));
2718
+ if (within) return within;
2719
+ const adjacent = readNewlineAt(value, end);
2720
+ if (adjacent) return adjacent;
2721
+ const after = findFirstNewline(value.slice(end));
2722
+ if (after) return after;
2723
+ const before = findPreviousNewline(value, start);
2724
+ if (before) return before;
2725
+ return (_findFirstNewline = findFirstNewline(value)) !== null && _findFirstNewline !== void 0 ? _findFirstNewline : "\n";
2726
+ };
2727
+ var collectLineStarts = (value) => {
2728
+ const starts = [0];
2729
+ for (let index = 0; index < value.length; index++) {
2730
+ const char = value[index];
2731
+ if (char === "\r") {
2732
+ if (value[index + 1] === "\n") index += 1;
2733
+ starts.push(index + 1);
2734
+ continue;
2735
+ }
2736
+ if (char === "\n") starts.push(index + 1);
2737
+ }
2738
+ return starts;
2739
+ };
2740
+ var getLineColumnOffset = (lineStarts, offset) => {
2741
+ let low = 0;
2742
+ let high = lineStarts.length - 1;
2743
+ while (low <= high) {
2744
+ const middle = low + high >> 1;
2745
+ const lineStart = lineStarts[middle];
2746
+ const nextStart = middle + 1 < lineStarts.length ? lineStarts[middle + 1] : Number.MAX_SAFE_INTEGER;
2747
+ if (offset < lineStart) {
2748
+ high = middle - 1;
2749
+ continue;
2750
+ }
2751
+ if (offset >= nextStart) {
2752
+ low = middle + 1;
2753
+ continue;
2754
+ }
2755
+ return {
2756
+ line: middle,
2757
+ column: offset - lineStart
2758
+ };
2759
+ }
2760
+ const lastLine = Math.max(0, lineStarts.length - 1);
2761
+ return {
2762
+ line: lastLine,
2763
+ column: offset - lineStarts[lastLine]
2764
+ };
2765
+ };
2766
+ //#endregion
2767
+ //#region src/declaration-import-fix.ts
2768
+ var declarationFilePattern = /\.d\.(?:cts|mts|ts)$/;
2769
+ var isRelativeSpecifier = (specifier) => specifier.startsWith("./") || specifier.startsWith("../");
2770
+ var hasExplicitExtension = (specifier) => path.posix.extname(specifier) !== "";
2771
+ var getDeclarationRuntimeSuffix = (declarationPath) => {
2772
+ if (declarationPath.endsWith(".d.mts")) return ".mjs";
2773
+ if (declarationPath.endsWith(".d.cts")) return ".cjs";
2774
+ return ".js";
2775
+ };
2776
+ var createCandidateDeclarationPaths = (resolvedPath) => [
2777
+ `${resolvedPath}.d.ts`,
2778
+ `${resolvedPath}.d.mts`,
2779
+ `${resolvedPath}.d.cts`,
2780
+ (0, path.join)(resolvedPath, "index.d.ts"),
2781
+ (0, path.join)(resolvedPath, "index.d.mts"),
2782
+ (0, path.join)(resolvedPath, "index.d.cts")
2783
+ ];
2784
+ var resolveSpecifierSuffix = (specifier, importerPath, declarationFiles, logger) => {
2785
+ if (!isRelativeSpecifier(specifier) || hasExplicitExtension(specifier)) return;
2786
+ const resolvedPath = (0, path.resolve)((0, path.dirname)(importerPath), specifier);
2787
+ const matches = createCandidateDeclarationPaths(resolvedPath).filter((path$1) => declarationFiles.has(path$1));
2788
+ if (matches.length === 0) return;
2789
+ if (matches.length >= 2) {
2790
+ logger === null || logger === void 0 || logger.warn(`[fixDeclarationImports] Skipped ambiguous declaration import: ${specifier} (${matches.map((path$2) => {
2791
+ var _path$split$pop;
2792
+ return (_path$split$pop = path$2.split(/[/\\]/).pop()) !== null && _path$split$pop !== void 0 ? _path$split$pop : path$2;
2793
+ }).join(", ")})`);
2794
+ return;
2795
+ }
2796
+ const match = matches[0];
2797
+ const runtimeSuffix = getDeclarationRuntimeSuffix(match);
2798
+ const indexPrefix = (0, path.join)(resolvedPath, "index.");
2799
+ return match.startsWith(indexPrefix) ? `/index${runtimeSuffix}` : runtimeSuffix;
2800
+ };
2801
+ var collectModuleSpecifierEdits = (ts, sourceFile, importerPath, declarationFiles, logger) => {
2802
+ const edits = [];
2803
+ const seen = /* @__PURE__ */ new Set();
2804
+ const pushSpecifierEdit = (literal) => {
2805
+ const suffix = resolveSpecifierSuffix(literal.text, importerPath, declarationFiles, logger);
2806
+ if (!suffix) return;
2807
+ const insertionPoint = literal.getEnd() - 1;
2808
+ if (seen.has(insertionPoint)) return;
2809
+ seen.add(insertionPoint);
2810
+ edits.push({
2811
+ start: insertionPoint,
2812
+ end: insertionPoint,
2813
+ text: suffix
2814
+ });
2815
+ };
2816
+ const visit = (node) => {
2817
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
2818
+ if (node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) pushSpecifierEdit(node.moduleSpecifier);
2819
+ } else if (ts.isImportTypeNode(node)) {
2820
+ const argument = node.argument;
2821
+ if (ts.isLiteralTypeNode(argument) && ts.isStringLiteralLike(argument.literal)) pushSpecifierEdit(argument.literal);
2822
+ }
2823
+ node.forEachChild(visit);
2824
+ };
2825
+ sourceFile.forEachChild(visit);
2826
+ return edits;
2827
+ };
2828
+ var isDeclarationFilePath = (filePath) => declarationFilePattern.test(filePath);
2829
+ var fixDeclarationImportSpecifiers = (ts, code, filePath, declarationFiles, logger) => {
2830
+ const edits = collectModuleSpecifierEdits(ts, ts.createSourceFile(filePath, code, ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS), filePath, declarationFiles, logger);
2831
+ if (edits.length === 0) return {
2832
+ changed: false,
2833
+ code,
2834
+ edits
2835
+ };
2836
+ return {
2837
+ changed: true,
2838
+ code: applyTextEdits(code, edits),
2839
+ edits
2840
+ };
2841
+ };
2842
+ var adjustSourceMapForDeclarationEdits = (source, originalCode, edits) => {
2843
+ if (edits.length === 0) return;
2844
+ const original = typeof source === "string" ? source : Buffer.from(source).toString("utf-8");
2845
+ let map;
2846
+ try {
2847
+ map = JSON.parse(original);
2848
+ } catch (_unused) {
2849
+ return;
2850
+ }
2851
+ if (!map || typeof map.mappings !== "string") return;
2852
+ const lineStarts = collectLineStarts(originalCode);
2853
+ const lineDeltas = /* @__PURE__ */ new Map();
2854
+ for (const edit of edits) {
2855
+ var _lineDeltas$get;
2856
+ if (edit.start !== edit.end) return;
2857
+ if (edit.text.includes("\n") || edit.text.includes("\r")) return;
2858
+ const position = getLineColumnOffset(lineStarts, edit.start);
2859
+ const entries = (_lineDeltas$get = lineDeltas.get(position.line)) !== null && _lineDeltas$get !== void 0 ? _lineDeltas$get : [];
2860
+ entries.push({
2861
+ column: position.column,
2862
+ delta: edit.text.length
2863
+ });
2864
+ lineDeltas.set(position.line, entries);
2865
+ }
2866
+ if (lineDeltas.size === 0) return;
2867
+ const decodedMappings = decode(map.mappings);
2868
+ for (const [line, entries] of lineDeltas.entries()) {
2869
+ const segments = decodedMappings[line];
2870
+ if (!segments || segments.length === 0) continue;
2871
+ const sortedEntries = [...entries].sort((lhs, rhs) => lhs.column - rhs.column);
2872
+ let entryIndex = 0;
2873
+ let cumulativeDelta = 0;
2874
+ for (const segment of segments) {
2875
+ while (entryIndex < sortedEntries.length && sortedEntries[entryIndex].column <= segment[0]) {
2876
+ cumulativeDelta += sortedEntries[entryIndex].delta;
2877
+ entryIndex += 1;
2878
+ }
2879
+ segment[0] += cumulativeDelta;
2880
+ }
2881
+ }
2882
+ map.mappings = encode(decodedMappings);
2883
+ const serialized = JSON.stringify(map);
2884
+ return original.endsWith("\n") ? `${serialized}\n` : serialized;
2885
+ };
2886
+ //#endregion
2461
2887
  //#region src/default-import-fix.ts
2462
2888
  var importConditions = [
2463
2889
  "import",
@@ -2599,45 +3025,46 @@ var cjsInteropGlobalFlagAssignmentPattern = new RegExp(`\\bglobalThis\\.${cjsInt
2599
3025
  var createCjsInteropHelperId = (seed) => {
2600
3026
  return (0, crypto$1.createHash)("sha256").update(seed).digest("hex").slice(0, cjsInteropIdLength);
2601
3027
  };
2602
- var buildHelperFunctionSource = (helperId) => `
2603
- globalThis.${cjsInteropGlobalFlagPrefix}${helperId} = false;
2604
- function __resolveDefaultExport<T>(module: T | { default?: T }, isESM: boolean): T {
2605
- const __isInCJS =
2606
- typeof globalThis !== 'undefined' &&
2607
- (globalThis as any).${cjsInteropGlobalFlagPrefix}${helperId} === true;
2608
- const maybe = module as { default?: T };
2609
- const hasDefault = !!(maybe && typeof maybe === 'object' && 'default' in maybe);
2610
- const unwrapNamespaceDefault = (value: unknown): unknown => {
2611
- if (!value || typeof value !== 'object') {
2612
- return value;
2613
- }
2614
- const inner = value as any;
2615
- const isModule =
2616
- inner.__esModule === true ||
2617
- (typeof Symbol !== 'undefined' &&
2618
- (inner as any)[Symbol.toStringTag] === 'Module');
2619
- if (isModule && 'default' in inner) {
2620
- return inner.default;
2621
- }
2622
- return value;
2623
- };
2624
- const resolvedDefault = hasDefault
2625
- ? unwrapNamespaceDefault((maybe as any).default)
2626
- : undefined;
2627
-
2628
- if (__isInCJS) {
2629
- return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);
2630
- }
2631
-
2632
- if (isESM) {
2633
- if (hasDefault) {
2634
- return resolvedDefault as T;
2635
- }
2636
- throw new Error('Default export not found.');
2637
- }
2638
-
2639
- return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);
2640
- }`;
3028
+ var buildHelperFunctionSource = (helperId, newline) => [
3029
+ `globalThis.${cjsInteropGlobalFlagPrefix}${helperId} = false;`,
3030
+ "function __resolveDefaultExport<T>(module: T | { default?: T }, isESM: boolean): T {",
3031
+ " const __isInCJS =",
3032
+ " typeof globalThis !== 'undefined' &&",
3033
+ ` (globalThis as any).${cjsInteropGlobalFlagPrefix}${helperId} === true;`,
3034
+ " const maybe = module as { default?: T };",
3035
+ " const hasDefault = !!(maybe && typeof maybe === 'object' && 'default' in maybe);",
3036
+ " const unwrapNamespaceDefault = (value: unknown): unknown => {",
3037
+ " if (!value || typeof value !== 'object') {",
3038
+ " return value;",
3039
+ " }",
3040
+ " const inner = value as any;",
3041
+ " const isModule =",
3042
+ " inner.__esModule === true ||",
3043
+ " (typeof Symbol !== 'undefined' &&",
3044
+ " (inner as any)[Symbol.toStringTag] === 'Module');",
3045
+ " if (isModule && 'default' in inner) {",
3046
+ " return inner.default;",
3047
+ " }",
3048
+ " return value;",
3049
+ " };",
3050
+ " const resolvedDefault = hasDefault",
3051
+ " ? unwrapNamespaceDefault((maybe as any).default)",
3052
+ " : undefined;",
3053
+ "",
3054
+ " if (__isInCJS) {",
3055
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
3056
+ " }",
3057
+ "",
3058
+ " if (isESM) {",
3059
+ " if (hasDefault) {",
3060
+ " return resolvedDefault as T;",
3061
+ " }",
3062
+ " throw new Error('Default export not found.');",
3063
+ " }",
3064
+ "",
3065
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
3066
+ "}"
3067
+ ].join(newline);
2641
3068
  var injectCjsInteropFlag = (code) => {
2642
3069
  let changed = false;
2643
3070
  return {
@@ -2748,7 +3175,8 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
2748
3175
  if (importClause.namedBindings && ts.isNamedImports(importClause.namedBindings)) replacementImports.push(buildNamedImport(moduleName, importClause.namedBindings));
2749
3176
  }
2750
3177
  const interopSource = (_namespaceName = namespaceName) !== null && _namespaceName !== void 0 ? _namespaceName : defaultImportName;
2751
- const replacement = `${replacementImports.join("\n")}\nconst ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
3178
+ const newline = detectPreferredNewline(code, statement.getStart(sourceFile), statement.getEnd());
3179
+ const replacement = `${replacementImports.join(newline)}${newline}const ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
2752
3180
  edits.push({
2753
3181
  start: statement.getStart(sourceFile),
2754
3182
  end: statement.getEnd(),
@@ -2764,20 +3192,17 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
2764
3192
  const importStatements = sourceFile.statements.filter(ts.isImportDeclaration);
2765
3193
  const lastImport = importStatements[importStatements.length - 1];
2766
3194
  if (lastImport) {
2767
- const newline = code.includes("\r\n") ? "\r\n" : "\n";
3195
+ const newline = detectPreferredNewline(code, lastImport.getStart(sourceFile), lastImport.getEnd());
2768
3196
  const helperId = createCjsInteropHelperId(normalizedId);
2769
3197
  edits.push({
2770
3198
  start: lastImport.getEnd(),
2771
3199
  end: lastImport.getEnd(),
2772
- text: `${newline}${buildHelperFunctionSource(helperId)}${newline}`
3200
+ text: `${newline}${buildHelperFunctionSource(helperId, newline)}${newline}`
2773
3201
  });
2774
3202
  }
2775
3203
  }
2776
- edits.sort((a, b) => b.start - a.start);
2777
- let nextCode = code;
2778
- for (const edit of edits) nextCode = nextCode.slice(0, edit.start) + edit.text + nextCode.slice(edit.end);
2779
3204
  return {
2780
- code: nextCode,
3205
+ code: applyTextEdits(code, edits),
2781
3206
  changed: true
2782
3207
  };
2783
3208
  };
@@ -2949,7 +3374,7 @@ var screwUp = (options = {}) => {
2949
3374
  "license",
2950
3375
  "repository.url",
2951
3376
  "git.commit.hash"
2952
- ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true } = options;
3377
+ ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true, fixDeclarationImportExtensions = true } = options;
2953
3378
  const assetFiltersRegex = assetFilters.map((filter) => new RegExp(filter));
2954
3379
  const generateMetadataSourceLocker = createMutex();
2955
3380
  const resolveModuleKind = createNodeModuleKindResolver();
@@ -3128,29 +3553,65 @@ var screwUp = (options = {}) => {
3128
3553
  }
3129
3554
  },
3130
3555
  writeBundle: async (options) => {
3131
- if (!insertMetadataBanner || !options.dir) return;
3556
+ if (!options.dir) return;
3132
3557
  try {
3133
3558
  const files = await (0, fs_promises.readdir)(options.dir, { recursive: true });
3134
- let count = 0;
3559
+ const declarationFiles = new Set(files.filter((file) => isDeclarationFilePath(file)).map((file) => (0, path.resolve)(options.dir, file)));
3560
+ const ts = fixDeclarationImportExtensions ? await loadTypeScript() : void 0;
3561
+ let bannerCount = 0;
3562
+ let declarationCount = 0;
3135
3563
  for (const file of files) {
3136
3564
  const filePath = (0, path.join)(options.dir, file);
3137
- if (assetFiltersRegex.some((filter) => filter.test(file))) try {
3138
- const content = await (0, fs_promises.readFile)(filePath, "utf-8");
3139
- if (!content.includes(banner)) {
3140
- const bannerBlock = `${banner}\n`;
3141
- await (0, fs_promises.writeFile)(filePath, insertBannerHeader(content, bannerBlock));
3142
- const lineOffset = countInsertedLines(bannerBlock);
3143
- const mapPath = `${filePath}.map`;
3565
+ const isAssetTarget = assetFiltersRegex.some((filter) => filter.test(file));
3566
+ const isDeclarationTarget = fixDeclarationImportExtensions && !!ts && isDeclarationFilePath(filePath);
3567
+ if (!isAssetTarget && !isDeclarationTarget) continue;
3568
+ try {
3569
+ let content = await (0, fs_promises.readFile)(filePath, "utf-8");
3570
+ let contentChanged = false;
3571
+ let mapLoaded = false;
3572
+ let mapContent;
3573
+ const mapPath = `${filePath}.map`;
3574
+ const loadMapContent = async () => {
3575
+ if (mapLoaded) return mapContent;
3576
+ mapLoaded = true;
3144
3577
  try {
3145
- const adjusted = applyLineOffsetToSourceMap(await (0, fs_promises.readFile)(mapPath, "utf-8"), lineOffset);
3146
- if (adjusted !== void 0) await (0, fs_promises.writeFile)(mapPath, adjusted);
3147
- } catch (_unused2) {}
3148
- count++;
3578
+ mapContent = await (0, fs_promises.readFile)(mapPath, "utf-8");
3579
+ } catch (_unused2) {
3580
+ mapContent = void 0;
3581
+ }
3582
+ return mapContent;
3583
+ };
3584
+ if (insertMetadataBanner && isAssetTarget && !content.includes(banner)) {
3585
+ const bannerBlock = `${banner}\n`;
3586
+ content = insertBannerHeader(content, bannerBlock);
3587
+ contentChanged = true;
3588
+ const currentMapContent = await loadMapContent();
3589
+ if (currentMapContent !== void 0) {
3590
+ const adjusted = applyLineOffsetToSourceMap(currentMapContent, countInsertedLines(bannerBlock));
3591
+ if (adjusted !== void 0) mapContent = adjusted;
3592
+ }
3593
+ bannerCount++;
3594
+ }
3595
+ if (isDeclarationTarget) {
3596
+ const declarationResult = fixDeclarationImportSpecifiers(ts, content, filePath, declarationFiles, logger);
3597
+ if (declarationResult.changed) {
3598
+ const currentMapContent = await loadMapContent();
3599
+ if (currentMapContent !== void 0) {
3600
+ const adjusted = adjustSourceMapForDeclarationEdits(currentMapContent, content, declarationResult.edits);
3601
+ if (adjusted !== void 0) mapContent = adjusted;
3602
+ }
3603
+ content = declarationResult.code;
3604
+ contentChanged = true;
3605
+ declarationCount++;
3606
+ }
3149
3607
  }
3150
- } catch (error) {}
3608
+ if (contentChanged) await (0, fs_promises.writeFile)(filePath, content);
3609
+ if (mapLoaded && mapContent !== void 0) await (0, fs_promises.writeFile)(mapPath, mapContent);
3610
+ } catch (_unused3) {}
3151
3611
  }
3152
- if (count >= 1) logger.debug(`writeBundle: Banner header inserted: ${count} file(s)`);
3153
- } catch (error) {}
3612
+ if (bannerCount >= 1) logger.debug(`writeBundle: Banner header inserted: ${bannerCount} file(s)`);
3613
+ if (declarationCount >= 1) logger.debug(`writeBundle: Declaration imports fixed: ${declarationCount} file(s)`);
3614
+ } catch (_unused4) {}
3154
3615
  }
3155
3616
  };
3156
3617
  };