@ucdjs/release-scripts 0.1.0-beta.5 → 0.1.0-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,16 +1,114 @@
1
- import { t as Eta } from "./eta-Boh7yPZi.mjs";
1
+ import { t as Eta } from "./eta-DAZlmVBQ.mjs";
2
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { join, relative } from "node:path";
4
+ import { getCommits, groupByType } from "commit-parser";
2
5
  import process from "node:process";
3
- import { getCommits } from "commit-parser";
6
+ import readline from "node:readline";
4
7
  import farver from "farver";
8
+ import mri from "mri";
5
9
  import { exec } from "tinyexec";
6
10
  import { dedent } from "@luxass/utils";
7
- import { join } from "node:path";
8
- import { readFile, writeFile } from "node:fs/promises";
11
+ import semver, { compare, gt } from "semver";
9
12
  import prompts from "prompts";
10
13
 
11
- //#region src/utils.ts
12
- const globalOptions = { dryRun: false };
14
+ //#region src/operations/changelog-format.ts
15
+ function formatCommitLine({ commit, owner, repo, authors }) {
16
+ const commitUrl = `https://github.com/${owner}/${repo}/commit/${commit.hash}`;
17
+ let line = `${commit.description}`;
18
+ const references = commit.references ?? [];
19
+ for (const ref of references) {
20
+ if (!ref.value) continue;
21
+ const number = Number.parseInt(ref.value.replace(/^#/, ""), 10);
22
+ if (Number.isNaN(number)) continue;
23
+ if (ref.type === "issue") {
24
+ line += ` ([Issue ${ref.value}](https://github.com/${owner}/${repo}/issues/${number}))`;
25
+ continue;
26
+ }
27
+ line += ` ([PR ${ref.value}](https://github.com/${owner}/${repo}/pull/${number}))`;
28
+ }
29
+ line += ` ([${commit.shortHash}](${commitUrl}))`;
30
+ if (authors.length > 0) {
31
+ const authorList = authors.map((author) => author.login ? `[@${author.login}](https://github.com/${author.login})` : author.name).join(", ");
32
+ line += ` (by ${authorList})`;
33
+ }
34
+ return line;
35
+ }
36
+ function buildTemplateGroups(options) {
37
+ const { commits, owner, repo, types, commitAuthors } = options;
38
+ const grouped = groupByType(commits, {
39
+ includeNonConventional: false,
40
+ mergeKeys: Object.fromEntries(Object.entries(types).map(([key, value]) => [key, value.types ?? [key]]))
41
+ });
42
+ return Object.entries(types).map(([key, value]) => {
43
+ const formattedCommits = (grouped.get(key) ?? []).map((commit) => ({ line: formatCommitLine({
44
+ commit,
45
+ owner,
46
+ repo,
47
+ authors: commitAuthors.get(commit.hash) ?? []
48
+ }) }));
49
+ return {
50
+ name: key,
51
+ title: value.title,
52
+ commits: formattedCommits
53
+ };
54
+ });
55
+ }
56
+
57
+ //#endregion
58
+ //#region src/shared/utils.ts
59
+ const args = mri(process.argv.slice(2));
60
+ const isDryRun = !!args.dry;
61
+ const isVerbose$1 = !!args.verbose;
62
+ const isForce = !!args.force;
63
+ const ucdjsReleaseOverridesPath = ".github/ucdjs-release.overrides.json";
13
64
  const isCI = typeof process.env.CI === "string" && process.env.CI !== "" && process.env.CI.toLowerCase() !== "false";
65
+ const logger = {
66
+ info: (...args) => {
67
+ console.info(...args);
68
+ },
69
+ warn: (...args) => {
70
+ console.warn(` ${farver.yellow("⚠")}`, ...args);
71
+ },
72
+ error: (...args) => {
73
+ console.error(` ${farver.red("✖")}`, ...args);
74
+ },
75
+ verbose: (...args) => {
76
+ if (!isVerbose$1) return;
77
+ if (args.length === 0) {
78
+ console.log();
79
+ return;
80
+ }
81
+ if (args.length > 1 && typeof args[0] === "string") {
82
+ console.log(farver.dim(args[0]), ...args.slice(1));
83
+ return;
84
+ }
85
+ console.log(...args);
86
+ },
87
+ section: (title) => {
88
+ console.log();
89
+ console.log(` ${farver.bold(title)}`);
90
+ console.log(` ${farver.gray("─".repeat(title.length + 2))}`);
91
+ },
92
+ emptyLine: () => {
93
+ console.log();
94
+ },
95
+ item: (message, ...args) => {
96
+ console.log(` ${message}`, ...args);
97
+ },
98
+ step: (message) => {
99
+ console.log(` ${farver.blue("→")} ${message}`);
100
+ },
101
+ success: (message) => {
102
+ console.log(` ${farver.green("✓")} ${message}`);
103
+ },
104
+ clearScreen: () => {
105
+ const repeatCount = process.stdout.rows - 2;
106
+ const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
107
+ console.log(blank);
108
+ readline.cursorTo(process.stdout, 0, 0);
109
+ readline.clearScreenDown(process.stdout);
110
+ }
111
+ };
14
112
  async function run(bin, args, opts = {}) {
15
113
  return exec(bin, args, {
16
114
  throwOnError: true,
@@ -22,288 +120,177 @@ async function run(bin, args, opts = {}) {
22
120
  });
23
121
  }
24
122
  async function dryRun(bin, args, opts) {
25
- return console.log(farver.blue(`[dryrun] ${bin} ${args.join(" ")}`), opts || "");
123
+ return logger.verbose(farver.blue(`[dryrun] ${bin} ${args.join(" ")}`), opts || "");
124
+ }
125
+ const runIfNotDry = isDryRun ? dryRun : run;
126
+ if (isDryRun || isVerbose$1 || isForce) {
127
+ logger.verbose(farver.inverse(farver.yellow(" Running with special flags ")));
128
+ logger.verbose({
129
+ isDryRun,
130
+ isVerbose: isVerbose$1,
131
+ isForce
132
+ });
133
+ logger.verbose();
26
134
  }
27
- const runIfNotDry = globalOptions.dryRun ? dryRun : run;
28
135
 
29
136
  //#endregion
30
- //#region src/commits.ts
31
- async function getLastPackageTag(packageName, workspaceRoot) {
32
- const { stdout } = await run("git", ["tag", "--list"], { nodeOptions: {
33
- cwd: workspaceRoot,
34
- stdio: "pipe"
35
- } });
36
- return stdout.split("\n").map((tag) => tag.trim()).filter(Boolean).reverse().find((tag) => tag.startsWith(`${packageName}@`));
137
+ //#region src/shared/errors.ts
138
+ const isVerbose = !!mri(process.argv.slice(2)).verbose;
139
+ function isRecord(value) {
140
+ return typeof value === "object" && value !== null;
37
141
  }
38
- function determineHighestBump(commits) {
39
- if (commits.length === 0) return "none";
40
- let highestBump = "none";
41
- for (const commit of commits) {
42
- const bump = determineBumpType(commit);
43
- if (bump === "major") return "major";
44
- if (bump === "minor") highestBump = "minor";
45
- else if (bump === "patch" && highestBump === "none") highestBump = "patch";
142
+ function toTrimmedString(value) {
143
+ if (typeof value === "string") {
144
+ const normalized = value.trim();
145
+ return normalized.length > 0 ? normalized : void 0;
46
146
  }
47
- return highestBump;
48
- }
49
- async function getPackageCommits(pkg, workspaceRoot) {
50
- const lastTag = await getLastPackageTag(pkg.name, workspaceRoot);
51
- const allCommits = getCommits({
52
- from: lastTag,
53
- to: "HEAD"
54
- });
55
- console.log(`Found ${allCommits.length} commits for ${pkg.name} since ${lastTag || "beginning"}`);
56
- const touchedCommitHashes = await getCommitsTouchingPackage(lastTag || "HEAD", "HEAD", pkg.path, workspaceRoot);
57
- const touchedSet = new Set(touchedCommitHashes);
58
- const packageCommits = allCommits.filter((commit) => touchedSet.has(commit.shortHash));
59
- console.log(`${packageCommits.length} commits affect ${pkg.name}`);
60
- return packageCommits;
61
- }
62
- async function analyzePackageCommits(pkg, workspaceRoot) {
63
- return determineHighestBump(await getPackageCommits(pkg, workspaceRoot));
64
- }
65
- /**
66
- * Analyze commits for multiple packages to determine version bumps
67
- *
68
- * @param packages - Packages to analyze
69
- * @param workspaceRoot - Root directory of the workspace
70
- * @returns Map of package names to their bump types
71
- */
72
- async function analyzeCommits(packages, workspaceRoot) {
73
- const changedPackages = /* @__PURE__ */ new Map();
74
- for (const pkg of packages) {
75
- const bump = await analyzePackageCommits(pkg, workspaceRoot);
76
- if (bump !== "none") changedPackages.set(pkg.name, bump);
147
+ if (value instanceof Uint8Array) {
148
+ const normalized = new TextDecoder().decode(value).trim();
149
+ return normalized.length > 0 ? normalized : void 0;
77
150
  }
78
- return changedPackages;
79
- }
80
- function determineBumpType(commit) {
81
- if (commit.isBreaking) return "major";
82
- if (!commit.isConventional || !commit.type) return "none";
83
- switch (commit.type) {
84
- case "feat": return "minor";
85
- case "fix":
86
- case "perf": return "patch";
87
- case "docs":
88
- case "style":
89
- case "refactor":
90
- case "test":
91
- case "build":
92
- case "ci":
93
- case "chore":
94
- case "revert": return "none";
95
- default: return "none";
96
- }
97
- }
98
- async function getCommitsTouchingPackage(from, to, packagePath, workspaceRoot) {
99
- try {
100
- const { stdout } = await run("git", [
101
- "log",
102
- "--pretty=format:%h",
103
- from === "HEAD" ? "HEAD" : `${from}...${to}`,
104
- "--",
105
- packagePath
106
- ], { nodeOptions: {
107
- cwd: workspaceRoot,
108
- stdio: "pipe"
109
- } });
110
- return stdout.split("\n").map((line) => line.trim()).filter(Boolean);
111
- } catch (error) {
112
- console.error(`Error getting commits touching package: ${error}`);
113
- return [];
151
+ if (isRecord(value) && typeof value.toString === "function") {
152
+ const rendered = value.toString();
153
+ if (typeof rendered === "string" && rendered !== "[object Object]") {
154
+ const normalized = rendered.trim();
155
+ return normalized.length > 0 ? normalized : void 0;
156
+ }
114
157
  }
115
158
  }
116
-
117
- //#endregion
118
- //#region src/git.ts
119
- /**
120
- * Check if the working directory is clean (no uncommitted changes)
121
- * @param {string} workspaceRoot - The root directory of the workspace
122
- * @returns {Promise<boolean>} A Promise resolving to true if clean, false otherwise
123
- */
124
- async function isWorkingDirectoryClean(workspaceRoot) {
125
- try {
126
- if ((await run("git", ["status", "--porcelain"], { nodeOptions: {
127
- cwd: workspaceRoot,
128
- stdio: "pipe"
129
- } })).stdout.trim() !== "") return false;
130
- return true;
131
- } catch (err) {
132
- console.error("Error checking git status:", err);
133
- return false;
159
+ function getNestedField(record, keys) {
160
+ let current = record;
161
+ for (const key of keys) {
162
+ if (!isRecord(current) || !(key in current)) return;
163
+ current = current[key];
134
164
  }
165
+ return current;
135
166
  }
136
- /**
137
- * Check if a git branch exists locally
138
- * @param {string} branch - The branch name to check
139
- * @param {string} workspaceRoot - The root directory of the workspace
140
- * @returns {Promise<boolean>} Promise resolving to true if branch exists, false otherwise
141
- */
142
- async function doesBranchExist(branch, workspaceRoot) {
143
- try {
144
- await run("git", [
145
- "rev-parse",
146
- "--verify",
147
- branch
148
- ], { nodeOptions: {
149
- cwd: workspaceRoot,
150
- stdio: "pipe"
151
- } });
152
- return true;
153
- } catch {
154
- return false;
167
+ function extractStderrLike(record) {
168
+ const candidates = [
169
+ record.stderr,
170
+ record.stdout,
171
+ record.shortMessage,
172
+ record.originalMessage,
173
+ getNestedField(record, ["result", "stderr"]),
174
+ getNestedField(record, ["result", "stdout"]),
175
+ getNestedField(record, ["output", "stderr"]),
176
+ getNestedField(record, ["output", "stdout"]),
177
+ getNestedField(record, ["cause", "stderr"]),
178
+ getNestedField(record, ["cause", "stdout"]),
179
+ getNestedField(record, ["cause", "shortMessage"]),
180
+ getNestedField(record, ["cause", "originalMessage"])
181
+ ];
182
+ for (const candidate of candidates) {
183
+ const rendered = toTrimmedString(candidate);
184
+ if (rendered) return rendered;
155
185
  }
156
186
  }
157
- /**
158
- * Pull latest changes from remote branch
159
- * @param branch - The branch name to pull from
160
- * @param workspaceRoot - The root directory of the workspace
161
- * @returns Promise resolving to true if pull succeeded, false otherwise
162
- */
163
- async function pullLatestChanges(branch, workspaceRoot) {
164
- try {
165
- await run("git", [
166
- "pull",
167
- "origin",
168
- branch
169
- ], { nodeOptions: {
170
- cwd: workspaceRoot,
171
- stdio: "pipe"
172
- } });
173
- return true;
174
- } catch {
175
- return false;
187
+ function formatUnknownError(error) {
188
+ if (error instanceof Error) {
189
+ const base = {
190
+ message: error.message || error.name,
191
+ stack: error.stack
192
+ };
193
+ const maybeError = error;
194
+ if (typeof maybeError.code === "string") base.code = maybeError.code;
195
+ if (typeof maybeError.status === "number") base.status = maybeError.status;
196
+ base.stderr = extractStderrLike(maybeError);
197
+ if (typeof maybeError.shortMessage === "string" && maybeError.shortMessage.trim() && base.message.startsWith("Process exited with non-zero status")) base.message = maybeError.shortMessage.trim();
198
+ if (!base.stderr && typeof maybeError.cause === "string" && maybeError.cause.trim()) base.stderr = maybeError.cause.trim();
199
+ return base;
176
200
  }
177
- }
178
- /**
179
- * Create a new git branch
180
- * @param branch - The new branch name
181
- * @param base - The base branch to create from
182
- * @param workspaceRoot - The root directory of the workspace
183
- */
184
- async function createBranch(branch, base, workspaceRoot) {
185
- await runIfNotDry("git", [
186
- "checkout",
187
- "-b",
188
- branch,
189
- base
190
- ], { nodeOptions: { cwd: workspaceRoot } });
191
- }
192
- /**
193
- * Checkout a git branch
194
- * @param branch - The branch name to checkout
195
- * @param workspaceRoot - The root directory of the workspace
196
- * @returns Promise resolving to true if checkout succeeded, false otherwise
197
- */
198
- async function checkoutBranch(branch, workspaceRoot) {
199
- try {
200
- await run("git", ["checkout", branch], { nodeOptions: { cwd: workspaceRoot } });
201
- return true;
202
- } catch {
203
- return false;
201
+ if (typeof error === "string") return { message: error };
202
+ if (isRecord(error)) {
203
+ const formatted = { message: typeof error.message === "string" ? error.message : typeof error.error === "string" ? error.error : JSON.stringify(error) };
204
+ if (typeof error.code === "string") formatted.code = error.code;
205
+ if (typeof error.status === "number") formatted.status = error.status;
206
+ formatted.stderr = extractStderrLike(error);
207
+ return formatted;
204
208
  }
209
+ return { message: String(error) };
205
210
  }
206
- /**
207
- * Get the current branch name
208
- * @param workspaceRoot - The root directory of the workspace
209
- * @returns Promise resolving to the current branch name
210
- */
211
- async function getCurrentBranch(workspaceRoot) {
212
- return (await run("git", [
213
- "rev-parse",
214
- "--abbrev-ref",
215
- "HEAD"
216
- ], { nodeOptions: {
217
- cwd: workspaceRoot,
218
- stdio: "pipe"
219
- } })).stdout.trim();
220
- }
221
- /**
222
- * Rebase current branch onto another branch
223
- * @param ontoBranch - The target branch to rebase onto
224
- * @param workspaceRoot - The root directory of the workspace
225
- */
226
- async function rebaseBranch(ontoBranch, workspaceRoot) {
227
- await run("git", ["rebase", ontoBranch], { nodeOptions: { cwd: workspaceRoot } });
228
- }
229
- /**
230
- * Check if local branch is ahead of remote (has commits to push)
231
- * @param branch - The branch name to check
232
- * @param workspaceRoot - The root directory of the workspace
233
- * @returns Promise resolving to true if local is ahead, false otherwise
234
- */
235
- async function isBranchAheadOfRemote(branch, workspaceRoot) {
236
- try {
237
- const result = await run("git", [
238
- "rev-list",
239
- `origin/${branch}..${branch}`,
240
- "--count"
241
- ], { nodeOptions: {
242
- cwd: workspaceRoot,
243
- stdio: "pipe"
244
- } });
245
- return Number.parseInt(result.stdout.trim(), 10) > 0;
246
- } catch {
247
- return true;
211
+ function exitWithError(message, hint, cause) {
212
+ console.error(` ${farver.red("✖")} ${farver.bold(message)}`);
213
+ if (cause !== void 0) {
214
+ const formatted = formatUnknownError(cause);
215
+ if (formatted.message && formatted.message !== message) console.error(farver.gray(` Cause: ${formatted.message}`));
216
+ if (formatted.code) console.error(farver.gray(` Code: ${formatted.code}`));
217
+ if (typeof formatted.status === "number") console.error(farver.gray(` Status: ${formatted.status}`));
218
+ if (formatted.stderr) {
219
+ console.error(farver.gray(" Stderr:"));
220
+ console.error(farver.gray(` ${formatted.stderr}`));
221
+ }
222
+ if (isVerbose && formatted.stack) {
223
+ console.error(farver.gray(" Stack:"));
224
+ console.error(farver.gray(` ${formatted.stack}`));
225
+ }
248
226
  }
249
- }
250
- /**
251
- * Check if there are any changes to commit (staged or unstaged)
252
- * @param workspaceRoot - The root directory of the workspace
253
- * @returns Promise resolving to true if there are changes, false otherwise
254
- */
255
- async function hasChangesToCommit(workspaceRoot) {
256
- return (await run("git", ["status", "--porcelain"], { nodeOptions: {
257
- cwd: workspaceRoot,
258
- stdio: "pipe"
259
- } })).stdout.trim() !== "";
260
- }
261
- /**
262
- * Commit changes with a message
263
- * @param message - The commit message
264
- * @param workspaceRoot - The root directory of the workspace
265
- * @returns Promise resolving to true if commit was made, false if there were no changes
266
- */
267
- async function commitChanges(message, workspaceRoot) {
268
- await run("git", ["add", "."], { nodeOptions: { cwd: workspaceRoot } });
269
- if (!await hasChangesToCommit(workspaceRoot)) return false;
270
- await run("git", [
271
- "commit",
272
- "-m",
273
- message
274
- ], { nodeOptions: { cwd: workspaceRoot } });
275
- return true;
276
- }
277
- /**
278
- * Push branch to remote
279
- * @param branch - The branch name to push
280
- * @param workspaceRoot - The root directory of the workspace
281
- * @param options - Push options
282
- * @param options.force - Force push (overwrite remote)
283
- * @param options.forceWithLease - Force push with safety check (won't overwrite unexpected changes)
284
- */
285
- async function pushBranch(branch, workspaceRoot, options) {
286
- const args = [
287
- "push",
288
- "origin",
289
- branch
290
- ];
291
- if (options?.forceWithLease) args.push("--force-with-lease");
292
- else if (options?.force) args.push("--force");
293
- await run("git", args, { nodeOptions: { cwd: workspaceRoot } });
227
+ if (hint) console.error(farver.gray(` ${hint}`));
228
+ process.exit(1);
294
229
  }
295
230
 
296
231
  //#endregion
297
- //#region src/github.ts
298
- async function getExistingPullRequest({ owner, repo, branch, githubToken }) {
299
- try {
300
- const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/pulls?state=open&head=${branch}`, { headers: {
301
- Accept: "application/vnd.github.v3+json",
302
- Authorization: `token ${githubToken}`
303
- } });
304
- if (!res.ok) throw new Error(`GitHub API request failed with status ${res.status}`);
305
- const pulls = await res.json();
306
- if (pulls == null || !Array.isArray(pulls) || pulls.length === 0) return null;
232
+ //#region src/core/github.ts
233
+ function toGitHubError(operation, error) {
234
+ const formatted = formatUnknownError(error);
235
+ return {
236
+ type: "github",
237
+ operation,
238
+ message: formatted.message,
239
+ status: formatted.status
240
+ };
241
+ }
242
+ var GitHubClient = class {
243
+ owner;
244
+ repo;
245
+ githubToken;
246
+ apiBase = "https://api.github.com";
247
+ constructor({ owner, repo, githubToken }) {
248
+ this.owner = owner;
249
+ this.repo = repo;
250
+ this.githubToken = githubToken;
251
+ }
252
+ async request(path, init = {}) {
253
+ const url = path.startsWith("http") ? path : `${this.apiBase}${path}`;
254
+ const method = init.method ?? "GET";
255
+ let res;
256
+ try {
257
+ res = await fetch(url, {
258
+ ...init,
259
+ headers: {
260
+ ...init.headers,
261
+ "Accept": "application/vnd.github.v3+json",
262
+ "Authorization": `token ${this.githubToken}`,
263
+ "User-Agent": "ucdjs-release-scripts (+https://github.com/ucdjs/ucdjs-release-scripts)"
264
+ }
265
+ });
266
+ } catch (error) {
267
+ throw Object.assign(/* @__PURE__ */ new Error(`[${method} ${path}] GitHub request failed: ${formatUnknownError(error).message}`), { status: void 0 });
268
+ }
269
+ if (!res.ok) {
270
+ const errorText = await res.text();
271
+ const parsedMessage = (() => {
272
+ try {
273
+ const parsed = JSON.parse(errorText);
274
+ if (typeof parsed.message === "string" && parsed.message.trim()) {
275
+ if (Array.isArray(parsed.errors) && parsed.errors.length > 0) return `${parsed.message} (${JSON.stringify(parsed.errors)})`;
276
+ return parsed.message;
277
+ }
278
+ return errorText;
279
+ } catch {
280
+ return errorText;
281
+ }
282
+ })();
283
+ throw Object.assign(/* @__PURE__ */ new Error(`[${method} ${path}] GitHub API request failed (${res.status} ${res.statusText}): ${parsedMessage || "No response body"}`), { status: res.status });
284
+ }
285
+ if (res.status === 204) return;
286
+ return res.json();
287
+ }
288
+ async getExistingPullRequest(branch) {
289
+ const head = branch.includes(":") ? branch : `${this.owner}:${branch}`;
290
+ const endpoint = `/repos/${this.owner}/${this.repo}/pulls?state=open&head=${encodeURIComponent(head)}`;
291
+ logger.verbose(`Requesting pull request for branch: ${branch} (url: ${this.apiBase}${endpoint})`);
292
+ const pulls = await this.request(endpoint);
293
+ if (!Array.isArray(pulls) || pulls.length === 0) return null;
307
294
  const firstPullRequest = pulls[0];
308
295
  if (typeof firstPullRequest !== "object" || firstPullRequest === null || !("number" in firstPullRequest) || typeof firstPullRequest.number !== "number" || !("title" in firstPullRequest) || typeof firstPullRequest.title !== "string" || !("body" in firstPullRequest) || typeof firstPullRequest.body !== "string" || !("draft" in firstPullRequest) || typeof firstPullRequest.draft !== "boolean" || !("html_url" in firstPullRequest) || typeof firstPullRequest.html_url !== "string") throw new TypeError("Pull request data validation failed");
309
296
  const pullRequest = {
@@ -311,20 +298,15 @@ async function getExistingPullRequest({ owner, repo, branch, githubToken }) {
311
298
  title: firstPullRequest.title,
312
299
  body: firstPullRequest.body,
313
300
  draft: firstPullRequest.draft,
314
- html_url: firstPullRequest.html_url
301
+ html_url: firstPullRequest.html_url,
302
+ head: "head" in firstPullRequest && typeof firstPullRequest.head === "object" && firstPullRequest.head !== null && "sha" in firstPullRequest.head && typeof firstPullRequest.head.sha === "string" ? { sha: firstPullRequest.head.sha } : void 0
315
303
  };
316
- console.info(`Found existing pull request: ${farver.yellow(`#${pullRequest.number}`)}`);
304
+ logger.info(`Found existing pull request: ${farver.yellow(`#${pullRequest.number}`)}`);
317
305
  return pullRequest;
318
- } catch (err) {
319
- console.error("Error fetching pull request:", err);
320
- return null;
321
306
  }
322
- }
323
- async function upsertPullRequest({ owner, repo, title, body, head, base, pullNumber, githubToken }) {
324
- try {
325
- const isUpdate = pullNumber != null;
326
- const url = isUpdate ? `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}` : `https://api.github.com/repos/${owner}/${repo}/pulls`;
327
- const method = isUpdate ? "PATCH" : "POST";
307
+ async upsertPullRequest({ title, body, head, base, pullNumber }) {
308
+ const isUpdate = typeof pullNumber === "number";
309
+ const endpoint = isUpdate ? `/repos/${this.owner}/${this.repo}/pulls/${pullNumber}` : `/repos/${this.owner}/${this.repo}/pulls`;
328
310
  const requestBody = isUpdate ? {
329
311
  title,
330
312
  body
@@ -332,21 +314,17 @@ async function upsertPullRequest({ owner, repo, title, body, head, base, pullNum
332
314
  title,
333
315
  body,
334
316
  head,
335
- base
317
+ base,
318
+ draft: true
336
319
  };
337
- const res = await fetch(url, {
338
- method,
339
- headers: {
340
- Accept: "application/vnd.github.v3+json",
341
- Authorization: `token ${githubToken}`
342
- },
320
+ logger.verbose(`${isUpdate ? "Updating" : "Creating"} pull request (url: ${this.apiBase}${endpoint})`);
321
+ const pr = await this.request(endpoint, {
322
+ method: isUpdate ? "PATCH" : "POST",
343
323
  body: JSON.stringify(requestBody)
344
324
  });
345
- if (!res.ok) throw new Error(`GitHub API request failed with status ${res.status}`);
346
- const pr = await res.json();
347
325
  if (typeof pr !== "object" || pr === null || !("number" in pr) || typeof pr.number !== "number" || !("title" in pr) || typeof pr.title !== "string" || !("body" in pr) || typeof pr.body !== "string" || !("draft" in pr) || typeof pr.draft !== "boolean" || !("html_url" in pr) || typeof pr.html_url !== "string") throw new TypeError("Pull request data validation failed");
348
326
  const action = isUpdate ? "Updated" : "Created";
349
- console.info(`${action} pull request: ${farver.yellow(`#${pr.number}`)}`);
327
+ logger.info(`${action} pull request: ${farver.yellow(`#${pr.number}`)}`);
350
328
  return {
351
329
  number: pr.number,
352
330
  title: pr.title,
@@ -354,27 +332,44 @@ async function upsertPullRequest({ owner, repo, title, body, head, base, pullNum
354
332
  draft: pr.draft,
355
333
  html_url: pr.html_url
356
334
  };
357
- } catch (err) {
358
- console.error(`Error upserting pull request:`, err);
359
- throw err;
360
335
  }
336
+ async setCommitStatus({ sha, state, targetUrl, description, context }) {
337
+ const endpoint = `/repos/${this.owner}/${this.repo}/statuses/${sha}`;
338
+ logger.verbose(`Setting commit status on ${sha} to ${state} (url: ${this.apiBase}${endpoint})`);
339
+ await this.request(endpoint, {
340
+ method: "POST",
341
+ body: JSON.stringify({
342
+ state,
343
+ target_url: targetUrl,
344
+ description: description || "",
345
+ context
346
+ })
347
+ });
348
+ logger.info(`Commit status set to ${farver.cyan(state)} for ${farver.gray(sha.substring(0, 7))}`);
349
+ }
350
+ async resolveAuthorInfo(info) {
351
+ if (info.login) return info;
352
+ try {
353
+ const q = encodeURIComponent(`${info.email} type:user in:email`);
354
+ const data = await this.request(`/search/users?q=${q}`);
355
+ if (!data.items || data.items.length === 0) return info;
356
+ info.login = data.items[0].login;
357
+ } catch (err) {
358
+ logger.warn(`Failed to resolve author info for email ${info.email}: ${formatUnknownError(err).message}`);
359
+ }
360
+ if (info.login) return info;
361
+ if (info.commits.length > 0) try {
362
+ const data = await this.request(`/repos/${this.owner}/${this.repo}/commits/${info.commits[0]}`);
363
+ if (data.author && data.author.login) info.login = data.author.login;
364
+ } catch (err) {
365
+ logger.warn(`Failed to resolve author info from commits for email ${info.email}: ${formatUnknownError(err).message}`);
366
+ }
367
+ return info;
368
+ }
369
+ };
370
+ function createGitHubClient(options) {
371
+ return new GitHubClient(options);
361
372
  }
362
- const defaultTemplate = dedent`
363
- This PR was automatically generated by the release script.
364
-
365
- The following packages have been prepared for release:
366
-
367
- <% it.packages.forEach((pkg) => { %>
368
- - **<%= pkg.name %>**: <%= pkg.currentVersion %> → <%= pkg.newVersion %> (<%= pkg.bumpType %>)
369
- <% }) %>
370
-
371
- Please review the changes and merge when ready.
372
-
373
- For a more in-depth look at the changes, please refer to the individual package changelogs.
374
-
375
- > [!NOTE]
376
- > When this PR is merged, the release process will be triggered automatically, publishing the new package versions to the registry.
377
- `;
378
373
  function dedentString(str) {
379
374
  const lines = str.split("\n");
380
375
  const minIndent = lines.filter((line) => line.trim().length > 0).reduce((min, line) => Math.min(min, line.search(/\S/)), Infinity);
@@ -382,7 +377,7 @@ function dedentString(str) {
382
377
  }
383
378
  function generatePullRequestBody(updates, body) {
384
379
  const eta = new Eta();
385
- const bodyTemplate = body ? dedentString(body) : defaultTemplate;
380
+ const bodyTemplate = body ? dedentString(body) : DEFAULT_PR_BODY_TEMPLATE;
386
381
  return eta.renderString(bodyTemplate, { packages: updates.map((u) => ({
387
382
  name: u.package.name,
388
383
  currentVersion: u.currentVersion,
@@ -393,94 +388,1126 @@ function generatePullRequestBody(updates, body) {
393
388
  }
394
389
 
395
390
  //#endregion
396
- //#region src/version.ts
397
- function isValidSemver(version) {
398
- return /^\d+\.\d+\.\d+(?:[-+].+)?$/.test(version);
391
+ //#region src/options.ts
392
+ const DEFAULT_PR_BODY_TEMPLATE = dedent`
393
+ This PR was automatically generated by the UCD release scripts.
394
+
395
+ The following packages have been prepared for release:
396
+
397
+ <% if (it.packages.length > 0) { %>
398
+ <% it.packages.forEach((pkg) => { %>
399
+ - **<%= pkg.name %>**: <%= pkg.currentVersion %> → <%= pkg.newVersion %> (<%= pkg.bumpType %>)
400
+ <% }) %>
401
+ <% } else { %>
402
+ There are no packages to release.
403
+ <% } %>
404
+
405
+ Please review the changes and merge when ready.
406
+
407
+ > [!NOTE]
408
+ > When this PR is merged, the release process will be triggered automatically, publishing the new package versions to the registry.
409
+ `;
410
+ const DEFAULT_CHANGELOG_TEMPLATE = dedent`
411
+ <% if (it.previousVersion) { -%>
412
+ ## [<%= it.version %>](<%= it.compareUrl %>) (<%= it.date %>)
413
+ <% } else { -%>
414
+ ## <%= it.version %> (<%= it.date %>)
415
+ <% } %>
416
+
417
+ <% it.groups.forEach((group) => { %>
418
+ <% if (group.commits.length > 0) { %>
419
+
420
+ ### <%= group.title %>
421
+ <% group.commits.forEach((commit) => { %>
422
+
423
+ * <%= commit.line %>
424
+ <% }); %>
425
+
426
+ <% } %>
427
+ <% }); %>
428
+ `;
429
+ const DEFAULT_TYPES = {
430
+ feat: { title: "🚀 Features" },
431
+ fix: { title: "🐞 Bug Fixes" },
432
+ perf: { title: "🏎 Performance" },
433
+ docs: { title: "📚 Documentation" },
434
+ style: { title: "🎨 Styles" }
435
+ };
436
+ function normalizeReleaseScriptsOptions(options) {
437
+ const { workspaceRoot = process.cwd(), githubToken = "", repo: fullRepo, packages = true, branch = {}, globalCommitMode = "dependencies", pullRequest = {}, changelog = {}, types, safeguards = true, dryRun = false, npm = {}, prompts = {} } = options;
438
+ const token = githubToken.trim();
439
+ if (!token) throw new Error("GitHub token is required. Pass it in via options.");
440
+ if (!fullRepo || !fullRepo.trim() || !fullRepo.includes("/")) throw new Error("Repository (repo) is required. Specify in 'owner/repo' format (e.g., 'octocat/hello-world').");
441
+ const [owner, repo] = fullRepo.split("/");
442
+ if (!owner || !repo) throw new Error(`Invalid repo format: "${fullRepo}". Expected format: "owner/repo" (e.g., "octocat/hello-world").`);
443
+ const normalizedPackages = typeof packages === "object" && !Array.isArray(packages) ? {
444
+ exclude: packages.exclude ?? [],
445
+ include: packages.include ?? [],
446
+ excludePrivate: packages.excludePrivate ?? false
447
+ } : packages;
448
+ const isCI = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true";
449
+ return {
450
+ dryRun,
451
+ workspaceRoot,
452
+ githubToken: token,
453
+ owner,
454
+ repo,
455
+ githubClient: createGitHubClient({
456
+ owner,
457
+ repo,
458
+ githubToken: token
459
+ }),
460
+ packages: normalizedPackages,
461
+ branch: {
462
+ release: branch.release ?? "release/next",
463
+ default: branch.default ?? "main"
464
+ },
465
+ globalCommitMode,
466
+ safeguards,
467
+ pullRequest: {
468
+ title: pullRequest.title ?? "chore: release new version",
469
+ body: pullRequest.body ?? DEFAULT_PR_BODY_TEMPLATE
470
+ },
471
+ changelog: {
472
+ enabled: changelog.enabled ?? true,
473
+ template: changelog.template ?? DEFAULT_CHANGELOG_TEMPLATE,
474
+ emojis: changelog.emojis ?? true
475
+ },
476
+ types: types ? {
477
+ ...DEFAULT_TYPES,
478
+ ...types
479
+ } : DEFAULT_TYPES,
480
+ npm: {
481
+ otp: npm.otp,
482
+ provenance: npm.provenance ?? true,
483
+ access: npm.access ?? "public"
484
+ },
485
+ prompts: {
486
+ versions: prompts.versions ?? !isCI,
487
+ packages: prompts.packages ?? !isCI
488
+ }
489
+ };
399
490
  }
400
- function validateSemver(version) {
401
- if (!isValidSemver(version)) throw new Error(`Invalid semver version: ${version}`);
491
+
492
+ //#endregion
493
+ //#region src/types.ts
494
+ function ok(value) {
495
+ return {
496
+ ok: true,
497
+ value
498
+ };
402
499
  }
403
- /**
404
- * Calculate the new version based on current version and bump type
405
- * Pure function - no side effects, easily testable
406
- */
407
- function calculateNewVersion(currentVersion, bump) {
408
- if (bump === "none") return currentVersion;
409
- validateSemver(currentVersion);
410
- const match = currentVersion.match(/^(\d+)\.(\d+)\.(\d+)(.*)$/);
411
- if (!match) throw new Error(`Invalid semver version: ${currentVersion}`);
412
- const [, major, minor, patch] = match;
413
- let newMajor = Number.parseInt(major, 10);
414
- let newMinor = Number.parseInt(minor, 10);
415
- let newPatch = Number.parseInt(patch, 10);
416
- switch (bump) {
417
- case "major":
418
- newMajor += 1;
419
- newMinor = 0;
420
- newPatch = 0;
421
- break;
422
- case "minor":
423
- newMinor += 1;
424
- newPatch = 0;
425
- break;
426
- case "patch":
427
- newPatch += 1;
428
- break;
429
- }
430
- return `${newMajor}.${newMinor}.${newPatch}`;
500
+ function err(error) {
501
+ return {
502
+ ok: false,
503
+ error
504
+ };
431
505
  }
432
- /**
433
- * Create a version update object
434
- */
435
- function createVersionUpdate(pkg, bump, hasDirectChanges) {
436
- const newVersion = calculateNewVersion(pkg.version, bump);
506
+
507
+ //#endregion
508
+ //#region src/core/git.ts
509
+ function toGitError(operation, error) {
510
+ const formatted = formatUnknownError(error);
437
511
  return {
438
- package: pkg,
439
- currentVersion: pkg.version,
440
- newVersion,
441
- bumpType: bump,
442
- hasDirectChanges
512
+ type: "git",
513
+ operation,
514
+ message: formatted.message,
515
+ stderr: formatted.stderr
443
516
  };
444
517
  }
518
+ async function isWorkingDirectoryClean(workspaceRoot) {
519
+ try {
520
+ return ok((await run("git", ["status", "--porcelain"], { nodeOptions: {
521
+ cwd: workspaceRoot,
522
+ stdio: "pipe"
523
+ } })).stdout.trim() === "");
524
+ } catch (error) {
525
+ return err(toGitError("isWorkingDirectoryClean", error));
526
+ }
527
+ }
445
528
  /**
446
- * Update a package.json file with new version and dependency versions
529
+ * Check if a git branch exists locally
530
+ * @param {string} branch - The branch name to check
531
+ * @param {string} workspaceRoot - The root directory of the workspace
532
+ * @returns {Promise<boolean>} Promise resolving to true if branch exists, false otherwise
447
533
  */
448
- async function updatePackageJson(pkg, newVersion, dependencyUpdates) {
449
- const packageJsonPath = join(pkg.path, "package.json");
450
- const content = await readFile(packageJsonPath, "utf-8");
451
- const packageJson = JSON.parse(content);
452
- packageJson.version = newVersion;
453
- for (const [depName, depVersion] of dependencyUpdates) {
454
- if (packageJson.dependencies?.[depName]) {
455
- if (packageJson.dependencies[depName] === "workspace:*") continue;
456
- packageJson.dependencies[depName] = `^${depVersion}`;
457
- }
458
- if (packageJson.devDependencies?.[depName]) {
459
- if (packageJson.devDependencies[depName] === "workspace:*") continue;
460
- packageJson.devDependencies[depName] = `^${depVersion}`;
461
- }
462
- if (packageJson.peerDependencies?.[depName]) {
463
- if (packageJson.peerDependencies[depName] === "workspace:*") continue;
464
- packageJson.peerDependencies[depName] = `^${depVersion}`;
465
- }
534
+ async function doesBranchExist(branch, workspaceRoot) {
535
+ try {
536
+ await run("git", [
537
+ "rev-parse",
538
+ "--verify",
539
+ branch
540
+ ], { nodeOptions: {
541
+ cwd: workspaceRoot,
542
+ stdio: "pipe"
543
+ } });
544
+ return ok(true);
545
+ } catch (error) {
546
+ logger.verbose(`Failed to verify branch "${branch}": ${formatUnknownError(error).message}`);
547
+ return ok(false);
466
548
  }
467
- await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, "utf-8");
468
549
  }
469
550
  /**
470
- * Get all dependency updates needed for a package
551
+ * Retrieves the name of the current branch in the repository.
552
+ * @param {string} workspaceRoot - The root directory of the workspace
553
+ * @returns {Promise<string>} A Promise resolving to the current branch name as a string
471
554
  */
472
- function getDependencyUpdates(pkg, allUpdates) {
473
- const updates = /* @__PURE__ */ new Map();
474
- const allDeps = [...pkg.workspaceDependencies, ...pkg.workspaceDevDependencies];
475
- for (const dep of allDeps) {
476
- const update = allUpdates.find((u) => u.package.name === dep);
477
- if (update) updates.set(dep, update.newVersion);
555
+ async function getCurrentBranch(workspaceRoot) {
556
+ try {
557
+ return ok((await run("git", [
558
+ "rev-parse",
559
+ "--abbrev-ref",
560
+ "HEAD"
561
+ ], { nodeOptions: {
562
+ cwd: workspaceRoot,
563
+ stdio: "pipe"
564
+ } })).stdout.trim());
565
+ } catch (error) {
566
+ return err(toGitError("getCurrentBranch", error));
478
567
  }
479
- return updates;
568
+ }
569
+ /**
570
+ * Creates a new branch from the specified base branch.
571
+ * @param {string} branch - The name of the new branch to create
572
+ * @param {string} base - The base branch to create the new branch from
573
+ * @param {string} workspaceRoot - The root directory of the workspace
574
+ * @returns {Promise<void>} A Promise that resolves when the branch is created
575
+ */
576
+ async function createBranch(branch, base, workspaceRoot) {
577
+ try {
578
+ logger.info(`Creating branch: ${farver.green(branch)} from ${farver.cyan(base)}`);
579
+ await runIfNotDry("git", [
580
+ "branch",
581
+ branch,
582
+ base
583
+ ], { nodeOptions: {
584
+ cwd: workspaceRoot,
585
+ stdio: "pipe"
586
+ } });
587
+ return ok(void 0);
588
+ } catch (error) {
589
+ return err(toGitError("createBranch", error));
590
+ }
591
+ }
592
+ async function checkoutBranch(branch, workspaceRoot) {
593
+ try {
594
+ logger.info(`Switching to branch: ${farver.green(branch)}`);
595
+ const output = (await run("git", ["checkout", branch], { nodeOptions: {
596
+ cwd: workspaceRoot,
597
+ stdio: "pipe"
598
+ } })).stderr.trim();
599
+ const match = output.match(/Switched to (?:a new )?branch '(.+)'/);
600
+ if (match && match[1] === branch) {
601
+ logger.info(`Successfully switched to branch: ${farver.green(branch)}`);
602
+ return ok(true);
603
+ }
604
+ console.warn(`Unexpected git checkout output: ${output}`);
605
+ return ok(false);
606
+ } catch (error) {
607
+ const gitError = toGitError("checkoutBranch", error);
608
+ logger.error(`Git checkout failed: ${gitError.message}`);
609
+ if (gitError.stderr) logger.error(`Git stderr: ${gitError.stderr}`);
610
+ try {
611
+ const branchResult = await run("git", ["branch", "-a"], { nodeOptions: {
612
+ cwd: workspaceRoot,
613
+ stdio: "pipe"
614
+ } });
615
+ logger.verbose(`Available branches:\n${branchResult.stdout}`);
616
+ } catch (error) {
617
+ logger.verbose(`Could not list available branches: ${formatUnknownError(error).message}`);
618
+ }
619
+ return err(gitError);
620
+ }
621
+ }
622
+ async function pullLatestChanges(branch, workspaceRoot) {
623
+ try {
624
+ await run("git", [
625
+ "pull",
626
+ "origin",
627
+ branch
628
+ ], { nodeOptions: {
629
+ cwd: workspaceRoot,
630
+ stdio: "pipe"
631
+ } });
632
+ return ok(true);
633
+ } catch (error) {
634
+ return err(toGitError("pullLatestChanges", error));
635
+ }
636
+ }
637
+ async function rebaseBranch(ontoBranch, workspaceRoot) {
638
+ try {
639
+ logger.info(`Rebasing onto: ${farver.cyan(ontoBranch)}`);
640
+ await runIfNotDry("git", ["rebase", ontoBranch], { nodeOptions: {
641
+ cwd: workspaceRoot,
642
+ stdio: "pipe"
643
+ } });
644
+ return ok(void 0);
645
+ } catch (error) {
646
+ return err(toGitError("rebaseBranch", error));
647
+ }
648
+ }
649
+ async function isBranchAheadOfRemote(branch, workspaceRoot) {
650
+ try {
651
+ const result = await run("git", [
652
+ "rev-list",
653
+ `origin/${branch}..${branch}`,
654
+ "--count"
655
+ ], { nodeOptions: {
656
+ cwd: workspaceRoot,
657
+ stdio: "pipe"
658
+ } });
659
+ return ok(Number.parseInt(result.stdout.trim(), 10) > 0);
660
+ } catch (error) {
661
+ logger.verbose(`Failed to compare branch "${branch}" with remote: ${formatUnknownError(error).message}`);
662
+ return ok(true);
663
+ }
664
+ }
665
+ async function commitChanges(message, workspaceRoot) {
666
+ try {
667
+ await run("git", ["add", "."], { nodeOptions: {
668
+ cwd: workspaceRoot,
669
+ stdio: "pipe"
670
+ } });
671
+ const isClean = await isWorkingDirectoryClean(workspaceRoot);
672
+ if (!isClean.ok || isClean.value) return ok(false);
673
+ logger.info(`Committing changes: ${farver.dim(message)}`);
674
+ await runIfNotDry("git", [
675
+ "commit",
676
+ "-m",
677
+ message
678
+ ], { nodeOptions: {
679
+ cwd: workspaceRoot,
680
+ stdio: "pipe"
681
+ } });
682
+ return ok(true);
683
+ } catch (error) {
684
+ const gitError = toGitError("commitChanges", error);
685
+ logger.error(`Git commit failed: ${gitError.message}`);
686
+ if (gitError.stderr) logger.error(`Git stderr: ${gitError.stderr}`);
687
+ return err(gitError);
688
+ }
689
+ }
690
+ async function pushBranch(branch, workspaceRoot, options) {
691
+ try {
692
+ const args = [
693
+ "push",
694
+ "origin",
695
+ branch
696
+ ];
697
+ if (options?.forceWithLease) try {
698
+ await run("git", [
699
+ "fetch",
700
+ "origin",
701
+ branch
702
+ ], { nodeOptions: {
703
+ cwd: workspaceRoot,
704
+ stdio: "pipe"
705
+ } });
706
+ args.push("--force-with-lease");
707
+ logger.info(`Pushing branch: ${farver.green(branch)} ${farver.dim("(with lease)")}`);
708
+ } catch (error) {
709
+ const fetchError = toGitError("pushBranch.fetch", error);
710
+ if (fetchError.stderr?.includes("couldn't find remote ref") || fetchError.message.includes("couldn't find remote ref")) logger.verbose(`Remote branch origin/${branch} does not exist yet, falling back to regular push without --force-with-lease.`);
711
+ else return err(fetchError);
712
+ }
713
+ else if (options?.force) {
714
+ args.push("--force");
715
+ logger.info(`Force pushing branch: ${farver.green(branch)}`);
716
+ } else logger.info(`Pushing branch: ${farver.green(branch)}`);
717
+ await runIfNotDry("git", args, { nodeOptions: {
718
+ cwd: workspaceRoot,
719
+ stdio: "pipe"
720
+ } });
721
+ return ok(true);
722
+ } catch (error) {
723
+ return err(toGitError("pushBranch", error));
724
+ }
725
+ }
726
+ async function readFileFromGit(workspaceRoot, ref, filePath) {
727
+ try {
728
+ return ok((await run("git", ["show", `${ref}:${filePath}`], { nodeOptions: {
729
+ cwd: workspaceRoot,
730
+ stdio: "pipe"
731
+ } })).stdout);
732
+ } catch (error) {
733
+ logger.verbose(`Failed to read ${filePath} from ${ref}: ${formatUnknownError(error).message}`);
734
+ return ok(null);
735
+ }
736
+ }
737
+ async function getMostRecentPackageTag(workspaceRoot, packageName) {
738
+ try {
739
+ const { stdout } = await run("git", [
740
+ "tag",
741
+ "--list",
742
+ `${packageName}@*`
743
+ ], { nodeOptions: {
744
+ cwd: workspaceRoot,
745
+ stdio: "pipe"
746
+ } });
747
+ const tags = stdout.split("\n").map((tag) => tag.trim()).filter(Boolean);
748
+ if (tags.length === 0) return ok(void 0);
749
+ return ok(tags.reverse()[0]);
750
+ } catch (error) {
751
+ return err(toGitError("getMostRecentPackageTag", error));
752
+ }
753
+ }
754
+ /**
755
+ * Builds a mapping of commit SHAs to the list of files changed in each commit
756
+ * within a given inclusive range.
757
+ *
758
+ * Internally runs:
759
+ * git log --name-only --format=%H <from>^..<to>
760
+ *
761
+ * Notes
762
+ * - This includes the commit identified by `from` (via `from^..to`).
763
+ * - Order of commits in the resulting Map follows `git log` output
764
+ * (reverse chronological, newest first).
765
+ * - On failure (e.g., invalid refs), the function returns null.
766
+ *
767
+ * @param {string} workspaceRoot Absolute path to the git repository root used as cwd.
768
+ * @param {string} from Starting commit/ref (inclusive).
769
+ * @param {string} to Ending commit/ref (inclusive).
770
+ * @returns {Promise<Map<string, string[]> | null>} Promise resolving to a Map where keys are commit SHAs and values are
771
+ * arrays of file paths changed by that commit, or null on error.
772
+ */
773
+ async function getGroupedFilesByCommitSha(workspaceRoot, from, to) {
774
+ const commitsMap = /* @__PURE__ */ new Map();
775
+ try {
776
+ const { stdout } = await run("git", [
777
+ "log",
778
+ "--name-only",
779
+ "--format=%H",
780
+ `${from}^..${to}`
781
+ ], { nodeOptions: {
782
+ cwd: workspaceRoot,
783
+ stdio: "pipe"
784
+ } });
785
+ const lines = stdout.trim().split("\n").filter((line) => line.trim() !== "");
786
+ let currentSha = null;
787
+ const HASH_REGEX = /^[0-9a-f]{40}$/i;
788
+ for (const line of lines) {
789
+ const trimmedLine = line.trim();
790
+ if (HASH_REGEX.test(trimmedLine)) {
791
+ currentSha = trimmedLine;
792
+ commitsMap.set(currentSha, []);
793
+ continue;
794
+ }
795
+ if (currentSha === null) continue;
796
+ commitsMap.get(currentSha).push(trimmedLine);
797
+ }
798
+ return ok(commitsMap);
799
+ } catch (error) {
800
+ return err(toGitError("getGroupedFilesByCommitSha", error));
801
+ }
802
+ }
803
+ /**
804
+ * Create a git tag for a package release
805
+ * @param packageName - The package name (e.g., "@scope/name")
806
+ * @param version - The version to tag (e.g., "1.2.3")
807
+ * @param workspaceRoot - The root directory of the workspace
808
+ * @returns Result indicating success or failure
809
+ */
810
+ async function createPackageTag(packageName, version, workspaceRoot) {
811
+ const tagName = `${packageName}@${version}`;
812
+ try {
813
+ logger.info(`Creating tag: ${farver.green(tagName)}`);
814
+ await runIfNotDry("git", ["tag", tagName], { nodeOptions: {
815
+ cwd: workspaceRoot,
816
+ stdio: "pipe"
817
+ } });
818
+ return ok(void 0);
819
+ } catch (error) {
820
+ return err(toGitError("createPackageTag", error));
821
+ }
822
+ }
823
+ /**
824
+ * Push a specific tag to the remote repository
825
+ * @param tagName - The tag name to push
826
+ * @param workspaceRoot - The root directory of the workspace
827
+ * @returns Result indicating success or failure
828
+ */
829
+ async function pushTag(tagName, workspaceRoot) {
830
+ try {
831
+ logger.info(`Pushing tag: ${farver.green(tagName)}`);
832
+ await runIfNotDry("git", [
833
+ "push",
834
+ "origin",
835
+ tagName
836
+ ], { nodeOptions: {
837
+ cwd: workspaceRoot,
838
+ stdio: "pipe"
839
+ } });
840
+ return ok(void 0);
841
+ } catch (error) {
842
+ return err(toGitError("pushTag", error));
843
+ }
844
+ }
845
+ /**
846
+ * Create and push a package tag in one operation
847
+ * @param packageName - The package name
848
+ * @param version - The version to tag
849
+ * @param workspaceRoot - The root directory of the workspace
850
+ * @returns Result indicating success or failure
851
+ */
852
+ async function createAndPushPackageTag(packageName, version, workspaceRoot) {
853
+ const createResult = await createPackageTag(packageName, version, workspaceRoot);
854
+ if (!createResult.ok) return createResult;
855
+ return pushTag(`${packageName}@${version}`, workspaceRoot);
856
+ }
857
+
858
+ //#endregion
859
+ //#region src/core/changelog.ts
860
+ const excludeAuthors = [
861
+ /\[bot\]/i,
862
+ /dependabot/i,
863
+ /\(bot\)/i
864
+ ];
865
+ async function generateChangelogEntry(options) {
866
+ const { packageName, version, previousVersion, date, commits, owner, repo, types, template, githubClient } = options;
867
+ const templateData = {
868
+ packageName,
869
+ version,
870
+ previousVersion,
871
+ date,
872
+ compareUrl: previousVersion ? `https://github.com/${owner}/${repo}/compare/${packageName}@${previousVersion}...${packageName}@${version}` : void 0,
873
+ owner,
874
+ repo,
875
+ groups: buildTemplateGroups({
876
+ commits,
877
+ owner,
878
+ repo,
879
+ types,
880
+ commitAuthors: await resolveCommitAuthors(commits, githubClient)
881
+ })
882
+ };
883
+ const eta = new Eta();
884
+ const templateToUse = template || DEFAULT_CHANGELOG_TEMPLATE;
885
+ return eta.renderString(templateToUse, templateData).trim();
886
+ }
887
+ async function updateChangelog(options) {
888
+ const { version, previousVersion, commits, date, normalizedOptions, workspacePackage, githubClient } = options;
889
+ const changelogPath = join(workspacePackage.path, "CHANGELOG.md");
890
+ const changelogRelativePath = relative(normalizedOptions.workspaceRoot, join(workspacePackage.path, "CHANGELOG.md"));
891
+ const existingContent = await readFileFromGit(normalizedOptions.workspaceRoot, normalizedOptions.branch.default, changelogRelativePath);
892
+ logger.verbose("Existing content found: ", existingContent.ok && Boolean(existingContent.value));
893
+ const newEntry = await generateChangelogEntry({
894
+ packageName: workspacePackage.name,
895
+ version,
896
+ previousVersion,
897
+ date,
898
+ commits,
899
+ owner: normalizedOptions.owner,
900
+ repo: normalizedOptions.repo,
901
+ types: normalizedOptions.types,
902
+ template: normalizedOptions.changelog?.template,
903
+ githubClient
904
+ });
905
+ let updatedContent;
906
+ if (!existingContent.ok || !existingContent.value) {
907
+ updatedContent = `# ${workspacePackage.name}\n\n${newEntry}\n`;
908
+ await writeFile(changelogPath, updatedContent, "utf-8");
909
+ return;
910
+ }
911
+ const parsed = parseChangelog(existingContent.value);
912
+ const lines = existingContent.value.split("\n");
913
+ const existingVersionIndex = parsed.versions.findIndex((v) => v.version === version);
914
+ if (existingVersionIndex !== -1) {
915
+ const existingVersion = parsed.versions[existingVersionIndex];
916
+ const before = lines.slice(0, existingVersion.lineStart);
917
+ const after = lines.slice(existingVersion.lineEnd + 1);
918
+ updatedContent = [
919
+ ...before,
920
+ newEntry,
921
+ ...after
922
+ ].join("\n");
923
+ } else {
924
+ const insertAt = parsed.headerLineEnd + 1;
925
+ const before = lines.slice(0, insertAt);
926
+ const after = lines.slice(insertAt);
927
+ if (before.length > 0 && before[before.length - 1] !== "") before.push("");
928
+ updatedContent = [
929
+ ...before,
930
+ newEntry,
931
+ "",
932
+ ...after
933
+ ].join("\n");
934
+ }
935
+ await writeFile(changelogPath, updatedContent, "utf-8");
936
+ }
937
+ async function resolveCommitAuthors(commits, githubClient) {
938
+ const authorMap = /* @__PURE__ */ new Map();
939
+ const commitAuthors = /* @__PURE__ */ new Map();
940
+ for (const commit of commits) {
941
+ const authorsForCommit = [];
942
+ commit.authors.forEach((author, idx) => {
943
+ if (!author.email || !author.name) return;
944
+ if (excludeAuthors.some((re) => re.test(author.name))) return;
945
+ if (!authorMap.has(author.email)) authorMap.set(author.email, {
946
+ commits: [],
947
+ name: author.name,
948
+ email: author.email
949
+ });
950
+ const info = authorMap.get(author.email);
951
+ if (idx === 0) info.commits.push(commit.shortHash);
952
+ authorsForCommit.push(info);
953
+ });
954
+ commitAuthors.set(commit.hash, authorsForCommit);
955
+ }
956
+ const authors = Array.from(authorMap.values());
957
+ await Promise.all(authors.map((info) => githubClient.resolveAuthorInfo(info)));
958
+ return commitAuthors;
959
+ }
960
+ function parseChangelog(content) {
961
+ const lines = content.split("\n");
962
+ let packageName = null;
963
+ let headerLineEnd = -1;
964
+ const versions = [];
965
+ for (let i = 0; i < lines.length; i++) {
966
+ const line = lines[i].trim();
967
+ if (line.startsWith("# ")) {
968
+ packageName = line.slice(2).trim();
969
+ headerLineEnd = i;
970
+ break;
971
+ }
972
+ }
973
+ for (let i = headerLineEnd + 1; i < lines.length; i++) {
974
+ const line = lines[i].trim();
975
+ if (line.startsWith("## ")) {
976
+ const versionMatch = line.match(/##\s+(?:<small>)?\[?([^\](\s<]+)/);
977
+ if (versionMatch) {
978
+ const version = versionMatch[1];
979
+ const lineStart = i;
980
+ let lineEnd = lines.length - 1;
981
+ for (let j = i + 1; j < lines.length; j++) if (lines[j].trim().startsWith("## ")) {
982
+ lineEnd = j - 1;
983
+ break;
984
+ }
985
+ const versionContent = lines.slice(lineStart, lineEnd + 1).join("\n");
986
+ versions.push({
987
+ version,
988
+ lineStart,
989
+ lineEnd,
990
+ content: versionContent
991
+ });
992
+ }
993
+ }
994
+ }
995
+ return {
996
+ packageName,
997
+ versions,
998
+ headerLineEnd
999
+ };
1000
+ }
1001
+
1002
+ //#endregion
1003
+ //#region src/operations/semver.ts
1004
+ function isValidSemver(version) {
1005
+ return semver.valid(version) != null;
1006
+ }
1007
+ function getNextVersion(currentVersion, bump) {
1008
+ if (bump === "none") return currentVersion;
1009
+ if (!isValidSemver(currentVersion)) throw new Error(`Cannot bump version for invalid semver: ${currentVersion}`);
1010
+ const next = semver.inc(currentVersion, bump);
1011
+ if (!next) throw new Error(`Failed to bump version ${currentVersion} with bump ${bump}`);
1012
+ return next;
1013
+ }
1014
+ function calculateBumpType(oldVersion, newVersion) {
1015
+ if (!isValidSemver(oldVersion) || !isValidSemver(newVersion)) throw new Error(`Cannot calculate bump type for invalid semver: ${oldVersion} or ${newVersion}`);
1016
+ const diff = semver.diff(oldVersion, newVersion);
1017
+ if (!diff) return "none";
1018
+ if (diff === "major" || diff === "premajor") return "major";
1019
+ if (diff === "minor" || diff === "preminor") return "minor";
1020
+ if (diff === "patch" || diff === "prepatch" || diff === "prerelease") return "patch";
1021
+ if (semver.gt(newVersion, oldVersion)) return "patch";
1022
+ return "none";
1023
+ }
1024
+ function getPrereleaseIdentifier(version) {
1025
+ const parsed = semver.parse(version);
1026
+ if (!parsed || parsed.prerelease.length === 0) return;
1027
+ const identifier = parsed.prerelease[0];
1028
+ return typeof identifier === "string" ? identifier : void 0;
1029
+ }
1030
+ function getNextPrereleaseVersion(currentVersion, mode, identifier) {
1031
+ if (!isValidSemver(currentVersion)) throw new Error(`Cannot bump prerelease for invalid semver: ${currentVersion}`);
1032
+ const releaseType = mode === "next" ? "prerelease" : mode;
1033
+ const next = identifier ? semver.inc(currentVersion, releaseType, identifier) : semver.inc(currentVersion, releaseType);
1034
+ if (!next) throw new Error(`Failed to compute prerelease version for ${currentVersion}`);
1035
+ return next;
1036
+ }
1037
+
1038
+ //#endregion
1039
+ //#region src/core/prompts.ts
1040
+ async function selectPackagePrompt(packages) {
1041
+ const response = await prompts({
1042
+ type: "multiselect",
1043
+ name: "selectedPackages",
1044
+ message: "Select packages to release",
1045
+ choices: packages.map((pkg) => ({
1046
+ title: `${pkg.name} (${farver.bold(pkg.version)})`,
1047
+ value: pkg.name,
1048
+ selected: true
1049
+ })),
1050
+ min: 1,
1051
+ hint: "Space to select/deselect. Return to submit.",
1052
+ instructions: false
1053
+ });
1054
+ if (!response.selectedPackages || response.selectedPackages.length === 0) return [];
1055
+ return response.selectedPackages;
1056
+ }
1057
+ async function selectVersionPrompt(workspaceRoot, pkg, currentVersion, suggestedVersion, options) {
1058
+ const defaultChoice = options?.defaultChoice ?? "auto";
1059
+ const suggestedSuffix = options?.suggestedHint ? farver.dim(` (${options.suggestedHint})`) : "";
1060
+ const prereleaseIdentifier = getPrereleaseIdentifier(currentVersion);
1061
+ const nextDefaultPrerelease = getNextPrereleaseVersion(currentVersion, "next", prereleaseIdentifier === "alpha" || prereleaseIdentifier === "beta" ? prereleaseIdentifier : "beta");
1062
+ const nextBeta = getNextPrereleaseVersion(currentVersion, "next", "beta");
1063
+ const nextAlpha = getNextPrereleaseVersion(currentVersion, "next", "alpha");
1064
+ const prePatchBeta = getNextPrereleaseVersion(currentVersion, "prepatch", "beta");
1065
+ const preMinorBeta = getNextPrereleaseVersion(currentVersion, "preminor", "beta");
1066
+ const preMajorBeta = getNextPrereleaseVersion(currentVersion, "premajor", "beta");
1067
+ const prePatchAlpha = getNextPrereleaseVersion(currentVersion, "prepatch", "alpha");
1068
+ const preMinorAlpha = getNextPrereleaseVersion(currentVersion, "preminor", "alpha");
1069
+ const preMajorAlpha = getNextPrereleaseVersion(currentVersion, "premajor", "alpha");
1070
+ const choices = [
1071
+ {
1072
+ value: "skip",
1073
+ title: `skip ${farver.dim("(no change)")}`
1074
+ },
1075
+ {
1076
+ value: "suggested",
1077
+ title: `suggested ${farver.bold(suggestedVersion)}${suggestedSuffix}`
1078
+ },
1079
+ {
1080
+ value: "as-is",
1081
+ title: `as-is ${farver.dim("(keep current version)")}`
1082
+ },
1083
+ {
1084
+ value: "patch",
1085
+ title: `patch ${farver.bold(getNextVersion(pkg.version, "patch"))}`
1086
+ },
1087
+ {
1088
+ value: "minor",
1089
+ title: `minor ${farver.bold(getNextVersion(pkg.version, "minor"))}`
1090
+ },
1091
+ {
1092
+ value: "major",
1093
+ title: `major ${farver.bold(getNextVersion(pkg.version, "major"))}`
1094
+ },
1095
+ {
1096
+ value: "prerelease",
1097
+ title: `prerelease ${farver.dim("(choose strategy)")}`
1098
+ },
1099
+ {
1100
+ value: "custom",
1101
+ title: "custom"
1102
+ }
1103
+ ];
1104
+ const initialValue = defaultChoice === "auto" ? suggestedVersion === currentVersion ? "skip" : "suggested" : defaultChoice;
1105
+ const initial = Math.max(0, choices.findIndex((choice) => choice.value === initialValue));
1106
+ const prereleaseVersionByChoice = {
1107
+ "next": nextDefaultPrerelease,
1108
+ "next-beta": nextBeta,
1109
+ "next-alpha": nextAlpha,
1110
+ "prepatch-beta": prePatchBeta,
1111
+ "preminor-beta": preMinorBeta,
1112
+ "premajor-beta": preMajorBeta,
1113
+ "prepatch-alpha": prePatchAlpha,
1114
+ "preminor-alpha": preMinorAlpha,
1115
+ "premajor-alpha": preMajorAlpha
1116
+ };
1117
+ const answers = await prompts({
1118
+ type: "autocomplete",
1119
+ name: "version",
1120
+ message: `${pkg.name}: ${farver.green(pkg.version)}`,
1121
+ choices,
1122
+ limit: choices.length,
1123
+ initial
1124
+ });
1125
+ if (!answers.version) return null;
1126
+ if (answers.version === "skip") return null;
1127
+ else if (answers.version === "suggested") return suggestedVersion;
1128
+ else if (answers.version === "custom") {
1129
+ const customAnswer = await prompts({
1130
+ type: "text",
1131
+ name: "custom",
1132
+ message: "Enter the new version number:",
1133
+ initial: suggestedVersion,
1134
+ validate: (custom) => {
1135
+ if (isValidSemver(custom)) return true;
1136
+ return "That's not a valid version number";
1137
+ }
1138
+ });
1139
+ if (!customAnswer.custom) return null;
1140
+ return customAnswer.custom;
1141
+ } else if (answers.version === "as-is") return currentVersion;
1142
+ else if (answers.version === "prerelease") {
1143
+ const prereleaseChoices = [
1144
+ {
1145
+ value: "next",
1146
+ title: `next ${farver.bold(nextDefaultPrerelease)}`
1147
+ },
1148
+ {
1149
+ value: "next-beta",
1150
+ title: `next beta ${farver.bold(nextBeta)}`
1151
+ },
1152
+ {
1153
+ value: "next-alpha",
1154
+ title: `next alpha ${farver.bold(nextAlpha)}`
1155
+ },
1156
+ {
1157
+ value: "prepatch-beta",
1158
+ title: `pre-patch (beta) ${farver.bold(prePatchBeta)}`
1159
+ },
1160
+ {
1161
+ value: "prepatch-alpha",
1162
+ title: `pre-patch (alpha) ${farver.bold(prePatchAlpha)}`
1163
+ },
1164
+ {
1165
+ value: "preminor-beta",
1166
+ title: `pre-minor (beta) ${farver.bold(preMinorBeta)}`
1167
+ },
1168
+ {
1169
+ value: "preminor-alpha",
1170
+ title: `pre-minor (alpha) ${farver.bold(preMinorAlpha)}`
1171
+ },
1172
+ {
1173
+ value: "premajor-beta",
1174
+ title: `pre-major (beta) ${farver.bold(preMajorBeta)}`
1175
+ },
1176
+ {
1177
+ value: "premajor-alpha",
1178
+ title: `pre-major (alpha) ${farver.bold(preMajorAlpha)}`
1179
+ }
1180
+ ];
1181
+ const prereleaseAnswer = await prompts({
1182
+ type: "autocomplete",
1183
+ name: "prerelease",
1184
+ message: `${pkg.name}: select prerelease strategy`,
1185
+ choices: prereleaseChoices,
1186
+ limit: prereleaseChoices.length,
1187
+ initial: 0
1188
+ });
1189
+ if (!prereleaseAnswer.prerelease) return null;
1190
+ return prereleaseVersionByChoice[prereleaseAnswer.prerelease];
1191
+ }
1192
+ const prereleaseVersion = prereleaseVersionByChoice[answers.version];
1193
+ if (prereleaseVersion) return prereleaseVersion;
1194
+ return getNextVersion(pkg.version, answers.version);
1195
+ }
1196
+
1197
+ //#endregion
1198
+ //#region src/core/workspace.ts
1199
+ function toWorkspaceError(operation, error) {
1200
+ return {
1201
+ type: "workspace",
1202
+ operation,
1203
+ message: error instanceof Error ? error.message : String(error)
1204
+ };
1205
+ }
1206
+ async function discoverWorkspacePackages(workspaceRoot, options) {
1207
+ let workspaceOptions;
1208
+ let explicitPackages;
1209
+ if (options.packages == null || options.packages === true) workspaceOptions = { excludePrivate: false };
1210
+ else if (Array.isArray(options.packages)) {
1211
+ workspaceOptions = {
1212
+ excludePrivate: false,
1213
+ include: options.packages
1214
+ };
1215
+ explicitPackages = options.packages;
1216
+ } else {
1217
+ workspaceOptions = options.packages;
1218
+ if (options.packages.include) explicitPackages = options.packages.include;
1219
+ }
1220
+ let workspacePackages;
1221
+ try {
1222
+ workspacePackages = await findWorkspacePackages(workspaceRoot, workspaceOptions);
1223
+ } catch (error) {
1224
+ return err(toWorkspaceError("discoverWorkspacePackages", error));
1225
+ }
1226
+ if (explicitPackages) {
1227
+ const foundNames = new Set(workspacePackages.map((p) => p.name));
1228
+ const missing = explicitPackages.filter((p) => !foundNames.has(p));
1229
+ if (missing.length > 0) exitWithError(`Package${missing.length > 1 ? "s" : ""} not found in workspace: ${missing.join(", ")}`, "Check your package names or run 'pnpm ls' to see available packages");
1230
+ }
1231
+ const isPackagePromptEnabled = options.prompts?.packages !== false;
1232
+ if (!isCI && isPackagePromptEnabled && !explicitPackages) {
1233
+ const selectedNames = await selectPackagePrompt(workspacePackages);
1234
+ workspacePackages = workspacePackages.filter((pkg) => selectedNames.includes(pkg.name));
1235
+ }
1236
+ return ok(workspacePackages);
1237
+ }
1238
+ async function findWorkspacePackages(workspaceRoot, options) {
1239
+ try {
1240
+ const result = await run("pnpm", [
1241
+ "-r",
1242
+ "ls",
1243
+ "--json"
1244
+ ], { nodeOptions: {
1245
+ cwd: workspaceRoot,
1246
+ stdio: "pipe"
1247
+ } });
1248
+ const rawProjects = JSON.parse(result.stdout);
1249
+ const allPackageNames = new Set(rawProjects.map((p) => p.name));
1250
+ const excludedPackages = /* @__PURE__ */ new Set();
1251
+ const promises = rawProjects.map(async (rawProject) => {
1252
+ const content = await readFile(join(rawProject.path, "package.json"), "utf-8");
1253
+ const packageJson = JSON.parse(content);
1254
+ if (!shouldIncludePackage(packageJson, options)) {
1255
+ excludedPackages.add(rawProject.name);
1256
+ return null;
1257
+ }
1258
+ return {
1259
+ name: rawProject.name,
1260
+ version: rawProject.version,
1261
+ path: rawProject.path,
1262
+ packageJson,
1263
+ workspaceDependencies: Object.keys(rawProject.dependencies || []).filter((dep) => {
1264
+ return allPackageNames.has(dep);
1265
+ }),
1266
+ workspaceDevDependencies: Object.keys(rawProject.devDependencies || []).filter((dep) => {
1267
+ return allPackageNames.has(dep);
1268
+ })
1269
+ };
1270
+ });
1271
+ const packages = await Promise.all(promises);
1272
+ if (excludedPackages.size > 0) logger.info(`Excluded packages: ${farver.green(Array.from(excludedPackages).join(", "))}`);
1273
+ return packages.filter((pkg) => pkg !== null);
1274
+ } catch (err) {
1275
+ logger.error("Error discovering workspace packages:", err);
1276
+ throw err;
1277
+ }
1278
+ }
1279
+ function shouldIncludePackage(pkg, options) {
1280
+ if (!options) return true;
1281
+ if (options.excludePrivate && pkg.private) return false;
1282
+ if (options.include && options.include.length > 0) {
1283
+ if (!options.include.includes(pkg.name)) return false;
1284
+ }
1285
+ if (options.exclude?.includes(pkg.name)) return false;
1286
+ return true;
1287
+ }
1288
+
1289
+ //#endregion
1290
+ //#region src/operations/branch.ts
1291
+ async function prepareReleaseBranch(options) {
1292
+ const { workspaceRoot, releaseBranch, defaultBranch } = options;
1293
+ const currentBranch = await getCurrentBranch(workspaceRoot);
1294
+ if (!currentBranch.ok) return currentBranch;
1295
+ if (currentBranch.value !== defaultBranch) return err({
1296
+ type: "git",
1297
+ operation: "validateBranch",
1298
+ message: `Current branch is '${currentBranch.value}'. Please switch to '${defaultBranch}'.`
1299
+ });
1300
+ const branchExists = await doesBranchExist(releaseBranch, workspaceRoot);
1301
+ if (!branchExists.ok) return branchExists;
1302
+ if (!branchExists.value) {
1303
+ const created = await createBranch(releaseBranch, defaultBranch, workspaceRoot);
1304
+ if (!created.ok) return created;
1305
+ }
1306
+ const checkedOut = await checkoutBranch(releaseBranch, workspaceRoot);
1307
+ if (!checkedOut.ok) return checkedOut;
1308
+ if (branchExists.value) {
1309
+ const pulled = await pullLatestChanges(releaseBranch, workspaceRoot);
1310
+ if (!pulled.ok) return pulled;
1311
+ if (!pulled.value) logger.warn("Failed to pull latest changes, continuing anyway.");
1312
+ }
1313
+ const rebased = await rebaseBranch(defaultBranch, workspaceRoot);
1314
+ if (!rebased.ok) return rebased;
1315
+ return ok(void 0);
1316
+ }
1317
+ async function syncReleaseChanges(options) {
1318
+ const { workspaceRoot, releaseBranch, commitMessage, hasChanges } = options;
1319
+ const committed = hasChanges ? await commitChanges(commitMessage, workspaceRoot) : ok(false);
1320
+ if (!committed.ok) return committed;
1321
+ const isAhead = await isBranchAheadOfRemote(releaseBranch, workspaceRoot);
1322
+ if (!isAhead.ok) return isAhead;
1323
+ if (!committed.value && !isAhead.value) return ok(false);
1324
+ const pushed = await pushBranch(releaseBranch, workspaceRoot, { forceWithLease: true });
1325
+ if (!pushed.ok) return pushed;
1326
+ return ok(true);
1327
+ }
1328
+
1329
+ //#endregion
1330
+ //#region src/versioning/commits.ts
1331
+ /**
1332
+ * Get commits grouped by workspace package.
1333
+ * For each package, retrieves all commits since its last release tag that affect that package.
1334
+ *
1335
+ * @param {string} workspaceRoot - The root directory of the workspace
1336
+ * @param {WorkspacePackage[]} packages - Array of workspace packages to analyze
1337
+ * @returns {Promise<Map<string, GitCommit[]>>} A map of package names to their commits since their last release
1338
+ */
1339
+ async function getWorkspacePackageGroupedCommits(workspaceRoot, packages) {
1340
+ const changedPackages = /* @__PURE__ */ new Map();
1341
+ const promises = packages.map(async (pkg) => {
1342
+ const lastTagResult = await getMostRecentPackageTag(workspaceRoot, pkg.name);
1343
+ const lastTag = lastTagResult.ok ? lastTagResult.value : void 0;
1344
+ const allCommits = await getCommits({
1345
+ from: lastTag,
1346
+ to: "HEAD",
1347
+ cwd: workspaceRoot,
1348
+ folder: pkg.path
1349
+ });
1350
+ logger.verbose(`Found ${farver.cyan(allCommits.length)} commits for package ${farver.bold(pkg.name)} since tag ${farver.cyan(lastTag ?? "N/A")}`);
1351
+ return {
1352
+ pkgName: pkg.name,
1353
+ commits: allCommits
1354
+ };
1355
+ });
1356
+ const results = await Promise.all(promises);
1357
+ for (const { pkgName, commits } of results) changedPackages.set(pkgName, commits);
1358
+ return changedPackages;
1359
+ }
1360
+ /**
1361
+ * Check if a file path touches any package folder.
1362
+ * @param file - The file path to check
1363
+ * @param packagePaths - Set of normalized package paths
1364
+ * @param workspaceRoot - The workspace root for path normalization
1365
+ * @returns true if the file is inside a package folder
1366
+ */
1367
+ function fileMatchesPackageFolder(file, packagePaths, workspaceRoot) {
1368
+ const normalizedFile = file.startsWith("./") ? file.slice(2) : file;
1369
+ for (const pkgPath of packagePaths) {
1370
+ const normalizedPkgPath = pkgPath.startsWith(workspaceRoot) ? pkgPath.slice(workspaceRoot.length + 1) : pkgPath;
1371
+ if (normalizedFile.startsWith(`${normalizedPkgPath}/`) || normalizedFile === normalizedPkgPath) return true;
1372
+ }
1373
+ return false;
1374
+ }
1375
+ /**
1376
+ * Check if a commit is a "global" commit (doesn't touch any package folder).
1377
+ * @param workspaceRoot - The workspace root
1378
+ * @param files - Array of files changed in the commit
1379
+ * @param packagePaths - Set of normalized package paths
1380
+ * @returns true if this is a global commit
1381
+ */
1382
+ function isGlobalCommit(workspaceRoot, files, packagePaths) {
1383
+ if (!files || files.length === 0) return false;
1384
+ return !files.some((file) => fileMatchesPackageFolder(file, packagePaths, workspaceRoot));
1385
+ }
1386
+ const DEPENDENCY_FILES = [
1387
+ "package.json",
1388
+ "pnpm-lock.yaml",
1389
+ "pnpm-workspace.yaml",
1390
+ "yarn.lock",
1391
+ "package-lock.json"
1392
+ ];
1393
+ /**
1394
+ * Find the oldest and newest commits across all packages.
1395
+ * @param packageCommits - Map of package commits
1396
+ * @returns Object with oldest and newest commit SHAs, or null if no commits
1397
+ */
1398
+ function findCommitRange(packageCommits) {
1399
+ let oldestCommit = null;
1400
+ let newestCommit = null;
1401
+ for (const commits of packageCommits.values()) {
1402
+ if (commits.length === 0) continue;
1403
+ const firstCommit = commits[0].shortHash;
1404
+ const lastCommit = commits[commits.length - 1].shortHash;
1405
+ if (!newestCommit) newestCommit = firstCommit;
1406
+ oldestCommit = lastCommit;
1407
+ }
1408
+ if (!oldestCommit || !newestCommit) return null;
1409
+ return {
1410
+ oldest: oldestCommit,
1411
+ newest: newestCommit
1412
+ };
1413
+ }
1414
+ /**
1415
+ * Get global commits for each package based on their individual commit timelines.
1416
+ * This solves the problem where packages with different release histories need different global commits.
1417
+ *
1418
+ * A "global commit" is a commit that doesn't touch any package folder but may affect all packages
1419
+ * (e.g., root package.json, CI config, README).
1420
+ *
1421
+ * Performance: Makes ONE batched git call to get files for all commits across all packages.
1422
+ *
1423
+ * @param workspaceRoot - The root directory of the workspace
1424
+ * @param packageCommits - Map of package name to their commits (from getWorkspacePackageCommits)
1425
+ * @param allPackages - All workspace packages (used to identify package folders)
1426
+ * @param mode - Filter mode: false (disabled), "all" (all global commits), or "dependencies" (only dependency-related)
1427
+ * @returns Map of package name to their global commits
1428
+ */
1429
+ async function getGlobalCommitsPerPackage(workspaceRoot, packageCommits, allPackages, mode) {
1430
+ const result = /* @__PURE__ */ new Map();
1431
+ if (!mode) {
1432
+ logger.verbose("Global commits mode disabled");
1433
+ return result;
1434
+ }
1435
+ logger.verbose(`Computing global commits per-package (mode: ${farver.cyan(mode)})`);
1436
+ const commitRange = findCommitRange(packageCommits);
1437
+ if (!commitRange) {
1438
+ logger.verbose("No commits found across packages");
1439
+ return result;
1440
+ }
1441
+ logger.verbose("Fetching files for commits range", `${farver.cyan(commitRange.oldest)}..${farver.cyan(commitRange.newest)}`);
1442
+ const commitFilesMap = await getGroupedFilesByCommitSha(workspaceRoot, commitRange.oldest, commitRange.newest);
1443
+ if (!commitFilesMap.ok) {
1444
+ logger.warn("Failed to get commit file list, returning empty global commits");
1445
+ return result;
1446
+ }
1447
+ logger.verbose("Got file lists for commits", `${farver.cyan(commitFilesMap.value.size)} commits in ONE git call`);
1448
+ const packagePaths = new Set(allPackages.map((p) => p.path));
1449
+ for (const [pkgName, commits] of packageCommits) {
1450
+ const globalCommitsAffectingPackage = [];
1451
+ logger.verbose("Filtering global commits for package", `${farver.bold(pkgName)} from ${farver.cyan(commits.length)} commits`);
1452
+ for (const commit of commits) {
1453
+ const files = commitFilesMap.value.get(commit.shortHash);
1454
+ if (!files) continue;
1455
+ if (isGlobalCommit(workspaceRoot, files, packagePaths)) globalCommitsAffectingPackage.push(commit);
1456
+ }
1457
+ logger.verbose("Package global commits found", `${farver.bold(pkgName)}: ${farver.cyan(globalCommitsAffectingPackage.length)} global commits`);
1458
+ if (mode === "all") {
1459
+ result.set(pkgName, globalCommitsAffectingPackage);
1460
+ continue;
1461
+ }
1462
+ const dependencyCommits = [];
1463
+ for (const commit of globalCommitsAffectingPackage) {
1464
+ const files = commitFilesMap.value.get(commit.shortHash);
1465
+ if (!files) continue;
1466
+ if (files.some((file) => DEPENDENCY_FILES.includes(file.startsWith("./") ? file.slice(2) : file))) {
1467
+ logger.verbose("Global commit affects dependencies", `${farver.bold(pkgName)}: commit ${farver.cyan(commit.shortHash)} affects dependencies`);
1468
+ dependencyCommits.push(commit);
1469
+ }
1470
+ }
1471
+ logger.verbose("Global commits affect dependencies", `${farver.bold(pkgName)}: ${farver.cyan(dependencyCommits.length)} global commits affect dependencies`);
1472
+ result.set(pkgName, dependencyCommits);
1473
+ }
1474
+ return result;
1475
+ }
1476
+
1477
+ //#endregion
1478
+ //#region src/operations/version.ts
1479
+ function determineHighestBump(commits) {
1480
+ if (commits.length === 0) return "none";
1481
+ let highestBump = "none";
1482
+ for (const commit of commits) {
1483
+ const bump = determineBumpType(commit);
1484
+ if (bump === "major") return "major";
1485
+ if (bump === "minor") highestBump = "minor";
1486
+ else if (bump === "patch" && highestBump === "none") highestBump = "patch";
1487
+ }
1488
+ return highestBump;
1489
+ }
1490
+ function createVersionUpdate(pkg, bump, hasDirectChanges) {
1491
+ const newVersion = getNextVersion(pkg.version, bump);
1492
+ return {
1493
+ package: pkg,
1494
+ currentVersion: pkg.version,
1495
+ newVersion,
1496
+ bumpType: bump,
1497
+ hasDirectChanges,
1498
+ changeKind: "dependent"
1499
+ };
1500
+ }
1501
+ function determineBumpType(commit) {
1502
+ if (!commit.isConventional) return "none";
1503
+ if (commit.isBreaking) return "major";
1504
+ if (commit.type === "feat") return "minor";
1505
+ if (commit.type === "fix" || commit.type === "perf") return "patch";
1506
+ return "none";
480
1507
  }
481
1508
 
482
1509
  //#endregion
483
- //#region src/package.ts
1510
+ //#region src/versioning/package.ts
484
1511
  /**
485
1512
  * Build a dependency graph from workspace packages
486
1513
  *
@@ -533,6 +1560,51 @@ function getAllAffectedPackages(graph, changedPackages) {
533
1560
  return affected;
534
1561
  }
535
1562
  /**
1563
+ * Calculate the order in which packages should be published
1564
+ *
1565
+ * Performs topological sorting to ensure dependencies are published before dependents.
1566
+ * Assigns a "level" to each package based on its depth in the dependency tree.
1567
+ *
1568
+ * This is used by the publish command to publish packages in the correct order.
1569
+ *
1570
+ * @param graph - Dependency graph
1571
+ * @param packagesToPublish - Set of package names to publish
1572
+ * @returns Array of packages in publish order with their dependency level
1573
+ */
1574
+ function getPackagePublishOrder(graph, packagesToPublish) {
1575
+ const result = [];
1576
+ const visited = /* @__PURE__ */ new Set();
1577
+ const toUpdate = new Set(packagesToPublish);
1578
+ const packagesToProcess = new Set(packagesToPublish);
1579
+ for (const pkg of packagesToPublish) {
1580
+ const deps = graph.dependents.get(pkg);
1581
+ if (deps) for (const dep of deps) {
1582
+ packagesToProcess.add(dep);
1583
+ toUpdate.add(dep);
1584
+ }
1585
+ }
1586
+ function visit(pkgName, level) {
1587
+ if (visited.has(pkgName)) return;
1588
+ visited.add(pkgName);
1589
+ const pkg = graph.packages.get(pkgName);
1590
+ if (!pkg) return;
1591
+ const allDeps = [...pkg.workspaceDependencies, ...pkg.workspaceDevDependencies];
1592
+ let maxDepLevel = level;
1593
+ for (const dep of allDeps) if (toUpdate.has(dep)) {
1594
+ visit(dep, level);
1595
+ const depResult = result.find((r) => r.package.name === dep);
1596
+ if (depResult && depResult.level >= maxDepLevel) maxDepLevel = depResult.level + 1;
1597
+ }
1598
+ result.push({
1599
+ package: pkg,
1600
+ level: maxDepLevel
1601
+ });
1602
+ }
1603
+ for (const pkg of toUpdate) visit(pkg, 0);
1604
+ result.sort((a, b) => a.level - b.level);
1605
+ return result;
1606
+ }
1607
+ /**
536
1608
  * Create version updates for all packages affected by dependency changes
537
1609
  *
538
1610
  * When a package is updated, all packages that depend on it should also be updated.
@@ -543,364 +1615,794 @@ function getAllAffectedPackages(graph, changedPackages) {
543
1615
  * @param directUpdates - Packages with direct code changes
544
1616
  * @returns All updates including dependent packages that need patch bumps
545
1617
  */
546
- function createDependentUpdates(graph, workspacePackages, directUpdates) {
1618
+ function createDependentUpdates(graph, workspacePackages, directUpdates, excludedPackages = /* @__PURE__ */ new Set()) {
547
1619
  const allUpdates = [...directUpdates];
548
1620
  const directUpdateMap = new Map(directUpdates.map((u) => [u.package.name, u]));
549
1621
  const affectedPackages = getAllAffectedPackages(graph, new Set(directUpdates.map((u) => u.package.name)));
550
1622
  for (const pkgName of affectedPackages) {
551
- if (directUpdateMap.has(pkgName)) continue;
1623
+ logger.verbose(`Processing affected package: ${pkgName}`);
1624
+ if (excludedPackages.has(pkgName)) {
1625
+ logger.verbose(`Skipping ${pkgName}, explicitly excluded from dependent bumps`);
1626
+ continue;
1627
+ }
1628
+ if (directUpdateMap.has(pkgName)) {
1629
+ logger.verbose(`Skipping ${pkgName}, already has a direct update`);
1630
+ continue;
1631
+ }
552
1632
  const pkg = workspacePackages.find((p) => p.name === pkgName);
553
1633
  if (!pkg) continue;
554
1634
  allUpdates.push(createVersionUpdate(pkg, "patch", false));
555
1635
  }
556
1636
  return allUpdates;
557
1637
  }
558
- /**
559
- * Update all package.json files with new versions and dependency updates
560
- *
561
- * Updates are performed in parallel for better performance.
562
- *
563
- * @param updates - Version updates to apply
564
- */
565
- async function updateAllPackageJsonFiles(updates) {
566
- await Promise.all(updates.map(async (update) => {
567
- const depUpdates = getDependencyUpdates(update.package, updates);
568
- await updatePackageJson(update.package, update.newVersion, depUpdates);
569
- }));
570
- }
571
1638
 
572
1639
  //#endregion
573
- //#region src/prompts.ts
574
- /**
575
- * Get commits for a package grouped by conventional commit type
576
- *
577
- * @param pkg - The workspace package
578
- * @param workspaceRoot - Root directory of the workspace
579
- * @param limit - Maximum number of commits to return (default: 10)
580
- * @returns Commits grouped by type
581
- */
582
- async function getCommitsForPackage(pkg, workspaceRoot, limit = 10) {
583
- const limitedCommits = (await getPackageCommits(pkg, workspaceRoot)).slice(0, limit);
584
- const grouped = {
585
- feat: [],
586
- fix: [],
587
- perf: [],
588
- chore: [],
589
- docs: [],
590
- style: [],
591
- refactor: [],
592
- test: [],
593
- build: [],
594
- ci: [],
595
- revert: [],
596
- other: []
1640
+ //#region src/versioning/version.ts
1641
+ const messageColorMap = {
1642
+ feat: farver.green,
1643
+ feature: farver.green,
1644
+ refactor: farver.cyan,
1645
+ style: farver.cyan,
1646
+ docs: farver.blue,
1647
+ doc: farver.blue,
1648
+ types: farver.blue,
1649
+ type: farver.blue,
1650
+ chore: farver.gray,
1651
+ ci: farver.gray,
1652
+ build: farver.gray,
1653
+ deps: farver.gray,
1654
+ dev: farver.gray,
1655
+ fix: farver.yellow,
1656
+ test: farver.yellow,
1657
+ perf: farver.magenta,
1658
+ revert: farver.red,
1659
+ breaking: farver.red
1660
+ };
1661
+ function formatCommitsForDisplay(commits) {
1662
+ if (commits.length === 0) return farver.dim("No commits found");
1663
+ const maxCommitsToShow = 10;
1664
+ const commitsToShow = commits.slice(0, maxCommitsToShow);
1665
+ const hasMore = commits.length > maxCommitsToShow;
1666
+ const typeLength = commits.map(({ type }) => type.length).reduce((a, b) => Math.max(a, b), 0);
1667
+ const scopeLength = commits.map(({ scope }) => scope?.length).reduce((a, b) => Math.max(a || 0, b || 0), 0) || 0;
1668
+ const formattedCommits = commitsToShow.map((commit) => {
1669
+ let color = messageColorMap[commit.type] || ((c) => c);
1670
+ if (commit.isBreaking) color = (s) => farver.inverse.red(s);
1671
+ const paddedType = commit.type.padStart(typeLength + 1, " ");
1672
+ const paddedScope = !commit.scope ? " ".repeat(scopeLength ? scopeLength + 2 : 0) : farver.dim("(") + commit.scope + farver.dim(")") + " ".repeat(scopeLength - commit.scope.length);
1673
+ return [
1674
+ farver.dim(commit.shortHash),
1675
+ " ",
1676
+ color === farver.gray ? color(paddedType) : farver.bold(color(paddedType)),
1677
+ " ",
1678
+ paddedScope,
1679
+ farver.dim(":"),
1680
+ " ",
1681
+ color === farver.gray ? color(commit.description) : commit.description
1682
+ ].join("");
1683
+ }).join("\n");
1684
+ if (hasMore) return `${formattedCommits}\n ${farver.dim(`... and ${commits.length - maxCommitsToShow} more commits`)}`;
1685
+ return formattedCommits;
1686
+ }
1687
+ async function calculateVersionUpdates({ workspacePackages, packageCommits, workspaceRoot, showPrompt, globalCommitsPerPackage, overrides: initialOverrides = {} }) {
1688
+ const versionUpdates = [];
1689
+ const processedPackages = /* @__PURE__ */ new Set();
1690
+ const newOverrides = { ...initialOverrides };
1691
+ const excludedPackages = /* @__PURE__ */ new Set();
1692
+ const bumpRanks = {
1693
+ major: 3,
1694
+ minor: 2,
1695
+ patch: 1,
1696
+ none: 0
1697
+ };
1698
+ logger.verbose(`Starting version inference for ${packageCommits.size} packages with commits`);
1699
+ for (const [pkgName, pkgCommits] of packageCommits) {
1700
+ const pkg = workspacePackages.find((p) => p.name === pkgName);
1701
+ if (!pkg) {
1702
+ logger.error(`Package ${pkgName} not found in workspace packages, skipping`);
1703
+ continue;
1704
+ }
1705
+ processedPackages.add(pkgName);
1706
+ const globalCommits = globalCommitsPerPackage.get(pkgName) || [];
1707
+ const allCommitsForPackage = [...pkgCommits, ...globalCommits];
1708
+ const determinedBump = determineHighestBump(allCommitsForPackage);
1709
+ const override = newOverrides[pkgName];
1710
+ const effectiveBump = override?.type || determinedBump;
1711
+ const canPrompt = !isCI && showPrompt;
1712
+ if (effectiveBump === "none" && !canPrompt) continue;
1713
+ let newVersion = override?.version || getNextVersion(pkg.version, effectiveBump);
1714
+ let finalBumpType = effectiveBump;
1715
+ if (canPrompt) {
1716
+ logger.clearScreen();
1717
+ logger.section(`📝 Commits for ${farver.cyan(pkg.name)}`);
1718
+ formatCommitsForDisplay(allCommitsForPackage).split("\n").forEach((line) => logger.item(line));
1719
+ logger.emptyLine();
1720
+ const selectedVersion = await selectVersionPrompt(workspaceRoot, pkg, pkg.version, newVersion, {
1721
+ defaultChoice: override ? "suggested" : "auto",
1722
+ suggestedHint: override ? "from override" : void 0
1723
+ });
1724
+ if (selectedVersion === null) continue;
1725
+ const userBump = calculateBumpType(pkg.version, selectedVersion);
1726
+ finalBumpType = userBump;
1727
+ if (selectedVersion === pkg.version) {
1728
+ excludedPackages.add(pkgName);
1729
+ if (determinedBump !== "none") {
1730
+ const nextOverride = {
1731
+ type: "none",
1732
+ version: pkg.version
1733
+ };
1734
+ if (!override || override.type !== nextOverride.type || override.version !== nextOverride.version) {
1735
+ newOverrides[pkgName] = nextOverride;
1736
+ logger.info(`Override set for ${pkgName}: suggested as-is (${pkg.version}) from auto ${determinedBump}`);
1737
+ }
1738
+ } else if (newOverrides[pkgName]) {
1739
+ delete newOverrides[pkgName];
1740
+ logger.info(`Override cleared for ${pkgName}.`);
1741
+ }
1742
+ versionUpdates.push({
1743
+ package: pkg,
1744
+ currentVersion: pkg.version,
1745
+ newVersion: pkg.version,
1746
+ bumpType: "none",
1747
+ hasDirectChanges: allCommitsForPackage.length > 0,
1748
+ changeKind: "as-is"
1749
+ });
1750
+ continue;
1751
+ }
1752
+ if (bumpRanks[userBump] < bumpRanks[determinedBump]) {
1753
+ const nextOverride = {
1754
+ type: userBump,
1755
+ version: selectedVersion
1756
+ };
1757
+ if (!override || override.type !== nextOverride.type || override.version !== nextOverride.version) {
1758
+ newOverrides[pkgName] = nextOverride;
1759
+ logger.info(`Override set for ${pkgName}: suggested ${userBump} (${selectedVersion}) from auto ${determinedBump}`);
1760
+ }
1761
+ } else if (newOverrides[pkgName] && bumpRanks[userBump] >= bumpRanks[determinedBump]) {
1762
+ delete newOverrides[pkgName];
1763
+ logger.info(`Override cleared for ${pkgName}.`);
1764
+ }
1765
+ newVersion = selectedVersion;
1766
+ }
1767
+ versionUpdates.push({
1768
+ package: pkg,
1769
+ currentVersion: pkg.version,
1770
+ newVersion,
1771
+ bumpType: finalBumpType,
1772
+ hasDirectChanges: allCommitsForPackage.length > 0,
1773
+ changeKind: canPrompt ? "manual" : "auto"
1774
+ });
1775
+ }
1776
+ if (!isCI && showPrompt) for (const pkg of workspacePackages) {
1777
+ if (processedPackages.has(pkg.name)) continue;
1778
+ logger.clearScreen();
1779
+ logger.section(`📦 Package: ${pkg.name}`);
1780
+ logger.item("No direct commits found");
1781
+ const newVersion = await selectVersionPrompt(workspaceRoot, pkg, pkg.version, pkg.version);
1782
+ if (newVersion === null) break;
1783
+ if (newVersion === pkg.version) {
1784
+ excludedPackages.add(pkg.name);
1785
+ continue;
1786
+ }
1787
+ const bumpType = calculateBumpType(pkg.version, newVersion);
1788
+ versionUpdates.push({
1789
+ package: pkg,
1790
+ currentVersion: pkg.version,
1791
+ newVersion,
1792
+ bumpType,
1793
+ hasDirectChanges: false,
1794
+ changeKind: "manual"
1795
+ });
1796
+ }
1797
+ return {
1798
+ updates: versionUpdates,
1799
+ overrides: newOverrides,
1800
+ excludedPackages
597
1801
  };
598
- for (const commit of limitedCommits) if (commit.type && commit.type in grouped) grouped[commit.type].push(commit);
599
- else grouped.other.push(commit);
600
- return grouped;
601
1802
  }
602
1803
  /**
603
- * Format grouped commits into a readable string
1804
+ * Calculate version updates and prepare dependent updates
1805
+ * Returns both the updates and a function to apply them
604
1806
  */
605
- function formatCommitGroups(grouped) {
606
- const lines = [];
607
- const typeLabels = {
608
- feat: "Features",
609
- fix: "Bug Fixes",
610
- perf: "Performance",
611
- chore: "Chores",
612
- docs: "Documentation",
613
- style: "Styling",
614
- refactor: "Refactoring",
615
- test: "Tests",
616
- build: "Build",
617
- ci: "CI",
618
- revert: "Reverts",
619
- other: "Other"
1807
+ async function calculateAndPrepareVersionUpdates({ workspacePackages, packageCommits, workspaceRoot, showPrompt, globalCommitsPerPackage, overrides }) {
1808
+ const { updates: directUpdates, overrides: newOverrides, excludedPackages: promptExcludedPackages } = await calculateVersionUpdates({
1809
+ workspacePackages,
1810
+ packageCommits,
1811
+ workspaceRoot,
1812
+ showPrompt,
1813
+ globalCommitsPerPackage,
1814
+ overrides
1815
+ });
1816
+ const graph = buildPackageDependencyGraph(workspacePackages);
1817
+ const overrideExcludedPackages = new Set(Object.entries(newOverrides).filter(([, override]) => override.type === "none").map(([pkgName]) => pkgName));
1818
+ const allUpdates = createDependentUpdates(graph, workspacePackages, directUpdates, new Set([...overrideExcludedPackages, ...promptExcludedPackages]));
1819
+ const applyUpdates = async () => {
1820
+ await Promise.all(allUpdates.map(async (update) => {
1821
+ const depUpdates = getDependencyUpdates(update.package, allUpdates);
1822
+ await updatePackageJson(update.package, update.newVersion, depUpdates);
1823
+ }));
620
1824
  };
621
- for (const type of [
622
- "feat",
623
- "fix",
624
- "perf",
625
- "refactor",
626
- "test",
627
- "docs",
628
- "style",
629
- "build",
630
- "ci",
631
- "chore",
632
- "revert",
633
- "other"
634
- ]) {
635
- const commits = grouped[type];
636
- if (commits.length > 0) {
637
- lines.push(`\n${typeLabels[type]}:`);
638
- for (const commit of commits) {
639
- const scope = commit.scope ? `(${commit.scope})` : "";
640
- const breaking = commit.isBreaking ? " ⚠️ BREAKING" : "";
641
- lines.push(` • ${commit.type}${scope}: ${commit.message}${breaking}`);
642
- }
1825
+ return {
1826
+ allUpdates,
1827
+ applyUpdates,
1828
+ overrides: newOverrides
1829
+ };
1830
+ }
1831
+ async function updatePackageJson(pkg, newVersion, dependencyUpdates) {
1832
+ const packageJsonPath = join(pkg.path, "package.json");
1833
+ const content = await readFile(packageJsonPath, "utf-8");
1834
+ const packageJson = JSON.parse(content);
1835
+ packageJson.version = newVersion;
1836
+ function updateDependency(deps, depName, depVersion, isPeerDependency = false) {
1837
+ if (!deps) return;
1838
+ const oldVersion = deps[depName];
1839
+ if (!oldVersion) return;
1840
+ if (oldVersion === "workspace:*") {
1841
+ logger.verbose(` - Skipping workspace:* dependency: ${depName}`);
1842
+ return;
643
1843
  }
1844
+ if (isPeerDependency) {
1845
+ const majorVersion = depVersion.split(".")[0];
1846
+ deps[depName] = `>=${depVersion} <${Number(majorVersion) + 1}.0.0`;
1847
+ } else deps[depName] = `^${depVersion}`;
1848
+ logger.verbose(` - Updated dependency ${depName}: ${oldVersion} → ${deps[depName]}`);
1849
+ }
1850
+ for (const [depName, depVersion] of dependencyUpdates) {
1851
+ updateDependency(packageJson.dependencies, depName, depVersion);
1852
+ updateDependency(packageJson.devDependencies, depName, depVersion);
1853
+ updateDependency(packageJson.peerDependencies, depName, depVersion, true);
644
1854
  }
645
- return lines.join("\n");
1855
+ await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, "utf-8");
1856
+ logger.verbose(` - Successfully wrote updated package.json`);
646
1857
  }
647
- async function selectPackagePrompt(packages) {
648
- const response = await prompts({
649
- type: "multiselect",
650
- name: "selectedPackages",
651
- message: "Select packages to release",
652
- choices: packages.map((pkg) => ({
653
- title: `${pkg.name} (${farver.bold(pkg.version)})`,
654
- value: pkg.name,
655
- selected: true
656
- })),
657
- min: 1,
658
- hint: "Space to select/deselect. Return to submit.",
659
- instructions: false
660
- });
661
- if (!response.selectedPackages || response.selectedPackages.length === 0) return [];
662
- return response.selectedPackages;
1858
+ /**
1859
+ * Get all dependency updates needed for a package
1860
+ */
1861
+ function getDependencyUpdates(pkg, allUpdates) {
1862
+ const updates = /* @__PURE__ */ new Map();
1863
+ const allDeps = [...pkg.workspaceDependencies, ...pkg.workspaceDevDependencies];
1864
+ for (const dep of allDeps) {
1865
+ const update = allUpdates.find((u) => u.package.name === dep);
1866
+ if (update) {
1867
+ logger.verbose(` - Dependency ${dep} will be updated: ${update.currentVersion} → ${update.newVersion} (${update.bumpType})`);
1868
+ updates.set(dep, update.newVersion);
1869
+ }
1870
+ }
1871
+ if (updates.size === 0) logger.verbose(` - No dependency updates needed`);
1872
+ return updates;
663
1873
  }
664
- async function promptVersionOverride(pkg, workspaceRoot, currentVersion, suggestedVersion, suggestedBumpType) {
665
- const commitSummary = formatCommitGroups(await getCommitsForPackage(pkg, workspaceRoot));
666
- if (commitSummary.trim()) console.log(`\nRecent changes in ${pkg.name}:${commitSummary}\n`);
667
- const choices = [{
668
- title: `Use suggested: ${suggestedVersion} (${suggestedBumpType})`,
669
- value: "suggested"
670
- }];
671
- for (const bumpType of [
672
- "patch",
673
- "minor",
674
- "major"
675
- ]) if (bumpType !== suggestedBumpType) {
676
- const version = calculateNewVersion(currentVersion, bumpType);
677
- choices.push({
678
- title: `${bumpType}: ${version}`,
679
- value: bumpType
1874
+
1875
+ //#endregion
1876
+ //#region src/operations/calculate.ts
1877
+ async function calculateUpdates(options) {
1878
+ const { workspacePackages, workspaceRoot, showPrompt, overrides, globalCommitMode } = options;
1879
+ try {
1880
+ const grouped = await getWorkspacePackageGroupedCommits(workspaceRoot, workspacePackages);
1881
+ return ok(await calculateAndPrepareVersionUpdates({
1882
+ workspacePackages,
1883
+ packageCommits: grouped,
1884
+ workspaceRoot,
1885
+ showPrompt,
1886
+ globalCommitsPerPackage: await getGlobalCommitsPerPackage(workspaceRoot, grouped, workspacePackages, globalCommitMode),
1887
+ overrides
1888
+ }));
1889
+ } catch (error) {
1890
+ return err({
1891
+ type: "git",
1892
+ operation: "calculateUpdates",
1893
+ message: error instanceof Error ? error.message : String(error)
680
1894
  });
681
1895
  }
682
- choices.push({
683
- title: "Custom version",
684
- value: "custom"
1896
+ }
1897
+ function ensureHasPackages(packages) {
1898
+ if (packages.length === 0) return err({
1899
+ type: "git",
1900
+ operation: "discoverWorkspacePackages",
1901
+ message: "No packages found to release"
685
1902
  });
686
- const response = await prompts([{
687
- type: "select",
688
- name: "choice",
689
- message: `${pkg.name} (${currentVersion}):`,
690
- choices,
691
- initial: 0
692
- }, {
693
- type: (prev) => prev === "custom" ? "text" : null,
694
- name: "customVersion",
695
- message: "Enter custom version:",
696
- initial: suggestedVersion,
697
- validate: (value) => {
698
- return /^\d+\.\d+\.\d+(?:[-+].+)?$/.test(value) || "Invalid semver version (e.g., 1.0.0)";
699
- }
700
- }]);
701
- if (response.choice === "suggested") return suggestedVersion;
702
- else if (response.choice === "custom") return response.customVersion;
703
- else return calculateNewVersion(currentVersion, response.choice);
1903
+ return ok(packages);
704
1904
  }
705
- async function promptVersionOverrides(packages, workspaceRoot) {
706
- const overrides = /* @__PURE__ */ new Map();
707
- for (const item of packages) {
708
- const newVersion = await promptVersionOverride(item.package, workspaceRoot, item.currentVersion, item.suggestedVersion, item.bumpType);
709
- overrides.set(item.package.name, newVersion);
1905
+
1906
+ //#endregion
1907
+ //#region src/operations/pr.ts
1908
+ async function syncPullRequest(options) {
1909
+ const { github, releaseBranch, defaultBranch, pullRequestTitle, pullRequestBody, updates } = options;
1910
+ let existing = null;
1911
+ try {
1912
+ existing = await github.getExistingPullRequest(releaseBranch);
1913
+ } catch (error) {
1914
+ return {
1915
+ ok: false,
1916
+ error: toGitHubError("getExistingPullRequest", error)
1917
+ };
1918
+ }
1919
+ const doesExist = !!existing;
1920
+ const title = existing?.title || pullRequestTitle || "chore: update package versions";
1921
+ const body = generatePullRequestBody(updates, pullRequestBody);
1922
+ let pr = null;
1923
+ try {
1924
+ pr = await github.upsertPullRequest({
1925
+ pullNumber: existing?.number,
1926
+ title,
1927
+ body,
1928
+ head: releaseBranch,
1929
+ base: defaultBranch
1930
+ });
1931
+ } catch (error) {
1932
+ return {
1933
+ ok: false,
1934
+ error: toGitHubError("upsertPullRequest", error)
1935
+ };
710
1936
  }
711
- return overrides;
1937
+ return ok({
1938
+ pullRequest: pr,
1939
+ created: !doesExist
1940
+ });
712
1941
  }
713
1942
 
714
1943
  //#endregion
715
- //#region src/workspace.ts
716
- async function discoverWorkspacePackages(workspaceRoot, options) {
717
- let workspaceOptions;
718
- let explicitPackages;
719
- if (options.packages == null || options.packages === true) workspaceOptions = { excludePrivate: false };
720
- else if (Array.isArray(options.packages)) {
721
- workspaceOptions = {
722
- excludePrivate: false,
723
- included: options.packages
724
- };
725
- explicitPackages = options.packages;
726
- } else {
727
- workspaceOptions = options.packages;
728
- if (options.packages.included) explicitPackages = options.packages.included;
1944
+ //#region src/workflows/prepare.ts
1945
+ async function prepareWorkflow(options) {
1946
+ if (options.safeguards) {
1947
+ const clean = await isWorkingDirectoryClean(options.workspaceRoot);
1948
+ if (!clean.ok) exitWithError("Failed to verify working directory state.", "Ensure this is a valid git repository and try again.", clean.error);
1949
+ if (!clean.value) exitWithError("Working directory is not clean. Please commit or stash your changes before proceeding.");
729
1950
  }
730
- const workspacePackages = await findWorkspacePackages(workspaceRoot, workspaceOptions);
731
- if (explicitPackages) {
732
- const foundNames = new Set(workspacePackages.map((p) => p.name));
733
- const missing = explicitPackages.filter((p) => !foundNames.has(p));
734
- if (missing.length > 0) throw new Error(`Packages not found in workspace: ${missing.join(", ")}`);
1951
+ const discovered = await discoverWorkspacePackages(options.workspaceRoot, options);
1952
+ if (!discovered.ok) exitWithError("Failed to discover packages.", void 0, discovered.error);
1953
+ const ensured = ensureHasPackages(discovered.value);
1954
+ if (!ensured.ok) {
1955
+ logger.warn(ensured.error.message);
1956
+ return null;
735
1957
  }
736
- let packagesToAnalyze = workspacePackages;
737
- const isPackagePromptEnabled = options.prompts?.packages !== false;
738
- if (!isCI && isPackagePromptEnabled && !explicitPackages) {
739
- const selectedNames = await selectPackagePrompt(workspacePackages);
740
- packagesToAnalyze = workspacePackages.filter((pkg) => selectedNames.includes(pkg.name));
1958
+ const workspacePackages = ensured.value;
1959
+ logger.section("📦 Workspace Packages");
1960
+ logger.item(`Found ${workspacePackages.length} packages`);
1961
+ for (const pkg of workspacePackages) {
1962
+ logger.item(`${farver.cyan(pkg.name)} (${farver.bold(pkg.version)})`);
1963
+ logger.item(` ${farver.gray("→")} ${farver.gray(pkg.path)}`);
741
1964
  }
742
- return {
1965
+ logger.emptyLine();
1966
+ const prepareBranchResult = await prepareReleaseBranch({
1967
+ workspaceRoot: options.workspaceRoot,
1968
+ releaseBranch: options.branch.release,
1969
+ defaultBranch: options.branch.default
1970
+ });
1971
+ if (!prepareBranchResult.ok) exitWithError("Failed to prepare release branch.", void 0, prepareBranchResult.error);
1972
+ const overridesPath = join(options.workspaceRoot, ucdjsReleaseOverridesPath);
1973
+ let existingOverrides = {};
1974
+ try {
1975
+ const overridesContent = await readFile(overridesPath, "utf-8");
1976
+ existingOverrides = JSON.parse(overridesContent);
1977
+ logger.info("Found existing version overrides file.");
1978
+ } catch (error) {
1979
+ logger.info("No existing version overrides file found. Continuing...");
1980
+ logger.verbose(`Reading overrides file failed: ${formatUnknownError(error).message}`);
1981
+ }
1982
+ const updatesResult = await calculateUpdates({
743
1983
  workspacePackages,
744
- packagesToAnalyze
1984
+ workspaceRoot: options.workspaceRoot,
1985
+ showPrompt: options.prompts?.versions !== false,
1986
+ globalCommitMode: options.globalCommitMode === "none" ? false : options.globalCommitMode,
1987
+ overrides: existingOverrides
1988
+ });
1989
+ if (!updatesResult.ok) exitWithError("Failed to calculate package updates.", void 0, updatesResult.error);
1990
+ const { allUpdates, applyUpdates, overrides: newOverrides } = updatesResult.value;
1991
+ const hasOverrideChanges = JSON.stringify(existingOverrides) !== JSON.stringify(newOverrides);
1992
+ if (Object.keys(newOverrides).length > 0 && hasOverrideChanges) {
1993
+ logger.step("Writing version overrides file...");
1994
+ try {
1995
+ await mkdir(join(options.workspaceRoot, ".github"), { recursive: true });
1996
+ await writeFile(overridesPath, JSON.stringify(newOverrides, null, 2), "utf-8");
1997
+ logger.success("Successfully wrote version overrides file.");
1998
+ } catch (e) {
1999
+ logger.error("Failed to write version overrides file:", e);
2000
+ }
2001
+ } else if (Object.keys(newOverrides).length > 0) logger.step("Version overrides unchanged. Skipping write.");
2002
+ if (Object.keys(newOverrides).length === 0 && Object.keys(existingOverrides).length > 0) {
2003
+ let shouldRemoveOverrides = false;
2004
+ for (const update of allUpdates) {
2005
+ const overriddenVersion = existingOverrides[update.package.name];
2006
+ if (overriddenVersion) {
2007
+ if (compare(update.newVersion, overriddenVersion.version) > 0) {
2008
+ shouldRemoveOverrides = true;
2009
+ break;
2010
+ }
2011
+ }
2012
+ }
2013
+ if (shouldRemoveOverrides) {
2014
+ logger.info("Removing obsolete version overrides file...");
2015
+ try {
2016
+ await rm(overridesPath);
2017
+ logger.success("Successfully removed obsolete version overrides file.");
2018
+ } catch (e) {
2019
+ logger.error("Failed to remove obsolete version overrides file:", e);
2020
+ }
2021
+ }
2022
+ }
2023
+ if (allUpdates.filter((u) => u.hasDirectChanges).length === 0) logger.warn("No packages have changes requiring a release");
2024
+ logger.section("🔄 Version Updates");
2025
+ logger.item(`Updating ${allUpdates.length} packages (including dependents)`);
2026
+ for (const update of allUpdates) {
2027
+ const suffix = update.changeKind === "as-is" ? farver.dim(" (as-is)") : "";
2028
+ logger.item(`${update.package.name}: ${update.currentVersion} → ${update.newVersion}${suffix}`);
2029
+ }
2030
+ await applyUpdates();
2031
+ if (options.changelog?.enabled) {
2032
+ logger.step("Updating changelogs");
2033
+ const groupedPackageCommits = await getWorkspacePackageGroupedCommits(options.workspaceRoot, workspacePackages);
2034
+ const globalCommitsPerPackage = await getGlobalCommitsPerPackage(options.workspaceRoot, groupedPackageCommits, workspacePackages, options.globalCommitMode === "none" ? false : options.globalCommitMode);
2035
+ const changelogPromises = allUpdates.map((update) => {
2036
+ const pkgCommits = groupedPackageCommits.get(update.package.name) || [];
2037
+ const globalCommits = globalCommitsPerPackage.get(update.package.name) || [];
2038
+ const allCommits = [...pkgCommits, ...globalCommits];
2039
+ if (allCommits.length === 0) {
2040
+ logger.verbose(`No commits for ${update.package.name}, skipping changelog`);
2041
+ return Promise.resolve();
2042
+ }
2043
+ logger.verbose(`Updating changelog for ${farver.cyan(update.package.name)}`);
2044
+ return updateChangelog({
2045
+ normalizedOptions: {
2046
+ ...options,
2047
+ workspaceRoot: options.workspaceRoot
2048
+ },
2049
+ githubClient: options.githubClient,
2050
+ workspacePackage: update.package,
2051
+ version: update.newVersion,
2052
+ previousVersion: update.currentVersion !== "0.0.0" ? update.currentVersion : void 0,
2053
+ commits: allCommits,
2054
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0]
2055
+ });
2056
+ }).filter((p) => p != null);
2057
+ const updates = await Promise.all(changelogPromises);
2058
+ logger.success(`Updated ${updates.length} changelog(s)`);
2059
+ }
2060
+ const hasChangesToPush = await syncReleaseChanges({
2061
+ workspaceRoot: options.workspaceRoot,
2062
+ releaseBranch: options.branch.release,
2063
+ commitMessage: "chore: update release versions",
2064
+ hasChanges: true
2065
+ });
2066
+ if (!hasChangesToPush.ok) exitWithError("Failed to sync release changes.", void 0, hasChangesToPush.error);
2067
+ if (!hasChangesToPush.value) {
2068
+ const prResult = await syncPullRequest({
2069
+ github: options.githubClient,
2070
+ releaseBranch: options.branch.release,
2071
+ defaultBranch: options.branch.default,
2072
+ pullRequestTitle: options.pullRequest?.title,
2073
+ pullRequestBody: options.pullRequest?.body,
2074
+ updates: allUpdates
2075
+ });
2076
+ if (!prResult.ok) exitWithError("Failed to sync release pull request.", void 0, prResult.error);
2077
+ if (prResult.value.pullRequest) {
2078
+ logger.item("No updates needed, PR is already up to date");
2079
+ const checkoutResult = await checkoutBranch(options.branch.default, options.workspaceRoot);
2080
+ if (!checkoutResult.ok) exitWithError(`Failed to checkout branch: ${options.branch.default}`, void 0, checkoutResult.error);
2081
+ return {
2082
+ updates: allUpdates,
2083
+ prUrl: prResult.value.pullRequest.html_url,
2084
+ created: prResult.value.created
2085
+ };
2086
+ }
2087
+ logger.error("No changes to commit, and no existing PR. Nothing to do.");
2088
+ return null;
2089
+ }
2090
+ const prResult = await syncPullRequest({
2091
+ github: options.githubClient,
2092
+ releaseBranch: options.branch.release,
2093
+ defaultBranch: options.branch.default,
2094
+ pullRequestTitle: options.pullRequest?.title,
2095
+ pullRequestBody: options.pullRequest?.body,
2096
+ updates: allUpdates
2097
+ });
2098
+ if (!prResult.ok) exitWithError("Failed to sync release pull request.", void 0, prResult.error);
2099
+ if (prResult.value.pullRequest?.html_url) {
2100
+ logger.section("🚀 Pull Request");
2101
+ logger.success(`Pull request ${prResult.value.created ? "created" : "updated"}: ${prResult.value.pullRequest.html_url}`);
2102
+ }
2103
+ const returnToDefault = await checkoutBranch(options.branch.default, options.workspaceRoot);
2104
+ if (!returnToDefault.ok) exitWithError(`Failed to checkout branch: ${options.branch.default}`, void 0, returnToDefault.error);
2105
+ if (!returnToDefault.value) exitWithError(`Failed to checkout branch: ${options.branch.default}`);
2106
+ return {
2107
+ updates: allUpdates,
2108
+ prUrl: prResult.value.pullRequest?.html_url,
2109
+ created: prResult.value.created
745
2110
  };
746
2111
  }
747
- async function findWorkspacePackages(workspaceRoot, options) {
2112
+
2113
+ //#endregion
2114
+ //#region src/core/npm.ts
2115
+ function toNPMError(operation, error, code) {
2116
+ const formatted = formatUnknownError(error);
2117
+ return {
2118
+ type: "npm",
2119
+ operation,
2120
+ message: formatted.message,
2121
+ code: code || formatted.code,
2122
+ stderr: formatted.stderr,
2123
+ status: formatted.status
2124
+ };
2125
+ }
2126
+ /**
2127
+ * Get the NPM registry URL
2128
+ * Respects NPM_CONFIG_REGISTRY environment variable, defaults to npmjs.org
2129
+ */
2130
+ function getRegistryURL() {
2131
+ return process.env.NPM_CONFIG_REGISTRY || "https://registry.npmjs.org";
2132
+ }
2133
+ /**
2134
+ * Fetch package metadata from NPM registry
2135
+ * @param packageName - The package name (e.g., "lodash" or "@scope/name")
2136
+ * @returns Result with package metadata or error
2137
+ */
2138
+ async function getPackageMetadata(packageName) {
748
2139
  try {
749
- const result = await run("pnpm", [
750
- "-r",
751
- "ls",
752
- "--json"
753
- ], { nodeOptions: {
2140
+ const registry = getRegistryURL();
2141
+ const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : encodeURIComponent(packageName);
2142
+ const response = await fetch(`${registry}/${encodedName}`, { headers: { Accept: "application/json" } });
2143
+ if (!response.ok) {
2144
+ if (response.status === 404) return err(toNPMError("getPackageMetadata", `Package not found: ${packageName}`, "E404"));
2145
+ return err(toNPMError("getPackageMetadata", `HTTP ${response.status}: ${response.statusText}`));
2146
+ }
2147
+ return ok(await response.json());
2148
+ } catch (error) {
2149
+ return err(toNPMError("getPackageMetadata", error, "ENETWORK"));
2150
+ }
2151
+ }
2152
+ /**
2153
+ * Check if a specific package version exists on NPM
2154
+ * @param packageName - The package name
2155
+ * @param version - The version to check (e.g., "1.2.3")
2156
+ * @returns Result with boolean (true if version exists) or error
2157
+ */
2158
+ async function checkVersionExists(packageName, version) {
2159
+ const metadataResult = await getPackageMetadata(packageName);
2160
+ if (!metadataResult.ok) {
2161
+ if (metadataResult.error.code === "E404") return ok(false);
2162
+ return err(metadataResult.error);
2163
+ }
2164
+ return ok(version in metadataResult.value.versions);
2165
+ }
2166
+ /**
2167
+ * Publish a package to NPM
2168
+ * Uses pnpm to handle workspace protocol and catalog: resolution automatically
2169
+ * @param packageName - The package name to publish
2170
+ * @param version - The package version to publish
2171
+ * @param workspaceRoot - Path to the workspace root
2172
+ * @param options - Normalized release scripts options
2173
+ * @returns Result indicating success or failure
2174
+ */
2175
+ async function publishPackage(packageName, version, workspaceRoot, options) {
2176
+ const args = [
2177
+ "--filter",
2178
+ packageName,
2179
+ "publish",
2180
+ "--access",
2181
+ options.npm.access,
2182
+ "--no-git-checks"
2183
+ ];
2184
+ if (options.npm.otp) args.push("--otp", options.npm.otp);
2185
+ const explicitTag = process.env.NPM_CONFIG_TAG;
2186
+ const prereleaseTag = (() => {
2187
+ const prerelease = semver.prerelease(version);
2188
+ if (!prerelease || prerelease.length === 0) return;
2189
+ const identifier = prerelease[0];
2190
+ if (identifier === "alpha" || identifier === "beta") return identifier;
2191
+ return "next";
2192
+ })();
2193
+ const publishTag = explicitTag || prereleaseTag;
2194
+ if (publishTag) args.push("--tag", publishTag);
2195
+ const env = { ...process.env };
2196
+ if (options.npm.provenance) env.NPM_CONFIG_PROVENANCE = "true";
2197
+ try {
2198
+ await runIfNotDry("pnpm", args, { nodeOptions: {
754
2199
  cwd: workspaceRoot,
755
- stdio: "pipe"
2200
+ stdio: "inherit",
2201
+ env
756
2202
  } });
757
- const rawProjects = JSON.parse(result.stdout);
758
- const allPackageNames = new Set(rawProjects.map((p) => p.name));
759
- const excludedPackages = /* @__PURE__ */ new Set();
760
- const promises = rawProjects.map(async (rawProject) => {
761
- const content = await readFile(join(rawProject.path, "package.json"), "utf-8");
762
- const packageJson = JSON.parse(content);
763
- if (!shouldIncludePackage(packageJson, options)) {
764
- excludedPackages.add(rawProject.name);
765
- return null;
766
- }
767
- return {
768
- name: rawProject.name,
769
- version: rawProject.version,
770
- path: rawProject.path,
771
- packageJson,
772
- workspaceDependencies: extractWorkspaceDependencies(rawProject.dependencies, allPackageNames),
773
- workspaceDevDependencies: extractWorkspaceDependencies(rawProject.devDependencies, allPackageNames)
774
- };
775
- });
776
- const packages = await Promise.all(promises);
777
- if (excludedPackages.size > 0) console.info(`${farver.cyan("[info]:")} Excluded packages: ${farver.green(Array.from(excludedPackages).join(", "))}`);
778
- return packages.filter((pkg) => pkg !== null);
779
- } catch (err) {
780
- console.error("Error discovering workspace packages:", err);
781
- throw err;
2203
+ return ok(void 0);
2204
+ } catch (error) {
2205
+ const errorMessage = formatUnknownError(error).message;
2206
+ return err(toNPMError("publishPackage", error, errorMessage.includes("E403") ? "E403" : errorMessage.includes("EPUBLISHCONFLICT") ? "EPUBLISHCONFLICT" : errorMessage.includes("EOTP") ? "EOTP" : void 0));
782
2207
  }
783
2208
  }
784
- function shouldIncludePackage(pkg, options) {
785
- if (!options) return true;
786
- if (options.excludePrivate && pkg.private) return false;
787
- if (options.included && options.included.length > 0) {
788
- if (!options.included.includes(pkg.name)) return false;
2209
+
2210
+ //#endregion
2211
+ //#region src/workflows/publish.ts
2212
+ async function publishWorkflow(options) {
2213
+ logger.section("📦 Publishing Packages");
2214
+ const discovered = await discoverWorkspacePackages(options.workspaceRoot, options);
2215
+ if (!discovered.ok) exitWithError("Failed to discover packages.", void 0, discovered.error);
2216
+ const workspacePackages = discovered.value;
2217
+ logger.item(`Found ${workspacePackages.length} packages in workspace`);
2218
+ const graph = buildPackageDependencyGraph(workspacePackages);
2219
+ const publicPackages = workspacePackages.filter((pkg) => !pkg.packageJson.private);
2220
+ logger.item(`Publishing ${publicPackages.length} public packages (private packages excluded)`);
2221
+ if (publicPackages.length === 0) {
2222
+ logger.warn("No public packages to publish");
2223
+ return;
789
2224
  }
790
- if (options.excluded?.includes(pkg.name)) return false;
791
- return true;
792
- }
793
- function extractWorkspaceDependencies(dependencies, workspacePackages) {
794
- if (!dependencies) return [];
795
- return Object.keys(dependencies).filter((dep) => {
796
- return workspacePackages.has(dep);
797
- });
2225
+ const publishOrder = getPackagePublishOrder(graph, new Set(publicPackages.map((p) => p.name)));
2226
+ const status = {
2227
+ published: [],
2228
+ skipped: [],
2229
+ failed: []
2230
+ };
2231
+ for (const order of publishOrder) {
2232
+ const pkg = order.package;
2233
+ const version = pkg.version;
2234
+ const packageName = pkg.name;
2235
+ logger.section(`📦 ${farver.cyan(packageName)} ${farver.gray(`(level ${order.level})`)}`);
2236
+ logger.step(`Checking if ${farver.cyan(`${packageName}@${version}`)} exists on NPM...`);
2237
+ const existsResult = await checkVersionExists(packageName, version);
2238
+ if (!existsResult.ok) {
2239
+ logger.error(`Failed to check version: ${existsResult.error.message}`);
2240
+ status.failed.push(packageName);
2241
+ exitWithError(`Publishing failed for ${packageName}.`, "Check your network connection and NPM registry access", existsResult.error);
2242
+ }
2243
+ if (existsResult.value) {
2244
+ logger.info(`Version ${farver.cyan(version)} already exists on NPM, skipping`);
2245
+ status.skipped.push(packageName);
2246
+ continue;
2247
+ }
2248
+ logger.step(`Publishing ${farver.cyan(`${packageName}@${version}`)} to NPM...`);
2249
+ const publishResult = await publishPackage(packageName, version, options.workspaceRoot, options);
2250
+ if (!publishResult.ok) {
2251
+ logger.error(`Failed to publish: ${publishResult.error.message}`);
2252
+ status.failed.push(packageName);
2253
+ let hint;
2254
+ if (publishResult.error.code === "E403") hint = "Authentication failed. Ensure your NPM token or OIDC configuration is correct";
2255
+ else if (publishResult.error.code === "EPUBLISHCONFLICT") hint = "Version conflict. The version may have been published recently";
2256
+ else if (publishResult.error.code === "EOTP") hint = "2FA/OTP required. Provide the otp option or use OIDC authentication";
2257
+ exitWithError(`Publishing failed for ${packageName}`, hint, publishResult.error);
2258
+ }
2259
+ logger.success(`Published ${farver.cyan(`${packageName}@${version}`)}`);
2260
+ status.published.push(packageName);
2261
+ logger.step(`Creating git tag ${farver.cyan(`${packageName}@${version}`)}...`);
2262
+ const tagResult = await createAndPushPackageTag(packageName, version, options.workspaceRoot);
2263
+ if (!tagResult.ok) {
2264
+ logger.error(`Failed to create/push tag: ${tagResult.error.message}`);
2265
+ logger.warn(`Package was published but tag was not created. You may need to create it manually.`);
2266
+ } else logger.success(`Created and pushed tag ${farver.cyan(`${packageName}@${version}`)}`);
2267
+ }
2268
+ logger.section("📊 Publishing Summary");
2269
+ logger.item(`${farver.green("✓")} Published: ${status.published.length} package(s)`);
2270
+ if (status.published.length > 0) for (const pkg of status.published) logger.item(` ${farver.green("•")} ${pkg}`);
2271
+ if (status.skipped.length > 0) {
2272
+ logger.item(`${farver.yellow("⚠")} Skipped (already exists): ${status.skipped.length} package(s)`);
2273
+ for (const pkg of status.skipped) logger.item(` ${farver.yellow("•")} ${pkg}`);
2274
+ }
2275
+ if (status.failed.length > 0) {
2276
+ logger.item(`${farver.red("✖")} Failed: ${status.failed.length} package(s)`);
2277
+ for (const pkg of status.failed) logger.item(` ${farver.red("•")} ${pkg}`);
2278
+ }
2279
+ if (status.failed.length > 0) exitWithError(`Publishing completed with ${status.failed.length} failure(s)`);
2280
+ logger.success("All packages published successfully!");
798
2281
  }
799
2282
 
800
2283
  //#endregion
801
- //#region src/release.ts
802
- async function release(options) {
803
- const { dryRun: dryRun$1 = false, safeguards = true, workspaceRoot = process.cwd(), releaseBranch = "release/next", githubToken } = options;
804
- globalOptions.dryRun = dryRun$1;
805
- if (githubToken.trim() === "" || githubToken == null) throw new Error("GitHub token is required");
806
- const [owner, repo] = options.repo.split("/");
807
- if (!owner || !repo) throw new Error(`Invalid repo format: ${options.repo}. Expected "owner/repo".`);
808
- if (safeguards && !await isWorkingDirectoryClean(workspaceRoot)) {
809
- console.error("Working directory is not clean. Please commit or stash your changes before proceeding.");
810
- return null;
2284
+ //#region src/workflows/verify.ts
2285
+ async function verifyWorkflow(options) {
2286
+ if (options.safeguards) {
2287
+ const clean = await isWorkingDirectoryClean(options.workspaceRoot);
2288
+ if (!clean.ok) exitWithError("Failed to verify working directory state.", "Ensure this is a valid git repository and try again.", clean.error);
2289
+ if (!clean.value) exitWithError("Working directory is not clean. Please commit or stash your changes before proceeding.");
811
2290
  }
812
- const { workspacePackages, packagesToAnalyze } = await discoverWorkspacePackages(workspaceRoot, options);
813
- if (packagesToAnalyze.length === 0) {
814
- console.log("No packages found to analyze for release.");
815
- return null;
2291
+ const releaseBranch = options.branch.release;
2292
+ const defaultBranch = options.branch.default;
2293
+ const releasePr = await options.githubClient.getExistingPullRequest(releaseBranch);
2294
+ if (!releasePr || !releasePr.head) {
2295
+ logger.warn(`No open release pull request found for branch "${releaseBranch}". Nothing to verify.`);
2296
+ return;
816
2297
  }
817
- const changedPackages = await analyzeCommits(packagesToAnalyze, workspaceRoot);
818
- if (changedPackages.size === 0) throw new Error("No packages have changes requiring a release");
819
- let versionUpdates = [];
820
- for (const [pkgName, bump] of changedPackages) {
821
- const pkg = workspacePackages.find((p) => p.name === pkgName);
822
- if (pkg) versionUpdates.push(createVersionUpdate(pkg, bump, true));
823
- }
824
- const isVersionPromptEnabled = options.prompts?.versions !== false;
825
- if (!isCI && isVersionPromptEnabled) {
826
- const versionOverrides = await promptVersionOverrides(versionUpdates.map((u) => ({
827
- package: u.package,
828
- currentVersion: u.currentVersion,
829
- suggestedVersion: u.newVersion,
830
- bumpType: u.bumpType
831
- })), workspaceRoot);
832
- versionUpdates = versionUpdates.map((update) => {
833
- const overriddenVersion = versionOverrides.get(update.package.name);
834
- if (overriddenVersion && overriddenVersion !== update.newVersion) return {
835
- ...update,
836
- newVersion: overriddenVersion
837
- };
838
- return update;
839
- });
2298
+ logger.info(`Found release PR #${releasePr.number}. Verifying against default branch "${defaultBranch}"...`);
2299
+ const originalBranch = await getCurrentBranch(options.workspaceRoot);
2300
+ if (!originalBranch.ok) exitWithError("Failed to detect current branch.", void 0, originalBranch.error);
2301
+ if (originalBranch.value !== defaultBranch) {
2302
+ const checkout = await checkoutBranch(defaultBranch, options.workspaceRoot);
2303
+ if (!checkout.ok) exitWithError(`Failed to checkout branch: ${defaultBranch}`, void 0, checkout.error);
2304
+ if (!checkout.value) exitWithError(`Failed to checkout branch: ${defaultBranch}`);
840
2305
  }
841
- const allUpdates = createDependentUpdates(buildPackageDependencyGraph(workspacePackages), workspacePackages, versionUpdates);
842
- const currentBranch = await getCurrentBranch(workspaceRoot);
843
- const existingPullRequest = await getExistingPullRequest({
844
- owner,
845
- repo,
846
- branch: releaseBranch,
847
- githubToken
848
- });
849
- const prExists = !!existingPullRequest;
850
- if (prExists) console.log("Existing pull request found:", existingPullRequest.html_url);
851
- else console.log("No existing pull request found, will create new one");
852
- const branchExists = await doesBranchExist(releaseBranch, workspaceRoot);
853
- if (!branchExists) {
854
- console.log("Creating release branch:", releaseBranch);
855
- await createBranch(releaseBranch, currentBranch, workspaceRoot);
856
- }
857
- if (!await checkoutBranch(releaseBranch, workspaceRoot)) throw new Error(`Failed to checkout branch: ${releaseBranch}`);
858
- if (branchExists) {
859
- console.log("Pulling latest changes from remote");
860
- if (!await pullLatestChanges(releaseBranch, workspaceRoot)) console.log("Warning: Failed to pull latest changes, continuing anyway");
861
- }
862
- console.log("Rebasing release branch onto", currentBranch);
863
- await rebaseBranch(currentBranch, workspaceRoot);
864
- await updateAllPackageJsonFiles(allUpdates);
865
- const hasCommitted = await commitChanges("chore: update release versions", workspaceRoot);
866
- const isBranchAhead = await isBranchAheadOfRemote(releaseBranch, workspaceRoot);
867
- if (!hasCommitted && !isBranchAhead) {
868
- console.log("No changes to commit and branch is in sync with remote");
869
- await checkoutBranch(currentBranch, workspaceRoot);
870
- if (prExists) {
871
- console.log("No updates needed, PR is already up to date");
872
- return {
873
- updates: allUpdates,
874
- prUrl: existingPullRequest.html_url,
875
- created: false
876
- };
877
- } else {
878
- console.error("No changes to commit, and no existing PR. Nothing to do.");
879
- return null;
2306
+ let existingOverrides = {};
2307
+ try {
2308
+ const overridesContent = await readFileFromGit(options.workspaceRoot, releasePr.head.sha, ucdjsReleaseOverridesPath);
2309
+ if (overridesContent.ok && overridesContent.value) {
2310
+ existingOverrides = JSON.parse(overridesContent.value);
2311
+ logger.info("Found existing version overrides file on release branch.");
880
2312
  }
2313
+ } catch (error) {
2314
+ logger.info("No version overrides file found on release branch. Continuing...");
2315
+ logger.verbose(`Reading release overrides failed: ${formatUnknownError(error).message}`);
881
2316
  }
882
- console.log("Pushing changes to remote");
883
- await pushBranch(releaseBranch, workspaceRoot, { forceWithLease: true });
884
- const prTitle = existingPullRequest?.title || options.pullRequest?.title || "chore: update package versions";
885
- const prBody = generatePullRequestBody(allUpdates, options.pullRequest?.body);
886
- const pullRequest = await upsertPullRequest({
887
- owner,
888
- repo,
889
- pullNumber: existingPullRequest?.number,
890
- title: prTitle,
891
- body: prBody,
892
- head: releaseBranch,
893
- base: currentBranch,
894
- githubToken
2317
+ const discovered = await discoverWorkspacePackages(options.workspaceRoot, options);
2318
+ if (!discovered.ok) exitWithError("Failed to discover packages.", void 0, discovered.error);
2319
+ const ensured = ensureHasPackages(discovered.value);
2320
+ if (!ensured.ok) {
2321
+ logger.warn(ensured.error.message);
2322
+ return;
2323
+ }
2324
+ const mainPackages = ensured.value;
2325
+ const updatesResult = await calculateUpdates({
2326
+ workspacePackages: mainPackages,
2327
+ workspaceRoot: options.workspaceRoot,
2328
+ showPrompt: false,
2329
+ globalCommitMode: options.globalCommitMode === "none" ? false : options.globalCommitMode,
2330
+ overrides: existingOverrides
895
2331
  });
896
- console.log(prExists ? "Updated pull request:" : "Created pull request:", pullRequest?.html_url);
897
- await checkoutBranch(currentBranch, workspaceRoot);
2332
+ if (!updatesResult.ok) exitWithError("Failed to calculate expected package updates.", void 0, updatesResult.error);
2333
+ const expectedUpdates = updatesResult.value.allUpdates;
2334
+ const expectedVersionMap = new Map(expectedUpdates.map((u) => [u.package.name, u.newVersion]));
2335
+ const prVersionMap = /* @__PURE__ */ new Map();
2336
+ for (const pkg of mainPackages) {
2337
+ const pkgJsonPath = relative(options.workspaceRoot, join(pkg.path, "package.json"));
2338
+ const pkgJsonContent = await readFileFromGit(options.workspaceRoot, releasePr.head.sha, pkgJsonPath);
2339
+ if (pkgJsonContent.ok && pkgJsonContent.value) {
2340
+ const pkgJson = JSON.parse(pkgJsonContent.value);
2341
+ prVersionMap.set(pkg.name, pkgJson.version);
2342
+ }
2343
+ }
2344
+ if (originalBranch.value !== defaultBranch) await checkoutBranch(originalBranch.value, options.workspaceRoot);
2345
+ let isOutOfSync = false;
2346
+ for (const [pkgName, expectedVersion] of expectedVersionMap.entries()) {
2347
+ const prVersion = prVersionMap.get(pkgName);
2348
+ if (!prVersion) {
2349
+ logger.warn(`Package "${pkgName}" found in default branch but not in release branch. Skipping.`);
2350
+ continue;
2351
+ }
2352
+ if (gt(expectedVersion, prVersion)) {
2353
+ logger.error(`Package "${pkgName}" is out of sync. Expected version >= ${expectedVersion}, but PR has ${prVersion}.`);
2354
+ isOutOfSync = true;
2355
+ } else logger.success(`Package "${pkgName}" is up to date (PR version: ${prVersion}, Expected: ${expectedVersion})`);
2356
+ }
2357
+ const statusContext = "ucdjs/release-verify";
2358
+ if (isOutOfSync) {
2359
+ await options.githubClient.setCommitStatus({
2360
+ sha: releasePr.head.sha,
2361
+ state: "failure",
2362
+ context: statusContext,
2363
+ description: "Release PR is out of sync with the default branch. Please re-run the release process."
2364
+ });
2365
+ logger.error("Verification failed. Commit status set to 'failure'.");
2366
+ } else {
2367
+ await options.githubClient.setCommitStatus({
2368
+ sha: releasePr.head.sha,
2369
+ state: "success",
2370
+ context: statusContext,
2371
+ description: "Release PR is up to date.",
2372
+ targetUrl: `https://github.com/${options.owner}/${options.repo}/pull/${releasePr.number}`
2373
+ });
2374
+ logger.success("Verification successful. Commit status set to 'success'.");
2375
+ }
2376
+ }
2377
+
2378
+ //#endregion
2379
+ //#region src/index.ts
2380
+ async function createReleaseScripts(options) {
2381
+ const normalizedOptions = normalizeReleaseScriptsOptions(options);
898
2382
  return {
899
- updates: allUpdates,
900
- prUrl: pullRequest?.html_url,
901
- created: !prExists
2383
+ async verify() {
2384
+ return verifyWorkflow(normalizedOptions);
2385
+ },
2386
+ async prepare() {
2387
+ return prepareWorkflow(normalizedOptions);
2388
+ },
2389
+ async publish() {
2390
+ return publishWorkflow(normalizedOptions);
2391
+ },
2392
+ packages: {
2393
+ async list() {
2394
+ const result = await discoverWorkspacePackages(normalizedOptions.workspaceRoot, normalizedOptions);
2395
+ if (!result.ok) throw new Error(result.error.message);
2396
+ return result.value;
2397
+ },
2398
+ async get(packageName) {
2399
+ const result = await discoverWorkspacePackages(normalizedOptions.workspaceRoot, normalizedOptions);
2400
+ if (!result.ok) throw new Error(result.error.message);
2401
+ return result.value.find((p) => p.name === packageName);
2402
+ }
2403
+ }
902
2404
  };
903
2405
  }
904
2406
 
905
2407
  //#endregion
906
- export { release };
2408
+ export { createReleaseScripts };