binary-collections 2.0.7 → 2.0.9

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 (155) hide show
  1. package/bin/dir-tree.cmd +7 -0
  2. package/bin/git-diff +4 -0
  3. package/bin/git-diff.cmd +5 -2
  4. package/bin/{git-fix-encoding → git-fix} +1 -4
  5. package/bin/git-fix.cmd +7 -0
  6. package/bin/nodekill +0 -0
  7. package/bin/nodekill.ps1 +0 -0
  8. package/bin/{submodule → submodule.txt} +0 -0
  9. package/lib/binary-collections-config.cjs +14 -0
  10. package/lib/binary-collections-config.d.mts +18 -0
  11. package/lib/binary-collections-config.d.ts +16 -0
  12. package/lib/binary-collections-config.js +39 -0
  13. package/lib/binary-collections-config.mjs +6 -0
  14. package/lib/binary-collections.cjs +123 -0
  15. package/lib/binary-collections.d.cts +2 -0
  16. package/lib/binary-collections.d.mts +137 -0
  17. package/lib/binary-collections.d.ts +137 -0
  18. package/lib/binary-collections.mjs +300 -0
  19. package/lib/changelog.cjs +328 -0
  20. package/lib/changelog.d.mts +2 -0
  21. package/lib/changelog.d.ts +1 -0
  22. package/lib/changelog.js +226 -0
  23. package/lib/changelog.mjs +199 -0
  24. package/lib/chunk-4BYBVEYC.mjs +30 -0
  25. package/lib/{chunk-FB6YIQYR.mjs → chunk-AASHBCRW.mjs} +17 -2
  26. package/lib/chunk-APBWENF6.mjs +135 -0
  27. package/lib/{chunk-4LEXWIIF.mjs → chunk-DPKAJKFO.mjs} +2 -4
  28. package/lib/chunk-EGSSKVDH.mjs +66 -0
  29. package/lib/{chunk-3LOB2P54.mjs → chunk-G3THLIDT.mjs} +3 -5
  30. package/lib/chunk-JGR2NW6D.mjs +187 -0
  31. package/lib/chunk-ONIBBBQ3.mjs +108 -0
  32. package/lib/chunk-SH3L6HHV.mjs +27 -0
  33. package/lib/chunk-VVEZVNIV.mjs +81 -0
  34. package/lib/{chunk-JL32QDSH.mjs → chunk-W3ENOM53.mjs} +2 -4
  35. package/lib/chunk-YV7DO3YV.mjs +48 -0
  36. package/lib/{chunk-BSD5CIRU.mjs → chunk-YX5U7XDR.mjs} +11 -5
  37. package/lib/chunk-ZYAQRPUL.mjs +28 -0
  38. package/lib/clean-github-actions-caches.cjs +162 -0
  39. package/lib/clean-github-actions-caches.d.cts +1 -0
  40. package/lib/clean-github-actions-caches.d.mts +169 -0
  41. package/lib/clean-github-actions-caches.d.ts +169 -0
  42. package/lib/clean-github-actions-caches.mjs +132 -0
  43. package/lib/del-gradle.cjs +87 -3
  44. package/lib/del-gradle.js +1 -1
  45. package/lib/del-gradle.mjs +4 -6
  46. package/lib/del-node-modules.cjs +86 -2
  47. package/lib/del-node-modules.mjs +3 -5
  48. package/lib/del-ps.cjs +89 -5
  49. package/lib/del-ps.js +2 -2
  50. package/lib/del-ps.mjs +6 -8
  51. package/lib/del-yarn-caches.cjs +86 -2
  52. package/lib/del-yarn-caches.mjs +3 -5
  53. package/lib/find-node-modules-cli.cjs +8 -0
  54. package/lib/find-node-modules-cli.mjs +2 -3
  55. package/lib/find-node-modules.cjs +8 -0
  56. package/lib/find-node-modules.d.mts +3 -0
  57. package/lib/find-node-modules.d.ts +3 -0
  58. package/lib/find-node-modules.js +12 -0
  59. package/lib/find-node-modules.mjs +2 -3
  60. package/lib/git/gitattributes.cjs +171 -0
  61. package/lib/git/gitattributes.d.mts +35 -0
  62. package/lib/git/gitattributes.d.ts +33 -0
  63. package/lib/git/gitattributes.js +223 -0
  64. package/lib/git/gitattributes.mjs +6 -0
  65. package/lib/git/line-endings.cjs +74 -0
  66. package/lib/git/line-endings.d.cts +7 -0
  67. package/lib/git/line-endings.d.mts +83 -0
  68. package/lib/git/line-endings.d.ts +83 -0
  69. package/lib/git/line-endings.mjs +8 -0
  70. package/lib/git/normalize.cjs +42 -0
  71. package/lib/git/normalize.d.cts +6 -0
  72. package/lib/git/normalize.d.mts +43 -0
  73. package/lib/git/normalize.d.ts +43 -0
  74. package/lib/git/normalize.mjs +6 -0
  75. package/lib/git/permissions.cjs +15 -0
  76. package/lib/git/permissions.d.cts +6 -0
  77. package/lib/git/permissions.d.mts +17 -0
  78. package/lib/git/permissions.d.ts +17 -0
  79. package/lib/git/permissions.mjs +7 -0
  80. package/lib/git/pull-strategy.cjs +13 -0
  81. package/lib/git/pull-strategy.d.cts +5 -0
  82. package/lib/git/pull-strategy.d.mts +15 -0
  83. package/lib/git/pull-strategy.d.ts +15 -0
  84. package/lib/git/pull-strategy.mjs +7 -0
  85. package/lib/git/user-config.cjs +100 -0
  86. package/lib/git/user-config.d.cts +10 -0
  87. package/lib/git/user-config.d.mts +105 -0
  88. package/lib/git/user-config.d.ts +105 -0
  89. package/lib/git/user-config.mjs +8 -0
  90. package/lib/git/utils.cjs +70 -0
  91. package/lib/git/utils.d.cts +20 -0
  92. package/lib/git/utils.d.mts +69 -0
  93. package/lib/git/utils.d.ts +69 -0
  94. package/lib/git/utils.mjs +6 -0
  95. package/lib/git-diff.cjs +23 -24
  96. package/lib/git-diff.d.mts +25 -28
  97. package/lib/git-diff.d.ts +25 -28
  98. package/lib/git-diff.mjs +32 -27
  99. package/lib/git-fix.cjs +129 -0
  100. package/lib/git-fix.d.cts +2 -0
  101. package/lib/git-fix.d.mts +141 -0
  102. package/lib/git-fix.d.ts +141 -0
  103. package/lib/git-fix.mjs +151 -0
  104. package/lib/git-purge.cjs +86 -2
  105. package/lib/git-purge.mjs +3 -5
  106. package/lib/index.cjs +8 -0
  107. package/lib/index.mjs +3 -5
  108. package/lib/npm-run-series.cjs +140 -1
  109. package/lib/npm-run-series.js +2 -1
  110. package/lib/npm-run-series.mjs +7 -5
  111. package/lib/package-resolutions-updater.cjs +447 -0
  112. package/lib/package-resolutions-updater.d.mts +1 -0
  113. package/lib/package-resolutions-updater.d.ts +352 -0
  114. package/lib/package-resolutions-updater.mjs +339 -0
  115. package/lib/print-directory-tree.cjs +241 -0
  116. package/lib/print-directory-tree.d.cts +1 -0
  117. package/lib/print-directory-tree.d.mts +234 -0
  118. package/lib/print-directory-tree.d.ts +234 -0
  119. package/lib/print-directory-tree.mjs +182 -0
  120. package/lib/ps/connected-domain.mjs +2 -3
  121. package/lib/ps/index.cjs +3 -3
  122. package/lib/ps/index.d.mjs +1 -2
  123. package/lib/ps/index.js +6 -3
  124. package/lib/ps/index.mjs +9 -11
  125. package/lib/ps/isWin.mjs +2 -3
  126. package/lib/ps/table-parser.mjs +3 -4
  127. package/lib/submodule-install.cjs +18 -35
  128. package/lib/submodule-install.d.mts +17 -37
  129. package/lib/submodule-install.d.ts +17 -37
  130. package/lib/submodule-install.mjs +21 -29
  131. package/lib/utils.cjs +86 -2
  132. package/lib/utils.d.mts +29 -9
  133. package/lib/utils.d.ts +28 -8
  134. package/lib/utils.js +139 -8
  135. package/lib/utils.mjs +2 -3
  136. package/lib/yarn-reinstall.cjs +9 -7
  137. package/lib/yarn-reinstall.d.mts +12 -8
  138. package/lib/yarn-reinstall.d.ts +12 -8
  139. package/lib/yarn-reinstall.mjs +14 -10
  140. package/package.json +109 -80
  141. package/readme.md +74 -11
  142. package/src/package-resolutions-updater.mjs +350 -0
  143. package/src/print-directory-tree.cjs +234 -0
  144. package/src/ps/index.js +4 -3
  145. package/src/yarn-reinstall.cjs +49 -0
  146. package/test-project/package.json +16 -0
  147. package/tmp/test-repo/package.json +7 -0
  148. package/bin/git-fix-encoding.cmd +0 -6
  149. package/lib/chunk-OKYLF2MU.mjs +0 -53
  150. package/lib/chunk-VXZQNLPU.mjs +0 -23
  151. package/lib/package-resolutions.cjs +0 -28
  152. package/lib/package-resolutions.d.mts +0 -25
  153. package/lib/package-resolutions.d.ts +0 -25
  154. package/lib/package-resolutions.mjs +0 -31
  155. /package/bin/{submodule-install → submodule-install.txt} +0 -0
package/readme.md CHANGED
@@ -24,9 +24,6 @@ npm install binary-collections
24
24
  # Install globally
25
25
  npm install binary-collections -g
26
26
 
27
- # Install from Git
28
- npm install binary-collections@git+https://github.com/dimaslanjaka/bin.git
29
-
30
27
  # Install from release archive
31
28
  npm install binary-collections@https://github.com/dimaslanjaka/bin/raw/master/releases/bin.tgz
32
29
  ```
@@ -77,14 +74,32 @@ Create `.vscode/settings.json` to add binary tools to your PATH:
77
74
 
78
75
  | Category | Tools | Description |
79
76
  |----------|-------|-------------|
80
- | **Git** | `git-purge`, `git-diff`, `git-fix-encoding`, `git-reduce-size` | Git repository management and optimization |
77
+ | **Git** | `git-purge`, `git-diff`, `git-fix`, `git-reduce-size` | Git repository management and optimization |
81
78
  | **Submodules** | `submodule`, `submodule-install`, `submodule-remove`, `submodule-token` | Git submodule operations |
82
79
  | **NPM Scripts** | `nrs`, `run-s`, `run-series`, `npm-run-series` | Run npm scripts in series with pattern matching |
83
- | **Package Mgmt** | `yarn-reinstall`, `package-resolutions` | Yarn package management utilities |
80
+ | **Package Mgmt** | `yarn-reinstall`, `pkg-resolutions-updater`, `pkg-res-updater` | Yarn/package resolutions management utilities |
84
81
  | **Node.js Dev** | `find-node-modules`, `find-nodemodules`, `dev`, `prod`, `empty` | Node.js development helpers |
85
82
  | **Process Mgmt** | `kill-process`, `nodekill`, `javakill`, `del-ps` | Process management and termination |
86
- | **File System** | `rmfind`, `rmpath`, `rmx` | File system operations |
83
+ | **File System** | `rmfind`, `rmpath`, `rmx`, `print-tree`, `dir-tree` | File system operations |
87
84
  | **Cleanup** | `del-nodemodules`, `del-yarncaches`, `del-gradle` | Cache and build directory cleanup |
85
+ | **GitHub Actions** | `clean-github-actions-caches`, `clean-github-actions-cache`, `clear-github-actions-cache`, `clear-github-actions-caches`, `clear-gh-caches` | Remove old GitHub Actions caches, keep only the latest |
86
+
87
+
88
+ ---
89
+ #### Binary List Generation & Source Code
90
+
91
+ The list of available binaries and utilities is automatically generated by the build script (`build.js`).
92
+ All CLI tools and binaries are collected from the `bin/`, `lib/`, and other relevant folders. The build process updates the `bin` field in `package.json` to reflect all available executables.
93
+
94
+ Source code for utilities is located in the [`src/`](./src/) folder. To update the binary list, run:
95
+
96
+ ```bash
97
+ yarn run build
98
+ # or
99
+ node build.js
100
+ ```
101
+
102
+ This will scan the project and update `package.json` with all available binaries. The list may change as files are added or removed from the project.
88
103
 
89
104
  For a complete list of available binaries and utilities, see:
90
105
  - [Binary executables](https://github.com/dimaslanjaka/bin/tree/master/bin)
@@ -109,13 +124,42 @@ Enhanced git diff functionality:
109
124
  git-diff
110
125
  ```
111
126
 
112
- #### Git Encoding Fixer
113
- Fix git file encoding issues:
127
+ #### Git Fix Utility
128
+ Comprehensive Git configuration fixer for cross-platform development (replaces the old `git-fix-encoding`):
114
129
 
115
130
  ```bash
116
- git-fix-encoding
131
+ git-fix # Apply all fixes
132
+ git-fix --lf-only # Force LF line endings only
133
+ git-fix --permissions # Ignore file permissions only
134
+ git-fix --normalize # Normalize existing files only
135
+ git-fix --user # Configure Git user from environment
136
+ git-fix --user NAME EMAIL # Configure Git user with specific values
137
+ git-fix --user --update-remote # Also update remote URL to match user
138
+ git-fix --user NAME EMAIL --update-remote # Configure user and update remote URL
117
139
  ```
118
140
 
141
+ Features:
142
+ - Forces LF line endings (`core.autocrlf = false`)
143
+ - Ignores file permission changes (`core.filemode = false`)
144
+ - Sets pull strategy to false (prevents auto-rebase)
145
+ - Normalizes existing line endings
146
+ - Creates/updates `.gitattributes` with proper line ending rules
147
+ - Configures Git user from environment variables or CLI arguments
148
+ - **Non-interactive:** All configuration is now argument-driven; no interactive prompts
149
+ - `--update-remote` flag: Update remote URL to match the configured user (for HTTPS remotes)
150
+
151
+ User Configuration:
152
+ - Environment variables: `GITHUB_USER`, `GITHUB_EMAIL`
153
+ - CLI arguments take precedence over environment variables
154
+ - Use `--update-remote` to update the remote URL with the configured user
155
+ - Examples:
156
+ ```bash
157
+ git-fix --user "John Doe" "john@example.com" # Use CLI args
158
+ git-fix --user --update-remote # Use env vars and update remote
159
+ git-fix --user "Jane" "jane@example.com" --update-remote # CLI args and update remote
160
+ GITHUB_USER="Jane" GITHUB_EMAIL="jane@example.com" git-fix --user # Use env vars
161
+ ```
162
+
119
163
  #### Git Repository Size Reducer
120
164
  Reduce git repository size by cleaning up history:
121
165
 
@@ -175,10 +219,11 @@ yarn-reinstall <packageName> [--dev|-D|--peer|-P|--optional|-O]
175
219
  ```
176
220
 
177
221
  #### Package Resolutions Manager
178
- Manage package resolutions in package.json:
222
+ Manage package resolutions in package.json (aliases: `pkg-resolutions-updater`, `pkg-res-updater`):
179
223
 
180
224
  ```bash
181
- package-resolutions
225
+ pkg-resolutions-updater
226
+ pkg-res-updater
182
227
  ```
183
228
 
184
229
  ### Node.js Development Tools
@@ -216,6 +261,24 @@ del-ps # Kill processes by command name
216
261
 
217
262
  ### Cleanup Tools
218
263
 
264
+ ### GitHub Actions Cache Cleaner
265
+
266
+ Remove old GitHub Actions caches, keeping only the most recent cache for each prefix:
267
+
268
+ ```bash
269
+ clean-github-actions-caches
270
+ ```
271
+
272
+ Features:
273
+ - Authenticates using `ACCESS_TOKEN` or `GITHUB_TOKEN` from your `.env` file
274
+ - Automatically groups and deletes caches by prefix, keeping only the latest
275
+ - Works for the current repository (origin remote)
276
+
277
+ Environment setup:
278
+ - Ensure your `.env` file contains `ACCESS_TOKEN` or `GITHUB_TOKEN`
279
+
280
+ Source: [`src/clean-github-actions-caches.cjs`](./src/clean-github-actions-caches.cjs)
281
+
219
282
  #### Node Modules Cleaner
220
283
  Remove node_modules directories recursively:
221
284
 
@@ -0,0 +1,350 @@
1
+ /**
2
+ * 📦 GitHub Package Resolver
3
+ *
4
+ * This script updates the commit hashes in `package.json`'s `resolutions` field
5
+ * for GitHub tarball URLs (typically using `raw/branch-name/...`) to point to the
6
+ * latest commit SHA of the corresponding repository and branch.
7
+ *
8
+ * 🔍 Features:
9
+ * - Parses GitHub URLs to extract repository owner, name, and branch.
10
+ * - Fetches the latest commit SHA across all branches using GitHub's API.
11
+ * - Replaces the old branch or commit in the URL with the latest SHA.
12
+ * - Overwrites `package.json` with the updated URLs.
13
+ *
14
+ * 🛠 Requirements:
15
+ * - GitHub Personal Access Token (GITHUB_TOKEN) via `.env`
16
+ * - ESM support (`type: "module"` in `package.json`)
17
+ * - Node.js v18+ recommended for ESM and `fetch` fallback compatibility
18
+ *
19
+ * 🧩 Dependencies:
20
+ * - `ansi-colors` – for styled terminal output
21
+ * - `dotenv` – to load GitHub token from `.env`
22
+ *
23
+ * ✅ Use case:
24
+ * - Ensures package resolutions always use immutable SHAs instead of mutable branch names.
25
+ * - Helps achieve deterministic builds in monorepos or projects with internal GitHub packages.
26
+ */
27
+
28
+ import ansiColors from "ansi-colors";
29
+ import * as dotenv from "dotenv";
30
+ import fs from "fs";
31
+ import https from "https";
32
+ import os from "os";
33
+ import path from "path";
34
+ import { getArgs } from "./utils.js";
35
+
36
+ const projectDir = process.cwd();
37
+ const envPath = path.join(projectDir, ".env");
38
+ const args = getArgs();
39
+ const ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
40
+
41
+ // Show help if --help/-h is passed
42
+ if (args.help || args.h) {
43
+ showHelp();
44
+ }
45
+
46
+ /**
47
+ * Display help information for the package-resolutions-updater script.
48
+ */
49
+ function showHelp() {
50
+ const helpText = `\n\
51
+ GitHub Package Resolutions Updater\n\
52
+ Usage:\n node src/package-resolutions-updater.mjs [options]\n\
53
+ Options:\n --help, -h Show this help message\n\
54
+ Description:\n Updates the commit hashes in package.json's 'resolutions' field for GitHub tarball URLs to point to the latest commit SHA of the corresponding repository and branch.\n\
55
+ Features:\n - Parses GitHub URLs to extract repository owner, name, and branch.\n - Fetches the latest commit SHA across all branches using GitHub's API.\n - Replaces the old branch or commit in the URL with the latest SHA.\n - Overwrites package.json with the updated URLs.\n\
56
+ Requirements:\n - GitHub Personal Access Token (GITHUB_TOKEN) via .env\n - ESM support (type: "module" in package.json)\n - Node.js v18+ recommended\n\
57
+ Dependencies:\n - ansi-colors – for styled terminal output\n - dotenv – to load GitHub token from .env\n\
58
+ Examples:\n node src/package-resolutions-updater.mjs\n node src/package-resolutions-updater.mjs --help\n\n`;
59
+ console.log(helpText);
60
+ process.exit(0);
61
+ }
62
+
63
+ // Load the .env file using dotenv (ESM import)
64
+ if (fs.existsSync(envPath)) dotenv.config({ path: envPath });
65
+
66
+ // 📌 Static override rules
67
+ const specialPackageOverrides = [
68
+ // SBG packages
69
+ { pkg: "sbg-utility", branch: "sbg-utility", repo: "static-blog-generator", owner: "dimaslanjaka" },
70
+ { pkg: "sbg-api", branch: "sbg-api", repo: "static-blog-generator", owner: "dimaslanjaka" },
71
+ { pkg: "instant-indexing", branch: "instant-indexing", repo: "static-blog-generator", owner: "dimaslanjaka" },
72
+ { pkg: "sbg-server", branch: "master", repo: "static-blog-generator", owner: "dimaslanjaka" },
73
+ { pkg: "sbg-cli", branch: "master", repo: "static-blog-generator", owner: "dimaslanjaka" },
74
+ { pkg: "static-blog-generator", branch: "master", repo: "static-blog-generator", owner: "dimaslanjaka" },
75
+ // Hexo family
76
+ { pkg: "hexo", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
77
+ { pkg: "hexo-util", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
78
+ { pkg: "warehouse", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
79
+ { pkg: "hexo-server", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
80
+ { pkg: "hexo-log", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
81
+ { pkg: "hexo-front-matter", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
82
+ { pkg: "hexo-cli", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
83
+ { pkg: "hexo-asset-link", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
84
+ { pkg: "hexo-post-parser", branch: "pre-release", repo: "hexo-post-parser", owner: "dimaslanjaka" },
85
+ { pkg: "hexo-seo", branch: "pre-release", repo: "hexo-seo", owner: "dimaslanjaka" },
86
+ { pkg: "hexo-is", branch: "master", repo: "hexo-is", owner: "dimaslanjaka" },
87
+ { pkg: "markdown-it", branch: "master", repo: "markdown-it", owner: "dimaslanjaka" },
88
+ { pkg: "hexo-renderers", branch: "pre-release", repo: "hexo-renderers", owner: "dimaslanjaka" },
89
+ { pkg: "hexo-shortcodes", branch: "pre-release", repo: "hexo-shortcodes", owner: "dimaslanjaka" },
90
+ { pkg: "google-news-sitemap", branch: "master", repo: "google-news-sitemap", owner: "dimaslanjaka" },
91
+ { pkg: "git-command-helper", branch: "pre-release", repo: "git-command-helper", owner: "dimaslanjaka" },
92
+ {
93
+ pkg: "nodejs-package-types",
94
+ branch: "main",
95
+ repo: "nodejs-package-types",
96
+ owner: "dimaslanjaka"
97
+ },
98
+ { pkg: "cross-spawn", branch: "private", repo: "node-cross-spawn", owner: "dimaslanjaka" },
99
+ { pkg: "hexo-generator-redirect", branch: "master", repo: "hexo-generator-redirect", owner: "dimaslanjaka" },
100
+ { pkg: "binary-collections", branch: "master", repo: "bin", owner: "dimaslanjaka" },
101
+ { pkg: "@types/hexo", branch: "monorepo-v7", repo: "hexo", owner: "dimaslanjaka" },
102
+ { pkg: "@types/git-command-helper", branch: "pre-release", repo: "git-command-helper", owner: "dimaslanjaka" }
103
+ ];
104
+
105
+ // --- Optimized: Load package.json once at the top ---
106
+ const pkgPath = path.join(process.cwd(), "package.json");
107
+ let pkg;
108
+ try {
109
+ pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
110
+ } catch (e) {
111
+ console.error(ansiColors.red(`Failed to read package.json: ${e.message}`));
112
+ process.exit(1);
113
+ }
114
+
115
+ // --- Use a random User-Agent for GitHub API requests ---
116
+ const GITHUB_USER_AGENTS = [
117
+ "octokit-rest.js/19.0.7",
118
+ "GitHub CLI/2.40.0",
119
+ "Mozilla/5.0 (compatible; GitHubCopilot/1.0)",
120
+ "PostmanRuntime/7.32.3",
121
+ "binary-collections-resolver/1.0 (+https://github.com/dimaslanjaka/bin)"
122
+ ];
123
+
124
+ // --- User-Agent persistence in system temp folder ---
125
+ const userAgentDir = path.join(os.tmpdir(), "nodejs");
126
+ const userAgentFile = path.join(userAgentDir, "useragent.txt");
127
+ let selectedUserAgent;
128
+ try {
129
+ if (!fs.existsSync(userAgentDir)) fs.mkdirSync(userAgentDir, { recursive: true });
130
+ if (fs.existsSync(userAgentFile)) {
131
+ const fileAgent = fs.readFileSync(userAgentFile, "utf-8").trim();
132
+ if (GITHUB_USER_AGENTS.includes(fileAgent)) {
133
+ selectedUserAgent = fileAgent;
134
+ }
135
+ }
136
+ if (!selectedUserAgent) {
137
+ selectedUserAgent = GITHUB_USER_AGENTS[Math.floor(Math.random() * GITHUB_USER_AGENTS.length)];
138
+ fs.writeFileSync(userAgentFile, selectedUserAgent, "utf-8");
139
+ }
140
+ } catch (_e) {
141
+ // fallback to random if any error
142
+ selectedUserAgent = GITHUB_USER_AGENTS[Math.floor(Math.random() * GITHUB_USER_AGENTS.length)];
143
+ }
144
+
145
+ /**
146
+ * Fetch JSON from a URL with GitHub headers.
147
+ * @param {string} url
148
+ * @returns {Promise<any>}
149
+ */
150
+ function fetchJson(url) {
151
+ const headers = {
152
+ "User-Agent": selectedUserAgent,
153
+ Accept: "application/vnd.github.v3+json",
154
+ "X-GitHub-Api-Version": "2022-11-28",
155
+ ...(ACCESS_TOKEN ? { Authorization: `token ${ACCESS_TOKEN}` } : {})
156
+ };
157
+ return new Promise((resolve, reject) => {
158
+ https
159
+ .get(url, { headers }, (res) => {
160
+ let data = "";
161
+ res.on("data", (chunk) => (data += chunk));
162
+ res.on("end", () => {
163
+ try {
164
+ const json = JSON.parse(data);
165
+ if (res.statusCode < 200 || res.statusCode >= 300) {
166
+ return reject(
167
+ new Error(`GitHub API Error ${res.statusCode}: ${json.message || "Unknown error"}\nURL: ${url}`)
168
+ );
169
+ }
170
+ resolve(json);
171
+ } catch {
172
+ reject(new Error(`Invalid JSON from: ${url}`));
173
+ }
174
+ });
175
+ })
176
+ .on("error", reject);
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Get latest commit SHA from a specific branch.
182
+ */
183
+ async function getLatestCommit(owner, repo, branch = "main") {
184
+ const url = `https://api.github.com/repos/${owner}/${repo}/commits/${branch}`;
185
+ const json = await fetchJson(url);
186
+
187
+ const sha = json.sha;
188
+ const dateStr = json.commit?.committer?.date || json.commit?.author?.date;
189
+
190
+ if (!sha || !dateStr) {
191
+ console.log(json);
192
+ throw new Error(`Missing SHA or date for ${owner}/${repo}@${branch}`);
193
+ }
194
+
195
+ return {
196
+ owner,
197
+ repo,
198
+ branch,
199
+ sha,
200
+ date: new Date(dateStr).toISOString()
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Get latest commit SHA from all branches and pick the latest.
206
+ */
207
+ async function getLatestCommitAcrossBranches(owner, repo) {
208
+ const branches = await fetchJson(`https://api.github.com/repos/${owner}/${repo}/branches`);
209
+
210
+ const commits = await Promise.all(
211
+ branches.map(async ({ name, commit }) => {
212
+ const commitSha = commit?.sha;
213
+ if (!commitSha) {
214
+ console.warn(`No commit SHA for '${owner}/${repo}' branch: ${name}`);
215
+ return { branch: name, sha: "", date: new Date(0) };
216
+ }
217
+
218
+ try {
219
+ const commitData = await fetchJson(`https://api.github.com/repos/${owner}/${repo}/commits/${commitSha}`);
220
+ const dateStr = commitData.commit?.committer?.date || commitData.commit?.author?.date;
221
+ const date = dateStr ? new Date(dateStr) : new Date(0);
222
+ return { branch: name, sha: commitData.sha, date };
223
+ } catch (e) {
224
+ console.warn(`Failed to fetch commit for ${name}: ${e.message}`);
225
+ return { branch: name, sha: commitSha, date: new Date(0) };
226
+ }
227
+ })
228
+ );
229
+
230
+ const latest = commits.reduce((a, b) => (a.date > b.date ? a : b), { date: new Date(0) });
231
+
232
+ return {
233
+ owner,
234
+ repo,
235
+ branch: latest.branch,
236
+ sha: latest.sha,
237
+ date: latest.date.toISOString()
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Replace the branch or commit in a GitHub raw URL with the latest hash.
243
+ */
244
+ function replaceRawWithLatestHash(url, latestHash) {
245
+ const match = url.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/raw\/([^/]+)\/(.+)$/);
246
+ if (!match) throw new Error("Invalid GitHub raw URL");
247
+
248
+ const [, owner, repo, _oldHash, path] = match;
249
+ return `https://github.com/${owner}/${repo}/raw/${latestHash}/${path}`;
250
+ }
251
+
252
+ /**
253
+ * Parse GitHub URLs and extract owner, repo, branch, and original URL.
254
+ */
255
+ function parseGitHubUrl(url) {
256
+ const ghRepoRoot = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/?$/;
257
+ const ghTreeOrBlob = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/(tree|blob)\/([^/]+(?:\/[^/]+)*)/;
258
+ const ghRaw = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)(\/.+)?$/;
259
+ const ghDotComRaw = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/raw\/([^/]+)\/.+/;
260
+
261
+ let match;
262
+
263
+ if ((match = url.match(ghRaw))) {
264
+ const [, owner, repo, branch] = match;
265
+ return { owner, repo, branch, url };
266
+ }
267
+
268
+ if ((match = url.match(ghDotComRaw))) {
269
+ const [, owner, repo, branch] = match;
270
+ return { owner, repo, branch, url };
271
+ }
272
+
273
+ if ((match = url.match(ghTreeOrBlob))) {
274
+ const [, owner, repo, , branchPath] = match;
275
+ return { owner, repo, branch: branchPath, url };
276
+ }
277
+
278
+ if ((match = url.match(ghRepoRoot))) {
279
+ const [, owner, repo] = match;
280
+ return { owner, repo, url };
281
+ }
282
+
283
+ throw new Error(`Unsupported GitHub URL: ${url}`);
284
+ }
285
+
286
+ // --- Main logic ---
287
+ (async () => {
288
+ const entries = Object.entries(pkg.resolutions || {});
289
+ if (entries.length === 0) {
290
+ console.log(ansiColors.yellow("No resolutions found in package.json"));
291
+ return;
292
+ }
293
+ console.log(`Processing ${entries.length} resolution(s)...`);
294
+ const updates = [];
295
+ for (const [currentPkgName, url] of entries) {
296
+ // Validate if URL is a GitHub URL
297
+ let repo;
298
+ try {
299
+ repo = parseGitHubUrl(url);
300
+ console.log(`✅ Valid GitHub URL for ${ansiColors.cyan(currentPkgName)}: ${url}`);
301
+ } catch (error) {
302
+ console.log(`⏭️ Skipping ${ansiColors.yellow(currentPkgName)}: ${error.message}`);
303
+ continue;
304
+ }
305
+ try {
306
+ const override = specialPackageOverrides.find((p) => p.pkg === currentPkgName);
307
+ const latest = override
308
+ ? await getLatestCommit(override.owner, override.repo, override.branch)
309
+ : await getLatestCommitAcrossBranches(repo.owner, repo.repo);
310
+ const new_url = replaceRawWithLatestHash(url, latest.sha);
311
+ updates.push({
312
+ currentPkgName,
313
+ url,
314
+ new_url,
315
+ repo,
316
+ latest
317
+ });
318
+ } catch (error) {
319
+ console.log(`❌ Failed to process ${ansiColors.red(currentPkgName)}: ${error.message}`);
320
+ }
321
+ }
322
+ if (updates.length === 0) {
323
+ console.log(ansiColors.yellow("No GitHub URLs were processed"));
324
+ return;
325
+ }
326
+ console.log(`\n📝 Applying updates to ${updates.length} GitHub URL(s)...`);
327
+ let changed = false;
328
+ for (const { currentPkgName, url, new_url, repo, latest } of updates) {
329
+ if (url !== new_url) {
330
+ console.log(`\n${ansiColors.cyan(currentPkgName)}:`);
331
+ console.log(" from:", url.replace(repo.branch, ansiColors.red(repo.branch)));
332
+ console.log(" to:", new_url.replace(latest.sha, ansiColors.green(latest.sha)));
333
+ pkg.resolutions[currentPkgName] = new_url;
334
+ changed = true;
335
+ } else {
336
+ console.log(`\n${ansiColors.cyan(currentPkgName)}: ${ansiColors.gray("already up-to-date")}`);
337
+ }
338
+ }
339
+ if (changed) {
340
+ try {
341
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
342
+ console.log(`\n✅ package.json updated successfully`);
343
+ } catch (e) {
344
+ console.error(ansiColors.red(`Failed to write package.json: ${e.message}`));
345
+ process.exit(1);
346
+ }
347
+ } else {
348
+ console.log(ansiColors.green("No changes to package.json were necessary."));
349
+ }
350
+ })();