@ucdjs/release-scripts 0.1.0-beta.6 → 0.1.0-beta.60

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