@ucdjs/release-scripts 0.1.0-beta.9 → 0.1.0

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