@icebreakers/monorepo 5.5.8 → 5.5.10

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.
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
2
  import { i as getWorkspacePackages, n as getWorkspaceData, r as getWorkspacePackageSummaries, t as clearWorkspaceCache } from "./workspace-MCKewElu.mjs";
3
- import { b as isIgnorableFsError, c as package_default$1, f as resolveRepoctlLocale, i as packageDir, l as version$1, m as logger, n as assetsDir, o as templatesDir, t as initToolingTargets, u as localize, y as fs$1 } from "./types-90NVHAdA.mjs";
3
+ import { b as isIgnorableFsError, c as package_default$1, f as resolveRepoctlLocale, i as packageDir, l as version$1, m as logger, n as assetsDir, o as templatesDir, t as initToolingTargets, u as localize, y as fs$1 } from "./types-m8JLwKzl.mjs";
4
4
  import { a as loadMonorepoConfig, c as resolveToolingConfig, i as getRepoctlConfigCandidates, o as loadMonorepoConfigDetails, s as resolveCommandConfig } from "./config-p842Knhq.mjs";
5
5
  import { f as defineTsconfigConfig } from "./tooling-BfXlmCi-.mjs";
6
6
  import gitUrlParse from "git-url-parse";
@@ -8,17 +8,17 @@ import { simpleGit } from "simple-git";
8
8
  import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
9
9
  import path from "pathe";
10
10
  import process from "node:process";
11
- import { access, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
11
+ import { access, copyFile, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
12
12
  import { execFileSync, spawnSync } from "node:child_process";
13
13
  import fs from "node:fs";
14
14
  import path$1 from "node:path";
15
15
  import { checkbox, ensureTemplateAssetsPrepared, getAssetTargets, getTemplateChoices, getWorkspacePackageManager, isGitignoreFile, scaffoldTemplate, shouldSkipTemplatePath, suggestTemplateKey, templateChoices, toPublishGitignorePath, toWorkspaceAssetPath, toWorkspaceGitignorePath } from "@icebreakers/monorepo-templates";
16
16
  import YAML, { isSeq, parseDocument } from "yaml";
17
17
  import { Buffer } from "node:buffer";
18
- import crypto, { randomUUID } from "node:crypto";
19
- import os from "node:os";
18
+ import crypto, { createHash, randomUUID } from "node:crypto";
19
+ import os, { tmpdir } from "node:os";
20
20
  import pc from "picocolors";
21
- import { coerce, gte, minVersion, satisfies } from "semver";
21
+ import semver, { coerce, gte, minVersion, satisfies } from "semver";
22
22
  import { parse, stringify } from "comment-json";
23
23
  import { stripVTControlCharacters } from "node:util";
24
24
  import { performance } from "node:perf_hooks";
@@ -1848,7 +1848,7 @@ var package_default = {
1848
1848
  type: "module",
1849
1849
  version: "0.0.0",
1850
1850
  "private": true,
1851
- packageManager: "pnpm@12.6.0",
1851
+ packageManager: "pnpm@12.8.1",
1852
1852
  description: "Source workspace for repoctl and Icebreaker's shared development packages",
1853
1853
  author: "ice breaker <hi@sonofmagic.top>",
1854
1854
  license: "MIT",
@@ -2663,6 +2663,79 @@ var ReleaseCommandError = class extends Error {
2663
2663
  }
2664
2664
  };
2665
2665
  //#endregion
2666
+ //#region src/commands/release/intents/index.ts
2667
+ function parseLedger(content) {
2668
+ const ledger = YAML.parse(content) ?? {};
2669
+ if (!ledger || typeof ledger !== "object" || Array.isArray(ledger)) throw new ReleaseCommandError("Invalid .changeset/ledger.yaml");
2670
+ return Object.fromEntries(Object.entries(ledger).map(([key, value]) => {
2671
+ const entry = value;
2672
+ const intents = Array.isArray(value) ? value : entry?.intents ?? [];
2673
+ if (value != null && !Array.isArray(value) && (typeof value !== "object" || typeof entry?.dir !== "string") || !Array.isArray(intents) || intents.some((id) => typeof id !== "string")) throw new ReleaseCommandError(`Invalid ledger entry: ${key}`);
2674
+ return [key, {
2675
+ ...typeof entry?.dir === "string" ? { dir: entry.dir } : {},
2676
+ intents
2677
+ }];
2678
+ }));
2679
+ }
2680
+ async function readLedger(cwd) {
2681
+ try {
2682
+ return parseLedger(await readFile(path.join(cwd, ".changeset/ledger.yaml"), "utf8"));
2683
+ } catch (error) {
2684
+ if (error.code === "ENOENT") return {};
2685
+ throw error;
2686
+ }
2687
+ }
2688
+ function parseIntent(content, filename) {
2689
+ const lines = content.replace(/^\uFEFF/, "").split(/\r?\n/);
2690
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
2691
+ if (lines[0]?.trim() !== "---" || end < 0) throw new ReleaseCommandError(`Invalid change intent frontmatter: ${filename}`);
2692
+ let data;
2693
+ try {
2694
+ data = YAML.parse(lines.slice(1, end).join("\n")) ?? {};
2695
+ } catch {
2696
+ throw new ReleaseCommandError(`Invalid change intent YAML: ${filename}`);
2697
+ }
2698
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.values(data).some((value) => ![
2699
+ "none",
2700
+ "patch",
2701
+ "minor",
2702
+ "major"
2703
+ ].includes(String(value)))) throw new ReleaseCommandError(`Invalid change intent bump type: ${filename}`);
2704
+ return Object.entries(data);
2705
+ }
2706
+ /** Only unconsumed release requests count; declines and resurrected prose do not. */
2707
+ async function readPendingIntents(cwd) {
2708
+ let files;
2709
+ try {
2710
+ files = await readdir(path.join(cwd, ".changeset"), { withFileTypes: true });
2711
+ } catch (error) {
2712
+ if (error.code === "ENOENT") return [];
2713
+ throw error;
2714
+ }
2715
+ const root = await realpath(cwd);
2716
+ const ledger = await readLedger(cwd);
2717
+ const config = YAML.parse(await readFile(path.join(cwd, "pnpm-workspace.yaml"), "utf8"));
2718
+ const workspace = await getWorkspacePackages(cwd, { ignorePrivatePackage: false });
2719
+ const pending = [];
2720
+ for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
2721
+ if (!file.isFile() || !file.name.endsWith(".md") || file.name.toLowerCase() === "readme.md") continue;
2722
+ const filename = `.changeset/${file.name}`;
2723
+ const releases = parseIntent(await readFile(path.join(cwd, filename), "utf8"), filename);
2724
+ let active = false;
2725
+ for (const [reference, bump] of releases) {
2726
+ if (bump === "none") continue;
2727
+ const pkg = workspace.find((item) => item.manifest.name === reference || path.relative(root, item.rootDir) === reference.replace(/^\.\//, ""));
2728
+ if (!pkg) throw new ReleaseCommandError(`Unknown package ${reference} in ${filename}`);
2729
+ const dir = path.relative(root, pkg.rootDir);
2730
+ const lane = config.versioning?.lanes?.[pkg.manifest.name ?? ""] ?? config.versioning?.lanes?.[dir];
2731
+ const consumed = Object.entries(ledger).some(([key, entry]) => (entry.dir ? entry.dir.replace(/^\.\//, "") === dir : key.slice(0, key.lastIndexOf("@")) === pkg.manifest.name) && entry.intents.includes(file.name.slice(0, -3)) && (lane && lane !== "main" || !semver.prerelease(key.slice(key.lastIndexOf("@") + 1))));
2732
+ active ||= !consumed;
2733
+ }
2734
+ if (active) pending.push(filename);
2735
+ }
2736
+ return pending;
2737
+ }
2738
+ //#endregion
2666
2739
  //#region src/commands/release/shared.ts
2667
2740
  function getReleaseEnv(options) {
2668
2741
  return options.env ?? process.env;
@@ -2705,11 +2778,7 @@ function hasGitChanges(options) {
2705
2778
  }).status !== 0;
2706
2779
  }
2707
2780
  async function hasPendingIntents(cwd) {
2708
- try {
2709
- return (await readdir(path.join(cwd, ".changeset"), { withFileTypes: true })).some((entry) => entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md");
2710
- } catch {
2711
- return false;
2712
- }
2781
+ return (await readPendingIntents(cwd)).length > 0;
2713
2782
  }
2714
2783
  function resolveBranch(options) {
2715
2784
  return options.branch?.trim() || getReleaseEnv(options)["GITHUB_REF_NAME"]?.trim() || capture("git", [
@@ -2920,6 +2989,100 @@ function buildGitHubReleaseBodyFromChangelog(packageName, packageVersion, change
2920
2989
  }], metadata), metadata);
2921
2990
  }
2922
2991
  //#endregion
2992
+ //#region src/commands/release/workspace-protocol.ts
2993
+ const EXPECTED_WORKSPACE_SPEC = "workspace:*";
2994
+ const DEPENDENCY_SECTIONS = [
2995
+ "dependencies",
2996
+ "devDependencies",
2997
+ "optionalDependencies",
2998
+ "peerDependencies"
2999
+ ];
3000
+ function displayPath(workspaceDir, packagePath) {
3001
+ return path.relative(workspaceDir, packagePath).replaceAll("\\", "/");
3002
+ }
3003
+ function collectWorkspaceProtocolViolations(options) {
3004
+ const violations = [];
3005
+ for (const entry of options.packages) {
3006
+ if (entry.packageJson.private === true || typeof entry.packageJson.name !== "string") continue;
3007
+ for (const section of DEPENDENCY_SECTIONS) {
3008
+ const dependencies = entry.packageJson[section];
3009
+ if (!dependencies) continue;
3010
+ for (const [dependencyName, spec] of Object.entries(dependencies)) if (options.workspacePackageNames.has(dependencyName) && spec !== EXPECTED_WORKSPACE_SPEC) violations.push(`${displayPath(options.workspaceDir, entry.file)} -> ${section}.${dependencyName}=${spec}`);
3011
+ }
3012
+ }
3013
+ return violations;
3014
+ }
3015
+ async function readPackageManifest(file) {
3016
+ return JSON.parse(await readFile(file, "utf8"));
3017
+ }
3018
+ async function assertWorkspaceDependencyProtocols(cwd) {
3019
+ const { workspaceDir, packages } = await getWorkspaceData(cwd, { ignorePrivatePackage: false });
3020
+ const manifests = await Promise.all(packages.map(async (pkg) => ({
3021
+ file: pkg.pkgJsonPath,
3022
+ packageJson: await readPackageManifest(pkg.pkgJsonPath)
3023
+ })));
3024
+ const violations = collectWorkspaceProtocolViolations({
3025
+ workspaceDir,
3026
+ packages: manifests,
3027
+ workspacePackageNames: new Set(manifests.map(({ packageJson }) => packageJson.name).filter((name) => typeof name === "string"))
3028
+ });
3029
+ if (violations.length > 0) throw new ReleaseCommandError([`Expected publishable workspace dependencies to use ${EXPECTED_WORKSPACE_SPEC}:`, ...violations.map((violation) => `- ${violation}`)].join("\n"));
3030
+ }
3031
+ //#endregion
3032
+ //#region src/commands/release/hooks.ts
3033
+ const defaultQualityScripts = [
3034
+ "build",
3035
+ "lint",
3036
+ "test"
3037
+ ];
3038
+ function validateScriptName(script) {
3039
+ const normalizedScript = script.trim();
3040
+ if (!normalizedScript) throw new ReleaseCommandError("release script name must not be empty");
3041
+ return normalizedScript;
3042
+ }
3043
+ function runScripts(scripts, options, extraEnv) {
3044
+ for (const script of scripts) run("pnpm", ["run", validateScriptName(script)], {
3045
+ ...options,
3046
+ ...extraEnv ? { env: {
3047
+ ...options.env ?? process.env,
3048
+ ...extraEnv
3049
+ } } : {}
3050
+ });
3051
+ }
3052
+ async function runQualityScripts(options) {
3053
+ await assertWorkspaceDependencyProtocols(options.cwd);
3054
+ runScripts(options.config?.qualityScripts ?? defaultQualityScripts, options);
3055
+ runScripts(options.config?.hooks?.verify ?? [], options);
3056
+ }
3057
+ function runReleaseHooks(phase, options) {
3058
+ runScripts(options.config?.hooks?.[phase] ?? [], options);
3059
+ }
3060
+ function runAfterPublishHooks(packages, options) {
3061
+ if (!packages.length) return;
3062
+ const extraEnv = {
3063
+ REPO_RELEASE_PUBLISHED_PACKAGES: JSON.stringify(packages),
3064
+ REPO_RELEASE_PUBLISH_SUMMARY: path.resolve(options.cwd, "pnpm-publish-summary.json")
3065
+ };
3066
+ for (const hook of options.config?.hooks?.afterPublish ?? []) try {
3067
+ runScripts([hook.script], options, extraEnv);
3068
+ } catch (error) {
3069
+ if (!hook.continueOnError) throw error;
3070
+ logger.warn(`release afterPublish hook failed and was ignored: ${hook.script}`);
3071
+ }
3072
+ }
3073
+ //#endregion
3074
+ //#region src/commands/release/github/errors.ts
3075
+ var GitHubApiError = class extends ReleaseCommandError {
3076
+ status;
3077
+ responseBody;
3078
+ constructor(message, status, responseBody) {
3079
+ super(message);
3080
+ this.status = status;
3081
+ this.responseBody = responseBody;
3082
+ this.name = "GitHubApiError";
3083
+ }
3084
+ };
3085
+ //#endregion
2923
3086
  //#region src/commands/release/github/metadata.ts
2924
3087
  function parseReleasePullRequestContributors(body) {
2925
3088
  if (!body) return [];
@@ -2968,17 +3131,100 @@ async function enrichReleaseNote(request, document) {
2968
3131
  };
2969
3132
  }
2970
3133
  //#endregion
2971
- //#region src/commands/release/github/client.ts
2972
- var GitHubApiError = class extends ReleaseCommandError {
2973
- status;
2974
- responseBody;
2975
- constructor(message, status, responseBody) {
2976
- super(message);
2977
- this.status = status;
2978
- this.responseBody = responseBody;
2979
- this.name = "GitHubApiError";
3134
+ //#region src/commands/release/github/state.ts
3135
+ const branch = "repoctl-release-state";
3136
+ function missing(error) {
3137
+ return error instanceof Error && "status" in error && error.status === 404;
3138
+ }
3139
+ function statePath(key) {
3140
+ if (!/^[a-f0-9]{64}$/.test(key)) throw new ReleaseCommandError("Invalid release state key");
3141
+ return `/contents/.repoctl-release/${key}.json`;
3142
+ }
3143
+ async function readReleaseState(request, key) {
3144
+ try {
3145
+ const { data } = await request("GET", `${statePath(key)}?ref=${branch}`);
3146
+ if (!data?.sha || !data.content) throw new ReleaseCommandError("GitHub returned an invalid release checkpoint");
3147
+ return {
3148
+ revision: data.sha,
3149
+ state: JSON.parse(Buffer.from(data.content, "base64").toString("utf8"))
3150
+ };
3151
+ } catch (error) {
3152
+ if (missing(error)) return;
3153
+ throw error;
2980
3154
  }
2981
- };
3155
+ }
3156
+ async function writeReleaseState(request, key, state, revision) {
3157
+ if (!revision) try {
3158
+ await request("GET", `/git/ref/heads/${branch}`);
3159
+ } catch (error) {
3160
+ if (!missing(error)) throw error;
3161
+ try {
3162
+ await request("POST", "/git/refs", {
3163
+ ref: `refs/heads/${branch}`,
3164
+ sha: state.packages[0]?.target
3165
+ });
3166
+ } catch {
3167
+ await request("GET", `/git/ref/heads/${branch}`);
3168
+ }
3169
+ }
3170
+ const content = JSON.stringify(state);
3171
+ try {
3172
+ const { data } = await request("PUT", statePath(key), {
3173
+ message: "chore(release): checkpoint release lifecycle [skip ci]",
3174
+ branch,
3175
+ content: Buffer.from(content).toString("base64"),
3176
+ ...revision ? { sha: revision } : {}
3177
+ });
3178
+ if (!data?.content.sha) throw new ReleaseCommandError("GitHub returned no release checkpoint revision");
3179
+ return data.content.sha;
3180
+ } catch (error) {
3181
+ const recovered = await readReleaseState(request, key);
3182
+ if (recovered && JSON.stringify(recovered.state) === content) return recovered.revision;
3183
+ throw new ReleaseCommandError(`Release checkpoint write failed or another publisher advanced it; retry after the other run finishes. ${error instanceof Error ? error.message : String(error)}`);
3184
+ }
3185
+ }
3186
+ //#endregion
3187
+ //#region src/commands/release/github/tags.ts
3188
+ async function readTagTarget(request, tag) {
3189
+ let object;
3190
+ try {
3191
+ object = (await request("GET", `/git/ref/tags/${encodeURIComponent(tag)}`)).data?.object;
3192
+ } catch (error) {
3193
+ if (error instanceof GitHubApiError && error.status === 404) return;
3194
+ throw error;
3195
+ }
3196
+ for (let depth = 0; object?.type === "tag" && depth < 10; depth++) object = (await request("GET", `/git/tags/${object.sha}`)).data?.object;
3197
+ if (object?.type !== "commit") throw new ReleaseCommandError(`Cannot resolve tag target for ${tag}`);
3198
+ return object.sha;
3199
+ }
3200
+ async function ensureTag(request, options) {
3201
+ const verify = async () => {
3202
+ const target = await readTagTarget(request, options.tag);
3203
+ if (target === void 0) return false;
3204
+ if (target !== options.target) throw new ReleaseCommandError(`Tag target conflict for ${options.tag}: expected ${options.target}, got ${target}; refusing to move the tag`);
3205
+ return true;
3206
+ };
3207
+ if (await verify()) return;
3208
+ try {
3209
+ await request("POST", "/git/refs", {
3210
+ ref: `refs/tags/${options.tag}`,
3211
+ sha: options.target
3212
+ });
3213
+ } catch (error) {
3214
+ if (!(error instanceof GitHubApiError) || ![
3215
+ 0,
3216
+ 422,
3217
+ 429,
3218
+ 500,
3219
+ 502,
3220
+ 503,
3221
+ 504
3222
+ ].includes(error.status)) throw error;
3223
+ if (!await verify()) throw error;
3224
+ }
3225
+ }
3226
+ //#endregion
3227
+ //#region src/commands/release/github/client.ts
2982
3228
  var GitHubClient = class {
2983
3229
  token;
2984
3230
  repository;
@@ -3008,6 +3254,7 @@ var GitHubClient = class {
3008
3254
  try {
3009
3255
  response = await this.requestFetch(`${this.apiUrl}/repos/${repository}${endpoint}`, {
3010
3256
  method,
3257
+ signal: AbortSignal.timeout(3e4),
3011
3258
  headers: {
3012
3259
  "Accept": "application/vnd.github+json",
3013
3260
  "Authorization": `Bearer ${this.token}`,
@@ -3017,7 +3264,7 @@ var GitHubClient = class {
3017
3264
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
3018
3265
  });
3019
3266
  } catch (error) {
3020
- if (method !== "POST" && attempt < this.retryAttempts) {
3267
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3021
3268
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3022
3269
  continue;
3023
3270
  }
@@ -3027,7 +3274,7 @@ var GitHubClient = class {
3027
3274
  try {
3028
3275
  text = await response.text();
3029
3276
  } catch (error) {
3030
- if (method !== "POST" && attempt < this.retryAttempts) {
3277
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3031
3278
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3032
3279
  continue;
3033
3280
  }
@@ -3037,21 +3284,21 @@ var GitHubClient = class {
3037
3284
  if (text) try {
3038
3285
  data = JSON.parse(text);
3039
3286
  } catch {
3040
- if (attempt < this.retryAttempts) {
3287
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3041
3288
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3042
3289
  continue;
3043
3290
  }
3044
- throw new GitHubApiError(`GitHub API returned invalid JSON for ${method} ${endpoint}`, response.status, text);
3291
+ throw new GitHubApiError(`GitHub API returned invalid JSON for ${method} ${endpoint}`, method === "POST" || method === "PUT" ? 0 : response.status, text);
3045
3292
  }
3046
3293
  if (!response.ok) {
3047
3294
  const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : text || response.statusText;
3048
- if ((response.status === 429 || response.status >= 500) && attempt < this.retryAttempts) {
3295
+ if (method !== "POST" && method !== "PUT" && (response.status === 429 || response.status >= 500) && attempt < this.retryAttempts) {
3049
3296
  const retryAfter = response.headers.get("retry-after");
3050
3297
  const reset = response.headers.get("x-ratelimit-reset");
3051
3298
  const retrySeconds = retryAfter && /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) : retryAfter ? Math.max(0, (Date.parse(retryAfter) - Date.now()) / 1e3) : 0;
3052
3299
  const resetSeconds = reset && /^\d+$/.test(reset) ? Math.max(0, Number(reset) - Date.now() / 1e3) : 0;
3053
3300
  const delay = Math.max(this.retryDelay * 2 ** (attempt - 1), retrySeconds * 1e3, resetSeconds * 1e3);
3054
- await this.sleep(delay);
3301
+ await this.sleep(Math.min(delay, 3e4));
3055
3302
  continue;
3056
3303
  }
3057
3304
  throw new GitHubApiError(`GitHub API ${method} ${endpoint} failed (${response.status}): ${message}`, response.status, text);
@@ -3066,6 +3313,12 @@ var GitHubClient = class {
3066
3313
  getRequest() {
3067
3314
  return this.request.bind(this);
3068
3315
  }
3316
+ async readReleaseState(key) {
3317
+ return readReleaseState(this.getRequest(), key);
3318
+ }
3319
+ async writeReleaseState(key, state, revision) {
3320
+ return writeReleaseState(this.getRequest(), key, state, revision);
3321
+ }
3069
3322
  async ensurePullRequest(options) {
3070
3323
  const [owner] = this.getRepository().split("/");
3071
3324
  const head = options.head.includes(":") ? options.head : `${owner}:${options.head}`;
@@ -3137,7 +3390,8 @@ var GitHubClient = class {
3137
3390
  if (options.body !== void 0 || options.name !== void 0) return (await this.request("PATCH", `/releases/${existing.id}`, {
3138
3391
  ...options.name === void 0 ? {} : { name: options.name },
3139
3392
  ...options.body === void 0 ? {} : { body: options.body },
3140
- prerelease: options.prerelease ?? false
3393
+ prerelease: options.prerelease ?? false,
3394
+ draft: false
3141
3395
  })).data ?? existing;
3142
3396
  return existing;
3143
3397
  }
@@ -3201,106 +3455,136 @@ var GitHubClient = class {
3201
3455
  async readReleasePullRequestContributors(target) {
3202
3456
  return readReleasePullRequestContributors(this.getRequest(), target);
3203
3457
  }
3458
+ async readTagTarget(tag) {
3459
+ return readTagTarget(this.getRequest(), tag);
3460
+ }
3204
3461
  async ensureTag(options) {
3205
- const endpoint = `/git/ref/tags/${encodeURIComponent(options.tag)}`;
3206
- try {
3207
- await this.request("GET", endpoint);
3208
- return;
3209
- } catch (error) {
3210
- if (!(error instanceof GitHubApiError) || error.status !== 404) throw error;
3211
- }
3212
- try {
3213
- await this.request("POST", "/git/refs", {
3214
- ref: `refs/tags/${options.tag}`,
3215
- sha: options.target
3216
- });
3217
- } catch (error) {
3218
- if (!(error instanceof GitHubApiError) || error.status !== 422) throw error;
3219
- await this.request("GET", endpoint);
3220
- }
3462
+ return ensureTag(this.getRequest(), options);
3221
3463
  }
3222
3464
  };
3223
3465
  //#endregion
3224
- //#region src/commands/release/workspace-protocol.ts
3225
- const EXPECTED_WORKSPACE_SPEC = "workspace:*";
3226
- const DEPENDENCY_SECTIONS = [
3227
- "dependencies",
3228
- "devDependencies",
3229
- "optionalDependencies",
3230
- "peerDependencies"
3231
- ];
3232
- function displayPath(workspaceDir, packagePath) {
3233
- return path.relative(workspaceDir, packagePath).replaceAll("\\", "/");
3234
- }
3235
- function collectWorkspaceProtocolViolations(options) {
3236
- const violations = [];
3237
- for (const entry of options.packages) {
3238
- if (entry.packageJson.private === true || typeof entry.packageJson.name !== "string") continue;
3239
- for (const section of DEPENDENCY_SECTIONS) {
3240
- const dependencies = entry.packageJson[section];
3241
- if (!dependencies) continue;
3242
- for (const [dependencyName, spec] of Object.entries(dependencies)) if (options.workspacePackageNames.has(dependencyName) && spec !== EXPECTED_WORKSPACE_SPEC) violations.push(`${displayPath(options.workspaceDir, entry.file)} -> ${section}.${dependencyName}=${spec}`);
3243
- }
3244
- }
3245
- return violations;
3466
+ //#region src/commands/release/metadata.ts
3467
+ function gitRefExists(ref, options) {
3468
+ return (options.spawn ?? spawnSync)("git", [
3469
+ "rev-parse",
3470
+ "--verify",
3471
+ "--quiet",
3472
+ ref
3473
+ ], {
3474
+ cwd: options.cwd,
3475
+ encoding: "utf8",
3476
+ shell: false,
3477
+ stdio: "ignore"
3478
+ }).status === 0;
3246
3479
  }
3247
- async function readPackageManifest(file) {
3248
- return JSON.parse(await readFile(file, "utf8"));
3480
+ function remoteTagExists(tag, options) {
3481
+ return (options.spawn ?? spawnSync)("git", [
3482
+ "ls-remote",
3483
+ "--exit-code",
3484
+ "--refs",
3485
+ "origin",
3486
+ `refs/tags/${tag}`
3487
+ ], {
3488
+ cwd: options.cwd,
3489
+ encoding: "utf8",
3490
+ shell: false,
3491
+ stdio: "ignore"
3492
+ }).status === 0;
3249
3493
  }
3250
- async function assertWorkspaceDependencyProtocols(cwd) {
3251
- const { workspaceDir, packages } = await getWorkspaceData(cwd, { ignorePrivatePackage: false });
3252
- const manifests = await Promise.all(packages.map(async (pkg) => ({
3253
- file: pkg.pkgJsonPath,
3254
- packageJson: await readPackageManifest(pkg.pkgJsonPath)
3255
- })));
3256
- const violations = collectWorkspaceProtocolViolations({
3257
- workspaceDir,
3258
- packages: manifests,
3259
- workspacePackageNames: new Set(manifests.map(({ packageJson }) => packageJson.name).filter((name) => typeof name === "string"))
3494
+ function resolveGitHub(options) {
3495
+ const env = getReleaseEnv(options);
3496
+ return options.github ?? new GitHubClient({
3497
+ ...env["GITHUB_TOKEN"] ? { token: env["GITHUB_TOKEN"] } : {},
3498
+ ...env["GITHUB_REPOSITORY"] ? { repository: env["GITHUB_REPOSITORY"] } : {},
3499
+ ...env["GITHUB_API_URL"] ? { apiUrl: env["GITHUB_API_URL"] } : {}
3260
3500
  });
3261
- if (violations.length > 0) throw new ReleaseCommandError([`Expected publishable workspace dependencies to use ${EXPECTED_WORKSPACE_SPEC}:`, ...violations.map((violation) => `- ${violation}`)].join("\n"));
3262
3501
  }
3263
- //#endregion
3264
- //#region src/commands/release/hooks.ts
3265
- const defaultQualityScripts = [
3266
- "build",
3267
- "lint",
3268
- "test"
3269
- ];
3270
- function validateScriptName(script) {
3271
- const normalizedScript = script.trim();
3272
- if (!normalizedScript) throw new ReleaseCommandError("release script name must not be empty");
3273
- return normalizedScript;
3502
+ function resolveTarget(options) {
3503
+ return getReleaseEnv(options)["GITHUB_SHA"]?.trim() || capture("git", ["rev-parse", "HEAD"], options);
3274
3504
  }
3275
- function runScripts(scripts, options, extraEnv) {
3276
- for (const script of scripts) run("pnpm", ["run", validateScriptName(script)], {
3277
- ...options,
3278
- ...extraEnv ? { env: {
3279
- ...options.env ?? process.env,
3280
- ...extraEnv
3281
- } } : {}
3282
- });
3283
- }
3284
- async function runQualityScripts(options) {
3285
- await assertWorkspaceDependencyProtocols(options.cwd);
3286
- runScripts(options.config?.qualityScripts ?? defaultQualityScripts, options);
3287
- runScripts(options.config?.hooks?.verify ?? [], options);
3505
+ function resolveReleaseLocale(options) {
3506
+ return resolveRepoctlLocale({ env: getReleaseEnv(options) });
3288
3507
  }
3289
- function runReleaseHooks(phase, options) {
3290
- runScripts(options.config?.hooks?.[phase] ?? [], options);
3508
+ function formatPublishedPackageSummary(packages) {
3509
+ return ["Published packages:", ...packages.length ? packages.map((pkg) => ` - ${pkg.name}@${pkg.version}`) : [" (none)"]].join("\n");
3291
3510
  }
3292
- function runAfterPublishHooks(packages, options) {
3293
- if (!packages.length) return;
3294
- const extraEnv = {
3295
- REPO_RELEASE_PUBLISHED_PACKAGES: JSON.stringify(packages),
3296
- REPO_RELEASE_PUBLISH_SUMMARY: path.resolve(options.cwd, "pnpm-publish-summary.json")
3297
- };
3298
- for (const hook of options.config?.hooks?.afterPublish ?? []) try {
3299
- runScripts([hook.script], options, extraEnv);
3511
+ async function publishMetadata(packages, options, prerelease = false) {
3512
+ if (!packages.length) {
3513
+ logger.success(formatPublishedPackageSummary(packages));
3514
+ return;
3515
+ }
3516
+ const github = resolveGitHub(options);
3517
+ const target = resolveTarget(options);
3518
+ const releaseEnv = getReleaseEnv(options);
3519
+ let releaseContributors = [];
3520
+ if (github.readReleasePullRequestContributors) try {
3521
+ releaseContributors = await github.readReleasePullRequestContributors(target);
3300
3522
  } catch (error) {
3301
- if (!hook.continueOnError) throw error;
3302
- logger.warn(`release afterPublish hook failed and was ignored: ${hook.script}`);
3523
+ const message = error instanceof Error ? error.message : String(error);
3524
+ logger.warn(`GitHub release PR contributor lookup skipped: ${message}`);
3525
+ }
3526
+ const metadata = {
3527
+ locale: resolveReleaseLocale(options),
3528
+ ...releaseContributors.length ? { contributors: releaseContributors } : {},
3529
+ ...releaseEnv["GITHUB_REPOSITORY"] ? { repository: releaseEnv["GITHUB_REPOSITORY"] } : {},
3530
+ ...releaseEnv["GITHUB_SERVER_URL"] ? { serverUrl: releaseEnv["GITHUB_SERVER_URL"] } : {}
3531
+ };
3532
+ const publishedPackageNames = new Set(packages.map((pkg) => pkg.name));
3533
+ let noteDocument = await buildReleaseNoteDocument(options.cwd, void 0, metadata, publishedPackageNames);
3534
+ if (github.enrichReleaseNote) noteDocument = await github.enrichReleaseNote(noteDocument);
3535
+ for (const pkg of packages) {
3536
+ const tag = `${pkg.name}@${pkg.version}`;
3537
+ const body = renderGitHubRelease({
3538
+ ...noteDocument,
3539
+ packages: noteDocument.packages.filter((item) => item.name === pkg.name && item.version === pkg.version),
3540
+ entries: noteDocument.entries.filter((entry) => entry.packageName === pkg.name && entry.version === pkg.version),
3541
+ compareUrls: noteDocument.compareUrls.filter((url) => url.includes(encodeURIComponent(`${pkg.name}@`)))
3542
+ }, metadata);
3543
+ if (github.ensureTag) {
3544
+ await github.ensureTag({
3545
+ tag,
3546
+ target
3547
+ });
3548
+ await github.ensureRelease({
3549
+ tag,
3550
+ target,
3551
+ prerelease,
3552
+ name: tag,
3553
+ body
3554
+ });
3555
+ continue;
3556
+ }
3557
+ if (remoteTagExists(tag, options)) {
3558
+ await github.ensureRelease({
3559
+ tag,
3560
+ target,
3561
+ prerelease,
3562
+ name: tag,
3563
+ body
3564
+ });
3565
+ continue;
3566
+ }
3567
+ if (!gitRefExists(tag, options)) run("git", [
3568
+ "tag",
3569
+ "-a",
3570
+ tag,
3571
+ "-m",
3572
+ tag
3573
+ ], options);
3574
+ run("git", [
3575
+ "push",
3576
+ "origin",
3577
+ `refs/tags/${tag}`
3578
+ ], options);
3579
+ await github.ensureRelease({
3580
+ tag,
3581
+ target,
3582
+ prerelease,
3583
+ name: tag,
3584
+ body
3585
+ });
3303
3586
  }
3587
+ logger.success(formatPublishedPackageSummary(packages));
3304
3588
  }
3305
3589
  //#endregion
3306
3590
  //#region src/commands/release/publish/evidence.ts
@@ -3365,11 +3649,13 @@ async function writeJsonAtomic(filename, value) {
3365
3649
  /** Evidence is monotonic for this invocation; old on-disk reports are never trusted. */
3366
3650
  var PublishState = class {
3367
3651
  candidates;
3652
+ checkpoint;
3368
3653
  accepted = /* @__PURE__ */ new Map();
3369
3654
  confirmed = /* @__PURE__ */ new Set();
3370
3655
  allowed;
3371
- constructor(candidates) {
3656
+ constructor(candidates, checkpoint) {
3372
3657
  this.candidates = candidates;
3658
+ this.checkpoint = checkpoint;
3373
3659
  this.allowed = new Set(candidates.map(packageKey));
3374
3660
  }
3375
3661
  accept(packages) {
@@ -3398,6 +3684,7 @@ var PublishState = class {
3398
3684
  confirmedPackages: acceptedPackages.filter((pkg) => this.confirmed.has(packageKey(pkg)))
3399
3685
  });
3400
3686
  await writeJsonAtomic(path.join(cwd, "pnpm-publish-summary.json"), { publishedPackages: acceptedPackages });
3687
+ await this.checkpoint?.(acceptedPackages);
3401
3688
  }
3402
3689
  };
3403
3690
  //#endregion
@@ -3408,9 +3695,14 @@ function sleep(milliseconds, options) {
3408
3695
  return options.sleep?.(milliseconds) ?? new Promise((resolve) => setTimeout(resolve, milliseconds));
3409
3696
  }
3410
3697
  async function refreshRegistry(state, options, packages = state.candidates, deadline = performance.now() + visibilityBudget) {
3411
- for (const pkg of state.unconfirmed(packages)) {
3698
+ const unknown = [];
3699
+ const pending = state.unconfirmed(packages);
3700
+ for (const [index, pkg] of pending.entries()) {
3412
3701
  const remaining = Math.floor(deadline - performance.now());
3413
- if (remaining <= 0) break;
3702
+ if (remaining <= 0) {
3703
+ unknown.push(...pending.slice(index));
3704
+ break;
3705
+ }
3414
3706
  const result = (options.spawn ?? spawnSync)("npm", [
3415
3707
  "view",
3416
3708
  packageKey(pkg),
@@ -3431,8 +3723,9 @@ async function refreshRegistry(state, options, packages = state.candidates, dead
3431
3723
  if (result.status === 0 && outputText(result.stdout).trim() === pkg.version) {
3432
3724
  state.confirm(pkg);
3433
3725
  await state.save(options.cwd, "confirming");
3434
- }
3726
+ } else if (result.error || result.status === 0 || !/\bE404\b/.test(outputText(result.stderr))) unknown.push(pkg);
3435
3727
  }
3728
+ return unknown;
3436
3729
  }
3437
3730
  async function confirmVisibility(state, options, packages, initialDelay = 0) {
3438
3731
  let remaining = visibilityBudget;
@@ -3466,8 +3759,9 @@ async function getPublishCandidates(cwd) {
3466
3759
  return candidates;
3467
3760
  }
3468
3761
  /** Only pnpm uploads; accepted versions never re-enter its retry filters. */
3469
- async function publishWithRetry(args, options, candidates, confirmAll = false) {
3470
- const state = new PublishState(candidates);
3762
+ async function publishWithRetry(args, options, candidates, confirmAll = false, recovery) {
3763
+ const state = new PublishState(candidates, recovery?.save);
3764
+ state.accept(recovery?.accepted ?? []);
3471
3765
  let attemptArgs = args;
3472
3766
  let recovering = confirmAll;
3473
3767
  try {
@@ -3497,14 +3791,16 @@ async function publishWithRetry(args, options, candidates, confirmAll = false) {
3497
3791
  const delay = retryDelays[attempt - 1];
3498
3792
  logger.warn(`npm publish transient failure; reconciling before retry in ${delay / 1e3}s (attempt ${attempt + 1}/${publishAttempts}).`);
3499
3793
  await sleep(delay, options);
3500
- await refreshRegistry(state, options);
3794
+ const unknown = await refreshRegistry(state, options);
3501
3795
  await state.save(options.cwd, "publishing");
3796
+ const unresolved = unknown.filter((pkg) => state.pendingUploads.some((pending) => packageKey(pending) === packageKey(pkg)));
3797
+ if (unresolved.length) throw new ReleaseCommandError(`npm registry state is unknown; refusing to retry uploads for: ${unresolved.map(packageKey).join(", ")}`);
3502
3798
  if (!state.pendingUploads.length) {
3503
3799
  await confirmVisibility(state, options, candidates);
3504
3800
  await state.save(options.cwd, "complete");
3505
3801
  return;
3506
3802
  }
3507
- attemptArgs = [...args, ...state.pendingUploads.flatMap((pkg) => ["--filter", pkg.name])];
3803
+ attemptArgs = [...args.filter((arg, index) => arg !== "--filter" && args[index - 1] !== "--filter"), ...state.pendingUploads.flatMap((pkg) => ["--filter", pkg.name])];
3508
3804
  }
3509
3805
  } catch (error) {
3510
3806
  await state.save(options.cwd, "failed");
@@ -3513,6 +3809,374 @@ async function publishWithRetry(args, options, candidates, confirmAll = false) {
3513
3809
  }
3514
3810
  }
3515
3811
  //#endregion
3812
+ //#region src/commands/release/lifecycle/hooks.ts
3813
+ async function finishHooks(state, save, options) {
3814
+ const acknowledged = new Set((getReleaseEnv(options)["REPO_RELEASE_ACKNOWLEDGE_HOOKS"] ?? "").split(",").filter(Boolean));
3815
+ for (const hook of options.config?.hooks?.afterPublish ?? []) {
3816
+ const status = state.hooks[hook.script];
3817
+ if (status === "complete" || status === "ignored") continue;
3818
+ if (acknowledged.has(hook.script)) {
3819
+ state.hooks[hook.script] = "complete";
3820
+ await save();
3821
+ continue;
3822
+ }
3823
+ if (status === "running" && !hook.idempotent) throw new ReleaseCommandError(`afterPublish hook ${hook.script} has an unknown outcome. Verify its external result, then set REPO_RELEASE_ACKNOWLEDGE_HOOKS=${hook.script}, or declare idempotent: true only if safe to retry`);
3824
+ state.hooks[hook.script] = "running";
3825
+ await save();
3826
+ try {
3827
+ runAfterPublishHooks(state.packages.map(({ name, version }) => ({
3828
+ name,
3829
+ version
3830
+ })), {
3831
+ ...options,
3832
+ config: {
3833
+ ...options.config,
3834
+ hooks: { afterPublish: [{
3835
+ ...hook,
3836
+ continueOnError: false
3837
+ }] }
3838
+ }
3839
+ });
3840
+ state.hooks[hook.script] = "complete";
3841
+ } catch (error) {
3842
+ if (!hook.continueOnError) throw error;
3843
+ state.hooks[hook.script] = "ignored";
3844
+ }
3845
+ await save();
3846
+ }
3847
+ }
3848
+ //#endregion
3849
+ //#region src/commands/release/lifecycle/identity.ts
3850
+ /** 用原提交中的 manifest/changelog 校验版本归属,禁止以重跑 HEAD 偷换来源。 */
3851
+ async function verifySource(pkg, target, options) {
3852
+ if (!/^[a-f0-9]{40}$/.test(target)) throw new ReleaseCommandError(`Cannot establish original commit for ${pkg.name}@${pkg.version}; restore its checkpoint or use an explicit verified source commit`);
3853
+ const workspace = (await getWorkspacePackages(options.cwd)).find((item) => item.manifest.name === pkg.name);
3854
+ if (!workspace) throw new ReleaseCommandError(`Release package is absent from workspace: ${pkg.name}`);
3855
+ const relative = path.relative(await realpath(options.cwd), workspace.pkgJsonPath);
3856
+ const original = JSON.parse(capture("git", ["show", `${target}:${relative}`], options));
3857
+ if (original.name !== pkg.name || original.version !== pkg.version) throw new ReleaseCommandError(`Original commit does not contain ${pkg.name}@${pkg.version}`);
3858
+ const changelog = path.join(path.dirname(relative), "CHANGELOG.md");
3859
+ let current;
3860
+ try {
3861
+ current = await readFile(path.join(options.cwd, changelog), "utf8");
3862
+ } catch (error) {
3863
+ if (error.code === "ENOENT") return;
3864
+ throw error;
3865
+ }
3866
+ if (capture("git", ["show", `${target}:${changelog}`], options).replace(/\r\n/g, "\n").trim() !== current.replace(/\r\n/g, "\n").trim()) throw new ReleaseCommandError(`Changelog differs from original commit for ${pkg.name}; check out ${target} before recovery`);
3867
+ }
3868
+ /** 从完整 Git 历史定位当前版本首次进入主线的提交,忽略后续 CI 修复。 */
3869
+ async function findVersionCommit(pkg, options) {
3870
+ const workspace = (await getWorkspacePackages(options.cwd)).find((item) => item.manifest.name === pkg.name);
3871
+ if (!workspace || capture("git", ["rev-parse", "--is-shallow-repository"], options) !== "false") throw new ReleaseCommandError("Release source discovery requires a full checkout (fetch-depth: 0)");
3872
+ const relative = path.relative(await realpath(options.cwd), workspace.pkgJsonPath);
3873
+ const commits = capture("git", [
3874
+ "log",
3875
+ "--format=%H",
3876
+ "--",
3877
+ relative
3878
+ ], options).split("\n").filter(Boolean);
3879
+ let target = "";
3880
+ for (const commit of commits) {
3881
+ const original = JSON.parse(capture("git", ["show", `${commit}:${relative}`], options));
3882
+ if (original.name !== pkg.name || original.version !== pkg.version) break;
3883
+ target = commit;
3884
+ }
3885
+ if (!target) throw new ReleaseCommandError(`Cannot find version commit for ${pkg.name}@${pkg.version}; commit the prepared versions first`);
3886
+ return target;
3887
+ }
3888
+ //#endregion
3889
+ //#region src/commands/release/lifecycle/key.ts
3890
+ function releaseStateKey(repository, distTag, candidates) {
3891
+ return createHash("sha256").update(JSON.stringify({
3892
+ repository,
3893
+ distTag,
3894
+ packages: candidates.map(packageKey).sort()
3895
+ })).digest("hex");
3896
+ }
3897
+ //#endregion
3898
+ //#region src/commands/release/lifecycle/registry.ts
3899
+ /** 明确的 E404 才代表不存在;其余失败不能作为重新上传的依据。 */
3900
+ async function inspectRegistry(pkg, options) {
3901
+ for (let attempt = 0; attempt < 3; attempt++) {
3902
+ const result = (options.spawn ?? spawnSync)("npm", [
3903
+ "view",
3904
+ packageKey(pkg),
3905
+ "--json"
3906
+ ], {
3907
+ cwd: options.cwd,
3908
+ env: getReleaseEnv(options),
3909
+ encoding: "utf8",
3910
+ shell: false,
3911
+ stdio: [
3912
+ "ignore",
3913
+ "pipe",
3914
+ "pipe"
3915
+ ],
3916
+ timeout: 1e4,
3917
+ killSignal: "SIGKILL"
3918
+ });
3919
+ const output = `${String(result.stdout ?? "")}
3920
+ ${String(result.stderr ?? "")}`;
3921
+ if (result.status === 0) {
3922
+ try {
3923
+ const data = JSON.parse(String(result.stdout));
3924
+ if (data.version === pkg.version) return data;
3925
+ } catch {}
3926
+ throw new ReleaseCommandError(`npm returned invalid metadata for ${packageKey(pkg)}; registry state is unknown`);
3927
+ }
3928
+ if (/\bE404\b/.test(output) && !result.error) return;
3929
+ if (/\b(?:E401|E403|ENEEDAUTH)\b/.test(output)) throw new ReleaseCommandError(`npm authentication failed for ${packageKey(pkg)}`);
3930
+ if (attempt < 2) await sleep(1e3 * 2 ** attempt, options);
3931
+ }
3932
+ throw new ReleaseCommandError(`npm registry state is unknown for ${packageKey(pkg)} after bounded retries; no upload attempted`);
3933
+ }
3934
+ //#endregion
3935
+ //#region src/commands/release/lifecycle/index.ts
3936
+ async function publishLifecycle(options, selected, distTag = "latest") {
3937
+ const github = resolveGitHub(options);
3938
+ if (!github.readReleaseState || !github.writeReleaseState || !github.ensureTag || !github.listReleases) throw new ReleaseCommandError("Release recovery requires checkpoint, tag and release query operations");
3939
+ const env = getReleaseEnv(options);
3940
+ const repository = env["GITHUB_REPOSITORY"];
3941
+ if (!repository || !/^[^/]+\/[^/]+$/.test(repository)) throw new ReleaseCommandError("GITHUB_REPOSITORY is required for durable release recovery");
3942
+ const candidates = selected ?? await getPublishCandidates(options.cwd);
3943
+ const key = releaseStateKey(repository, distTag, candidates);
3944
+ const snapshot = await github.readReleaseState(key);
3945
+ let revision = snapshot?.revision;
3946
+ const releases = new Map((await github.listReleases()).map((release) => [release.tag_name, release]));
3947
+ const registry = /* @__PURE__ */ new Map();
3948
+ for (const pkg of candidates) registry.set(packageKey(pkg), await inspectRegistry(pkg, options));
3949
+ const tags = /* @__PURE__ */ new Map();
3950
+ if (github.readTagTarget) for (const pkg of candidates) tags.set(packageKey(pkg), await github.readTagTarget(packageKey(pkg)));
3951
+ let state;
3952
+ if (snapshot) {
3953
+ state = snapshot.state;
3954
+ if (state.schemaVersion !== 1 || state.repository !== repository || JSON.stringify(state.candidates.map(packageKey).sort()) !== JSON.stringify(candidates.map(packageKey).sort()) || state.packages.some((pkg) => !candidates.some((candidate) => packageKey(candidate) === packageKey(pkg)))) throw new ReleaseCommandError("Release checkpoint identity does not match this repository and exact versions");
3955
+ } else {
3956
+ const packages = [];
3957
+ for (const pkg of candidates) {
3958
+ const published = registry.get(packageKey(pkg));
3959
+ const release = releases.get(packageKey(pkg));
3960
+ const tagTarget = tags.get(packageKey(pkg));
3961
+ if (published && release && !release.draft && Boolean(release.prerelease) === (distTag !== "latest") && (!github.readTagTarget || tagTarget)) {
3962
+ if (published.gitHead && tagTarget && published.gitHead !== tagTarget) throw new ReleaseCommandError(`Tag target conflict for ${packageKey(pkg)}`);
3963
+ continue;
3964
+ }
3965
+ const target = published ? published.gitHead ?? env["REPO_RELEASE_SOURCE_SHA"] ?? "" : env["REPO_RELEASE_SOURCE_SHA"] ?? await findVersionCommit(pkg, options);
3966
+ await verifySource(pkg, target, options);
3967
+ packages.push({
3968
+ ...pkg,
3969
+ target
3970
+ });
3971
+ }
3972
+ const targets = new Set(packages.map((pkg) => pkg.target));
3973
+ for (const pkg of candidates) {
3974
+ const source = registry.get(packageKey(pkg))?.gitHead;
3975
+ if (source && targets.has(source) && !packages.some((item) => packageKey(item) === packageKey(pkg))) {
3976
+ await verifySource(pkg, source, options);
3977
+ packages.push({
3978
+ ...pkg,
3979
+ target: source
3980
+ });
3981
+ }
3982
+ }
3983
+ if (!packages.length) {
3984
+ logger.info("No unfinished release targets found.");
3985
+ return [];
3986
+ }
3987
+ const legacy = packages.some((pkg) => registry.has(packageKey(pkg)) && registry.get(packageKey(pkg)));
3988
+ state = {
3989
+ schemaVersion: 1,
3990
+ writer: "",
3991
+ repository,
3992
+ candidates,
3993
+ packages,
3994
+ accepted: packages.filter((pkg) => registry.get(packageKey(pkg))).map(({ name, version }) => ({
3995
+ name,
3996
+ version
3997
+ })),
3998
+ npm: "pending",
3999
+ metadata: [],
4000
+ complete: false,
4001
+ hooks: Object.fromEntries((options.config?.hooks?.afterPublish ?? []).map((hook) => [hook.script, legacy ? "running" : "pending"]))
4002
+ };
4003
+ }
4004
+ const scripts = (options.config?.hooks?.afterPublish ?? []).map((hook) => hook.script);
4005
+ if (new Set(scripts).size !== scripts.length || JSON.stringify(Object.keys(state.hooks).sort()) !== JSON.stringify([...scripts].sort())) throw new ReleaseCommandError("afterPublish scripts must be unique and match the persisted release; restore the original hook configuration");
4006
+ for (const pkg of state.packages) {
4007
+ await verifySource(pkg, pkg.target, options);
4008
+ const target = tags.get(packageKey(pkg));
4009
+ if (target && target !== pkg.target) throw new ReleaseCommandError(`Tag target conflict for ${packageKey(pkg)}`);
4010
+ }
4011
+ if (options.dryRun ?? env["REPO_RELEASE_DRY_RUN"] === "true") {
4012
+ logger.info(JSON.stringify({
4013
+ key,
4014
+ packages: state.packages,
4015
+ npm: state.npm,
4016
+ tags: state.packages.filter((pkg) => !tags.get(packageKey(pkg))).map(packageKey),
4017
+ metadata: state.packages.filter((pkg) => !releases.has(packageKey(pkg))).map(packageKey),
4018
+ hooks: state.hooks
4019
+ }, null, 2));
4020
+ return state.packages.map(({ name, version }) => ({
4021
+ name,
4022
+ version
4023
+ }));
4024
+ }
4025
+ state.writer = randomUUID();
4026
+ state.complete = false;
4027
+ const save = async () => {
4028
+ await writeFile(path.join(options.cwd, "repoctl-release-progress.json"), `${JSON.stringify(state, null, 2)}\n`);
4029
+ revision = await github.writeReleaseState(key, state, revision);
4030
+ };
4031
+ await save();
4032
+ const packages = state.packages.map(({ name, version }) => ({
4033
+ name,
4034
+ version
4035
+ }));
4036
+ const confirmed = new PublishState(packages);
4037
+ confirmed.accept(state.accepted);
4038
+ for (const pkg of packages) if (registry.get(packageKey(pkg))) confirmed.confirm(pkg);
4039
+ if (state.npm === "running") await confirmVisibility(confirmed, options, packages);
4040
+ else if (confirmed.unconfirmed(state.accepted).length) await confirmVisibility(confirmed, options, state.accepted);
4041
+ const missing = packages.filter((pkg) => !confirmed.acceptedPackages.some((item) => packageKey(item) === packageKey(pkg)));
4042
+ if (missing.length) {
4043
+ runReleaseHooks("beforePublish", options);
4044
+ await clearPublishSummary(options.cwd);
4045
+ state.npm = "running";
4046
+ state.complete = false;
4047
+ await save();
4048
+ try {
4049
+ await publishWithRetry([
4050
+ "publish",
4051
+ "-r",
4052
+ "--report-summary",
4053
+ "--provenance",
4054
+ "--no-git-checks",
4055
+ "--tag",
4056
+ distTag,
4057
+ ...missing.flatMap((pkg) => ["--filter", pkg.name])
4058
+ ], options, packages, true, {
4059
+ accepted: confirmed.acceptedPackages,
4060
+ save: async (accepted) => {
4061
+ state.accepted = accepted;
4062
+ await save();
4063
+ }
4064
+ });
4065
+ } catch (error) {
4066
+ state.npm = "failed";
4067
+ await save();
4068
+ throw error;
4069
+ }
4070
+ }
4071
+ for (const pkg of packages) {
4072
+ const remote = await inspectRegistry(pkg, options);
4073
+ if (!remote || remote["dist-tags"]?.[distTag] !== pkg.version) throw new ReleaseCommandError(`npm version/dist-tag ${distTag} is not confirmed for ${packageKey(pkg)}; release remains incomplete`);
4074
+ }
4075
+ state.npm = "complete";
4076
+ state.accepted = packages;
4077
+ await save();
4078
+ await writeFile(path.join(options.cwd, "pnpm-publish-summary.json"), JSON.stringify({ publishedPackages: packages }));
4079
+ for (const pkg of state.packages) {
4080
+ await github.ensureTag({
4081
+ tag: packageKey(pkg),
4082
+ target: pkg.target
4083
+ });
4084
+ const release = releases.get(packageKey(pkg));
4085
+ if (!release || release.draft || Boolean(release.prerelease) !== (distTag !== "latest")) await publishMetadata([pkg], {
4086
+ ...options,
4087
+ env: {
4088
+ ...env,
4089
+ GITHUB_SHA: pkg.target
4090
+ }
4091
+ }, distTag !== "latest");
4092
+ if (!state.metadata.includes(packageKey(pkg))) {
4093
+ state.metadata.push(packageKey(pkg));
4094
+ await save();
4095
+ }
4096
+ }
4097
+ await finishHooks(state, save, options);
4098
+ state.complete = true;
4099
+ await save();
4100
+ logger.success(`Release lifecycle complete: ${packages.map(packageKey).join(", ")}`);
4101
+ return packages;
4102
+ }
4103
+ //#endregion
4104
+ //#region src/commands/release/preparation/guard.ts
4105
+ /** A prepared version belongs to its original source, even before npm accepts it. */
4106
+ async function assertPreviousReleaseComplete(options, distTag = "latest") {
4107
+ const ledger = await readLedger(options.cwd);
4108
+ const candidates = await getPublishCandidates(options.cwd);
4109
+ const workspace = await getWorkspacePackages(options.cwd);
4110
+ const prepared = [];
4111
+ for (const pkg of candidates) {
4112
+ if (ledger[packageKey(pkg)]) {
4113
+ prepared.push(pkg);
4114
+ continue;
4115
+ }
4116
+ const directory = workspace.find((item) => item.manifest.name === pkg.name).rootDir;
4117
+ try {
4118
+ if (readVersionSection(await readFile(path.join(directory, "CHANGELOG.md"), "utf8"), pkg.version)?.previousVersion) prepared.push(pkg);
4119
+ } catch (error) {
4120
+ if (error.code !== "ENOENT") throw error;
4121
+ }
4122
+ }
4123
+ if (!prepared.length) return;
4124
+ const github = options.github;
4125
+ const releases = github?.listReleases ? await github.listReleases() : void 0;
4126
+ const repository = getReleaseEnv(options)["GITHUB_REPOSITORY"];
4127
+ const sources = /* @__PURE__ */ new Map();
4128
+ const cohorts = /* @__PURE__ */ new Map();
4129
+ for (const pkg of prepared) {
4130
+ const source = await findVersionCommit(pkg, options);
4131
+ sources.set(packageKey(pkg), source);
4132
+ cohorts.set(source, [...cohorts.get(source) ?? [], pkg]);
4133
+ }
4134
+ const unfinished = /* @__PURE__ */ new Set();
4135
+ if (repository && github?.readReleaseState) for (const group of [candidates, ...cohorts.values()]) {
4136
+ const key = releaseStateKey(repository, distTag, group);
4137
+ const checkpoint = await github.readReleaseState(key);
4138
+ if (checkpoint && (!checkpoint.state.complete || checkpoint.state.schemaVersion !== 1)) group.forEach((pkg) => unfinished.add(packageKey(pkg)));
4139
+ }
4140
+ const blocked = [];
4141
+ for (const pkg of prepared) {
4142
+ const published = await inspectRegistry(pkg, options);
4143
+ const release = releases?.find((item) => item.tag_name === packageKey(pkg));
4144
+ const tag = github?.readTagTarget ? await github.readTagTarget(packageKey(pkg)) : void 0;
4145
+ if (!published || unfinished.has(packageKey(pkg)) || releases && (!release || release.draft || Boolean(release.prerelease) !== (distTag !== "latest")) || github?.readTagTarget && (!tag || published.gitHead && tag !== published.gitHead)) {
4146
+ const source = sources.get(packageKey(pkg));
4147
+ const recovery = distTag === "latest" ? `repo release ci --mode publish --source-sha ${source}` : `check out ${source} on ${distTag} and run repo release ci`;
4148
+ blocked.push(`${packageKey(pkg)} (source ${source}); recover with ${recovery}`);
4149
+ }
4150
+ }
4151
+ if (blocked.length) throw new ReleaseCommandError(`Prepared releases must finish before consuming new intents:\n${blocked.join("\n")}`);
4152
+ }
4153
+ //#endregion
4154
+ //#region src/commands/release/preparation/result.ts
4155
+ async function applyVersions(options) {
4156
+ const before = await readWorkspaceVersions(options.cwd);
4157
+ const output = capture("pnpm", [
4158
+ "version",
4159
+ "-r",
4160
+ "--no-git-checks",
4161
+ "--json"
4162
+ ], options);
4163
+ let data;
4164
+ try {
4165
+ data = JSON.parse(output);
4166
+ } catch {
4167
+ throw new ReleaseCommandError("pnpm version returned invalid JSON; no release PR will be pushed");
4168
+ }
4169
+ if (!Array.isArray(data)) throw new ReleaseCommandError("pnpm version must return an applied release array");
4170
+ const after = await readWorkspaceVersions(options.cwd);
4171
+ const names = /* @__PURE__ */ new Set();
4172
+ for (const item of data) {
4173
+ if (!item || typeof item.name !== "string" || names.has(item.name) || typeof item.currentVersion !== "string" || !semver.valid(item.currentVersion) || typeof item.newVersion !== "string" || !semver.valid(item.newVersion) || before.get(item.name) !== item.currentVersion || after.get(item.name) !== item.newVersion) throw new ReleaseCommandError("pnpm version result does not match workspace manifests");
4174
+ names.add(item.name);
4175
+ }
4176
+ for (const [name, version] of after) if (before.get(name) !== version && !names.has(name)) throw new ReleaseCommandError(`pnpm version omitted changed package ${name}`);
4177
+ return data;
4178
+ }
4179
+ //#endregion
3516
4180
  //#region src/commands/release/types.ts
3517
4181
  const prereleaseBranches$1 = /* @__PURE__ */ new Set([
3518
4182
  "alpha",
@@ -3522,26 +4186,35 @@ const prereleaseBranches$1 = /* @__PURE__ */ new Set([
3522
4186
  ]);
3523
4187
  //#endregion
3524
4188
  //#region src/commands/release/prerelease.ts
3525
- async function releasePrerelease(options) {
4189
+ async function releasePrerelease(options, publish) {
3526
4190
  const branch = resolveBranch(options);
3527
4191
  if (!prereleaseBranches$1.has(branch)) throw new ReleaseCommandError(`repo release pre is only allowed on alpha, beta, rc, or next branches, got ${branch}`);
3528
4192
  await assertLaneAssignments(branch, options);
3529
- if (!await hasPendingIntents(options.cwd)) return;
4193
+ if (!await hasPendingIntents(options.cwd)) {
4194
+ if (publish) await runQualityScripts(options);
4195
+ return publish?.();
4196
+ }
4197
+ await assertPreviousReleaseComplete(options, branch);
3530
4198
  runReleaseHooks("beforeVersion", options);
3531
4199
  await runQualityScripts(options);
3532
- run("pnpm", [
3533
- "version",
3534
- "-r",
3535
- "--no-git-checks"
3536
- ], options);
4200
+ const releases = await applyVersions(options);
3537
4201
  runReleaseHooks("afterVersion", options);
3538
- if (!hasGitChanges(options)) return;
4202
+ if (!releases.length) return;
4203
+ if (!hasGitChanges(options)) throw new ReleaseCommandError("pnpm reported releases without file changes");
3539
4204
  run("git", ["add", "-A"], options);
3540
4205
  run("git", [
3541
4206
  "commit",
3542
4207
  "-m",
3543
4208
  `chore(release): ${branch} [skip ci]`
3544
4209
  ], options);
4210
+ if (publish) {
4211
+ run("git", [
4212
+ "push",
4213
+ "origin",
4214
+ `HEAD:${branch}`
4215
+ ], options);
4216
+ return publish();
4217
+ }
3545
4218
  runReleaseHooks("beforePublish", options);
3546
4219
  await clearPublishSummary(options.cwd);
3547
4220
  await publishWithRetry([
@@ -3570,39 +4243,31 @@ async function exitPrerelease(options) {
3570
4243
  }
3571
4244
  //#endregion
3572
4245
  //#region src/commands/release/reconcile.ts
3573
- function remoteTagExists$1(tag, options) {
3574
- return (options.spawn ?? spawnSync)("git", [
4246
+ function remoteTagTarget(tag, options) {
4247
+ const result = (options.spawn ?? spawnSync)("git", [
3575
4248
  "ls-remote",
3576
4249
  "--exit-code",
3577
- "--refs",
3578
4250
  "origin",
3579
- `refs/tags/${tag}`
3580
- ], {
3581
- cwd: options.cwd,
3582
- encoding: "utf8",
3583
- shell: false,
3584
- stdio: "ignore"
3585
- }).status === 0;
3586
- }
3587
- function resolveTarget$1(options) {
3588
- return getReleaseEnv(options)["GITHUB_SHA"]?.trim() || capture("git", ["rev-parse", "HEAD"], options);
3589
- }
3590
- function isPublished(pkg, options) {
3591
- const result = (options.spawn ?? spawnSync)("npm", [
3592
- "view",
3593
- `${pkg.name}@${pkg.version}`,
3594
- "version"
4251
+ `refs/tags/${tag}`,
4252
+ `refs/tags/${tag}^{}`
3595
4253
  ], {
3596
4254
  cwd: options.cwd,
4255
+ env: getReleaseEnv(options),
3597
4256
  encoding: "utf8",
3598
4257
  shell: false,
3599
4258
  stdio: [
3600
4259
  "ignore",
3601
4260
  "pipe",
3602
- "ignore"
3603
- ]
4261
+ "pipe"
4262
+ ],
4263
+ timeout: 1e4
3604
4264
  });
3605
- return result.status === 0 && String(result.stdout ?? "").trim() === pkg.version;
4265
+ if (result.status === 2) return;
4266
+ if (result.status !== 0) throw new ReleaseCommandError(`Cannot query remote tag ${tag}; state is unknown`);
4267
+ const refs = String(result.stdout ?? "").trim().split("\n");
4268
+ const sha = (refs.find((ref) => ref.endsWith("^{}")) ?? refs[0])?.split(/\s+/)[0];
4269
+ if (!sha || !/^[a-f0-9]{40}$/.test(sha)) throw new ReleaseCommandError(`Invalid remote tag response for ${tag}`);
4270
+ return sha;
3606
4271
  }
3607
4272
  async function reconcileRelease(options) {
3608
4273
  const github = options.github ?? new GitHubClient();
@@ -3612,7 +4277,7 @@ async function reconcileRelease(options) {
3612
4277
  const packages = (await getWorkspacePackages(options.cwd)).flatMap(({ manifest }) => typeof manifest.name === "string" && typeof manifest.version === "string" ? [{
3613
4278
  name: manifest.name,
3614
4279
  version: manifest.version
3615
- }] : []).filter((pkg) => (!options.packageName || pkg.name === options.packageName) && (!options.packageVersion || pkg.version === options.packageVersion)).filter((pkg) => isPublished(pkg, options));
4280
+ }] : []).filter((pkg) => (!options.packageName || pkg.name === options.packageName) && (!options.packageVersion || pkg.version === options.packageVersion));
3616
4281
  const env = getReleaseEnv(options);
3617
4282
  const metadata = {};
3618
4283
  if (env["GITHUB_REPOSITORY"]) metadata.repository = env["GITHUB_REPOSITORY"];
@@ -3620,7 +4285,13 @@ async function reconcileRelease(options) {
3620
4285
  const document = await buildReleaseNoteDocument(options.cwd, void 0, metadata, new Set(packages.map((pkg) => pkg.name)));
3621
4286
  const repaired = [];
3622
4287
  const pending = [];
4288
+ const publishedPackages = [];
3623
4289
  for (const pkg of packages) {
4290
+ const published = await inspectRegistry(pkg, options);
4291
+ if (!published) continue;
4292
+ publishedPackages.push(pkg);
4293
+ const target = published.gitHead ?? env["REPO_RELEASE_SOURCE_SHA"] ?? "";
4294
+ await verifySource(pkg, target, options);
3624
4295
  const tag = `${pkg.name}@${pkg.version}`;
3625
4296
  const release = existing.get(tag);
3626
4297
  const body = renderGitHubRelease({
@@ -3629,18 +4300,20 @@ async function reconcileRelease(options) {
3629
4300
  entries: document.entries.filter((entry) => entry.packageName === pkg.name && entry.version === pkg.version),
3630
4301
  compareUrls: document.compareUrls.filter((url) => url.includes(encodeURIComponent(`${pkg.name}@`)))
3631
4302
  });
3632
- const needsTag = !remoteTagExists$1(tag, options);
4303
+ const tagTarget = github.readTagTarget ? await github.readTagTarget(tag) : remoteTagTarget(tag, options);
4304
+ if (tagTarget && tagTarget !== target) throw new ReleaseCommandError(`Tag target conflict for ${tag}`);
4305
+ const needsTag = !tagTarget;
3633
4306
  const needsRelease = !release || release.name !== tag || release.body !== body;
3634
4307
  if (!needsTag && !needsRelease) continue;
3635
4308
  pending.push(tag);
3636
4309
  if (options.dryRun) continue;
3637
4310
  if (needsTag && github.ensureTag) await github.ensureTag({
3638
4311
  tag,
3639
- target: resolveTarget$1(options)
4312
+ target
3640
4313
  });
3641
4314
  await github.ensureRelease({
3642
4315
  tag,
3643
- target: resolveTarget$1(options),
4316
+ target,
3644
4317
  name: tag,
3645
4318
  body
3646
4319
  });
@@ -3649,32 +4322,166 @@ async function reconcileRelease(options) {
3649
4322
  return {
3650
4323
  repaired,
3651
4324
  pending,
3652
- skipped: packages.filter((pkg) => !pending.includes(`${pkg.name}@${pkg.version}`)).map((pkg) => `${pkg.name}@${pkg.version}`)
4325
+ skipped: publishedPackages.filter((pkg) => !pending.includes(`${pkg.name}@${pkg.version}`)).map((pkg) => `${pkg.name}@${pkg.version}`)
3653
4326
  };
3654
4327
  }
3655
4328
  //#endregion
4329
+ //#region src/commands/release/recovery/candidates.ts
4330
+ /** Dependency propagation can change manifests without adding ledger entries. */
4331
+ async function readSourceCandidates(options, source) {
4332
+ const ledger = await readLedger(options.cwd);
4333
+ const previous = capture("git", [
4334
+ "ls-tree",
4335
+ `${source}^`,
4336
+ "--",
4337
+ ".changeset/ledger.yaml"
4338
+ ], options) ? parseLedger(capture("git", ["show", `${source}^:.changeset/ledger.yaml`], options)) : {};
4339
+ const root = await realpath(options.cwd);
4340
+ const candidates = [];
4341
+ for (const pkg of await getWorkspacePackages(options.cwd)) {
4342
+ const { name, version } = pkg.manifest;
4343
+ if (!name || !version) continue;
4344
+ const file = path.relative(root, pkg.pkgJsonPath);
4345
+ const before = capture("git", [
4346
+ "ls-tree",
4347
+ `${source}^`,
4348
+ "--",
4349
+ file
4350
+ ], options) ? JSON.parse(capture("git", ["show", `${source}^:${file}`], options)) : void 0;
4351
+ const key = `${name}@${version}`;
4352
+ if (before?.name !== name || before.version !== version || ledger[key] && !previous[key]) candidates.push({
4353
+ name,
4354
+ version
4355
+ });
4356
+ }
4357
+ return candidates;
4358
+ }
4359
+ //#endregion
4360
+ //#region src/commands/release/recovery/source.ts
4361
+ /** Run current tooling against the original source, never today's package contents. */
4362
+ async function recoverSource(options, source) {
4363
+ if (!/^[a-f0-9]{40}$/.test(source)) throw new ReleaseCommandError("source-sha must be a full lowercase commit SHA");
4364
+ const mode = options.mode ?? getReleaseEnv(options)["REPO_RELEASE_MODE"] ?? "auto";
4365
+ if (!["publish", "publish-unpublished"].includes(mode)) throw new ReleaseCommandError("source-sha requires publish or publish-unpublished mode");
4366
+ if (capture("git", ["rev-parse", "--is-shallow-repository"], options) !== "false") throw new ReleaseCommandError("Source recovery requires full Git history");
4367
+ run("git", [
4368
+ "merge-base",
4369
+ "--is-ancestor",
4370
+ source,
4371
+ "origin/main"
4372
+ ], options);
4373
+ const origin = capture("git", [
4374
+ "remote",
4375
+ "get-url",
4376
+ "origin"
4377
+ ], options);
4378
+ const root = await mkdtemp(path.join(tmpdir(), "repoctl-release-source-"));
4379
+ const cwd = path.join(root, "source");
4380
+ try {
4381
+ run("git", [
4382
+ "clone",
4383
+ "--shared",
4384
+ "--no-checkout",
4385
+ options.cwd,
4386
+ cwd
4387
+ ], options);
4388
+ const env = {
4389
+ ...getReleaseEnv(options),
4390
+ REPO_RELEASE_SOURCE_SHA: source
4391
+ };
4392
+ let recovery = {
4393
+ ...options,
4394
+ cwd,
4395
+ branch: "main",
4396
+ env
4397
+ };
4398
+ run("git", [
4399
+ "remote",
4400
+ "set-url",
4401
+ "origin",
4402
+ origin
4403
+ ], recovery);
4404
+ run("git", [
4405
+ "checkout",
4406
+ "--detach",
4407
+ source
4408
+ ], recovery);
4409
+ clearWorkspaceCache();
4410
+ const workspaceCandidates = await getPublishCandidates(cwd);
4411
+ const candidates = await readSourceCandidates(recovery, source);
4412
+ if (!candidates.length) throw new ReleaseCommandError("Source commit introduces no prepared release versions");
4413
+ const name = options.packageName ?? env["REPO_RELEASE_PACKAGE"];
4414
+ const version = options.packageVersion ?? env["REPO_RELEASE_VERSION"];
4415
+ if ((name || version) && !candidates.some((pkg) => pkg.name === name && pkg.version === version)) throw new ReleaseCommandError("Requested package/version is not part of the source release");
4416
+ if (await hasPendingIntents(cwd)) throw new ReleaseCommandError("Source contains unconsumed release requests; select the merged version commit");
4417
+ const github = resolveGitHub(options);
4418
+ let selected = candidates;
4419
+ const repository = env["GITHUB_REPOSITORY"];
4420
+ if (repository && github.readReleaseState) {
4421
+ const checkpoint = await github.readReleaseState(releaseStateKey(repository, "latest", workspaceCandidates));
4422
+ if (checkpoint) {
4423
+ if (checkpoint.state.packages.some((pkg) => pkg.target !== source || !candidates.some((item) => packageKey(item) === packageKey(pkg)))) throw new ReleaseCommandError("Existing checkpoint includes a different source release; recover its original candidate set");
4424
+ selected = workspaceCandidates;
4425
+ }
4426
+ }
4427
+ if (!(options.dryRun ?? env["REPO_RELEASE_DRY_RUN"] === "true")) {
4428
+ run("pnpm", ["install", "--frozen-lockfile"], recovery);
4429
+ const config = await resolveCommandConfig("release", cwd);
4430
+ recovery = {
4431
+ ...recovery,
4432
+ config: config ?? {}
4433
+ };
4434
+ await runQualityScripts(recovery);
4435
+ } else recovery = {
4436
+ ...recovery,
4437
+ dryRun: true
4438
+ };
4439
+ return await publishLifecycle({
4440
+ ...recovery,
4441
+ github
4442
+ }, selected);
4443
+ } finally {
4444
+ for (const file of [
4445
+ "repoctl-publish-progress.json",
4446
+ "repoctl-release-progress.json",
4447
+ "pnpm-publish-summary.json"
4448
+ ]) await copyFile(path.join(cwd, file), path.join(options.cwd, file)).catch((error) => {
4449
+ if (error.code !== "ENOENT") throw error;
4450
+ });
4451
+ clearWorkspaceCache();
4452
+ await rm(root, {
4453
+ recursive: true,
4454
+ force: true
4455
+ });
4456
+ }
4457
+ }
4458
+ //#endregion
3656
4459
  //#region src/commands/release/stable.ts
3657
- async function prepareStable(options) {
4460
+ async function prepareStableReleases(options) {
3658
4461
  const branch = resolveBranch(options);
3659
4462
  if (branch !== "main") throw new ReleaseCommandError(`repo release stable prepare is only allowed on main, got ${branch}`);
3660
4463
  await assertStableLaneAssignments(options);
3661
- if (!await hasPendingIntents(options.cwd)) return false;
4464
+ if (!await hasPendingIntents(options.cwd)) return [];
4465
+ await assertPreviousReleaseComplete(options);
3662
4466
  runReleaseHooks("beforeVersion", options);
3663
4467
  await runQualityScripts(options);
3664
- run("pnpm", [
3665
- "version",
3666
- "-r",
3667
- "--no-git-checks"
3668
- ], options);
4468
+ const releases = await applyVersions(options);
3669
4469
  runReleaseHooks("afterVersion", options);
3670
- return hasGitChanges(options);
4470
+ if (releases.length && !hasGitChanges(options)) throw new ReleaseCommandError("pnpm reported releases without file changes");
4471
+ return releases;
3671
4472
  }
3672
- async function publishStable(options) {
4473
+ async function prepareStable(options) {
4474
+ return (await prepareStableReleases(options)).length > 0;
4475
+ }
4476
+ async function assertStablePublish(options, quality = true) {
3673
4477
  const branch = resolveBranch(options);
3674
4478
  if (branch !== "main") throw new ReleaseCommandError(`repo release stable publish is only allowed on main, got ${branch}`);
3675
4479
  await assertStableLaneAssignments(options);
3676
4480
  if (await hasPendingIntents(options.cwd)) throw new ReleaseCommandError("stable publish found unconsumed change intents; prepare and merge the Release PR before publishing");
3677
- await runQualityScripts(options);
4481
+ if (quality) await runQualityScripts(options);
4482
+ }
4483
+ async function publishStable(options) {
4484
+ await assertStablePublish(options);
3678
4485
  runReleaseHooks("beforePublish", options);
3679
4486
  await clearPublishSummary(options.cwd);
3680
4487
  await publishWithRetry([
@@ -3740,13 +4547,6 @@ function shouldRunRelease(context) {
3740
4547
  if (prereleaseBranches.has(context.branch)) return false;
3741
4548
  return isReleaseCommitMessage(context.commitMessage) || hasReleaseArtifactPair(context.changedFiles);
3742
4549
  }
3743
- async function readPendingChangesetFiles(cwd) {
3744
- try {
3745
- return (await readdir(path.join(cwd, ".changeset"), { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md").map((entry) => `.changeset/${entry.name}`);
3746
- } catch {
3747
- return [];
3748
- }
3749
- }
3750
4550
  function readGitOutput(options, args) {
3751
4551
  try {
3752
4552
  return capture("git", args, options);
@@ -3782,7 +4582,7 @@ async function readReleaseTriggerContext(options) {
3782
4582
  return {
3783
4583
  eventName,
3784
4584
  branch,
3785
- pendingChangesetFiles: await readPendingChangesetFiles(options.cwd),
4585
+ pendingChangesetFiles: await readPendingIntents(options.cwd),
3786
4586
  changedFiles: await readChangedFiles(options),
3787
4587
  commitMessage: readGitOutput(options, [
3788
4588
  "log",
@@ -3795,129 +4595,35 @@ async function readReleaseTriggerContext(options) {
3795
4595
  //#endregion
3796
4596
  //#region src/commands/release/ci.ts
3797
4597
  const releaseBranch = "release/pnpm-version";
3798
- function gitRefExists(ref, options) {
3799
- return (options.spawn ?? spawnSync)("git", [
3800
- "rev-parse",
3801
- "--verify",
3802
- "--quiet",
3803
- ref
3804
- ], {
3805
- cwd: options.cwd,
3806
- encoding: "utf8",
3807
- shell: false,
3808
- stdio: "ignore"
3809
- }).status === 0;
3810
- }
3811
- function remoteTagExists(tag, options) {
3812
- return (options.spawn ?? spawnSync)("git", [
3813
- "ls-remote",
3814
- "--exit-code",
3815
- "--refs",
3816
- "origin",
3817
- `refs/tags/${tag}`
3818
- ], {
3819
- cwd: options.cwd,
3820
- encoding: "utf8",
3821
- shell: false,
3822
- stdio: "ignore"
3823
- }).status === 0;
3824
- }
3825
- function resolveGitHub(options) {
3826
- return options.github ?? new GitHubClient();
3827
- }
3828
- function resolveTarget(options) {
3829
- return getReleaseEnv(options)["GITHUB_SHA"]?.trim() || capture("git", ["rev-parse", "HEAD"], options);
3830
- }
3831
- function resolveReleaseLocale(options) {
3832
- return resolveRepoctlLocale({ env: getReleaseEnv(options) });
3833
- }
3834
- function formatPublishedPackageSummary(packages) {
3835
- return ["Published packages:", ...packages.length ? packages.map((pkg) => ` - ${pkg.name}@${pkg.version}`) : [" (none)"]].join("\n");
3836
- }
3837
- async function publishMetadata(packages, options, prerelease = false) {
3838
- if (!packages.length) {
3839
- logger.success(formatPublishedPackageSummary(packages));
3840
- return;
3841
- }
4598
+ async function createReleasePullRequest(options) {
4599
+ const branch = resolveBranch(options);
4600
+ if (branch !== "main") throw new ReleaseCommandError(`repo release stable prepare is only allowed on main, got ${branch}`);
4601
+ const sourceCommits = await readPendingIntentCommits(options);
3842
4602
  const github = resolveGitHub(options);
3843
- const target = resolveTarget(options);
4603
+ const releases = await prepareStableReleases({
4604
+ ...options,
4605
+ github
4606
+ });
4607
+ if (!releases.length) return false;
3844
4608
  const releaseEnv = getReleaseEnv(options);
3845
- let releaseContributors = [];
3846
- if (github.readReleasePullRequestContributors) try {
3847
- releaseContributors = await github.readReleasePullRequestContributors(target);
3848
- } catch (error) {
3849
- const message = error instanceof Error ? error.message : String(error);
3850
- logger.warn(`GitHub release PR contributor lookup skipped: ${message}`);
3851
- }
3852
4609
  const metadata = {
3853
4610
  locale: resolveReleaseLocale(options),
3854
- ...releaseContributors.length ? { contributors: releaseContributors } : {},
4611
+ commits: sourceCommits,
3855
4612
  ...releaseEnv["GITHUB_REPOSITORY"] ? { repository: releaseEnv["GITHUB_REPOSITORY"] } : {},
3856
4613
  ...releaseEnv["GITHUB_SERVER_URL"] ? { serverUrl: releaseEnv["GITHUB_SERVER_URL"] } : {}
3857
4614
  };
3858
- const publishedPackageNames = new Set(packages.map((pkg) => pkg.name));
3859
- let noteDocument = await buildReleaseNoteDocument(options.cwd, void 0, metadata, publishedPackageNames);
3860
- if (github.enrichReleaseNote) noteDocument = await github.enrichReleaseNote(noteDocument);
3861
- for (const pkg of packages) {
3862
- const tag = `${pkg.name}@${pkg.version}`;
3863
- const body = renderGitHubRelease({
3864
- ...noteDocument,
3865
- packages: noteDocument.packages.filter((item) => item.name === pkg.name && item.version === pkg.version),
3866
- entries: noteDocument.entries.filter((entry) => entry.packageName === pkg.name && entry.version === pkg.version),
3867
- compareUrls: noteDocument.compareUrls.filter((url) => url.includes(encodeURIComponent(`${pkg.name}@`)))
3868
- }, metadata);
3869
- if (github.ensureTag) {
3870
- await github.ensureTag({
3871
- tag,
3872
- target
3873
- });
3874
- await github.ensureRelease({
3875
- tag,
3876
- target,
3877
- prerelease,
3878
- name: tag,
3879
- body
3880
- });
3881
- continue;
4615
+ const names = new Set(releases.map((release) => release.name));
4616
+ const previousVersions = new Map(releases.filter((release) => release.currentVersion !== release.newVersion).map((release) => [release.name, release.currentVersion]));
4617
+ let noteDocument = await buildReleaseNoteDocument(options.cwd, previousVersions, metadata, names);
4618
+ for (const release of releases) {
4619
+ const pkg = noteDocument.packages.find((pkg) => pkg.name === release.name && pkg.version === release.newVersion);
4620
+ if (!pkg || !noteDocument.entries.some((entry) => entry.packageName === pkg.name)) throw new ReleaseCommandError(`Missing release notes for ${release.name}@${release.newVersion}; no PR pushed`);
4621
+ if (release.currentVersion === release.newVersion) {
4622
+ delete pkg.previousVersion;
4623
+ delete pkg.previousNpmUrl;
3882
4624
  }
3883
- if (remoteTagExists(tag, options)) {
3884
- await github.ensureRelease({
3885
- tag,
3886
- target,
3887
- prerelease,
3888
- name: tag,
3889
- body
3890
- });
3891
- continue;
3892
- }
3893
- if (!gitRefExists(tag, options)) run("git", [
3894
- "tag",
3895
- "-a",
3896
- tag,
3897
- "-m",
3898
- tag
3899
- ], options);
3900
- run("git", [
3901
- "push",
3902
- "origin",
3903
- `refs/tags/${tag}`
3904
- ], options);
3905
- await github.ensureRelease({
3906
- tag,
3907
- target,
3908
- prerelease,
3909
- name: tag,
3910
- body
3911
- });
3912
4625
  }
3913
- logger.success(formatPublishedPackageSummary(packages));
3914
- }
3915
- async function createReleasePullRequest(options) {
3916
- const branch = resolveBranch(options);
3917
- if (branch !== "main") throw new ReleaseCommandError(`repo release stable prepare is only allowed on main, got ${branch}`);
3918
- const previousVersions = await readWorkspaceVersions(options.cwd);
3919
- const sourceCommits = await readPendingIntentCommits(options);
3920
- if (!await prepareStable(options)) return false;
4626
+ if (github.enrichReleaseNote) noteDocument = await github.enrichReleaseNote(noteDocument);
3921
4627
  run("git", [
3922
4628
  "config",
3923
4629
  "user.name",
@@ -3945,16 +4651,6 @@ async function createReleasePullRequest(options) {
3945
4651
  "origin",
3946
4652
  `HEAD:${releaseBranch}`
3947
4653
  ], options);
3948
- const github = resolveGitHub(options);
3949
- const releaseEnv = getReleaseEnv(options);
3950
- const metadata = {
3951
- locale: resolveReleaseLocale(options),
3952
- commits: sourceCommits,
3953
- ...releaseEnv["GITHUB_REPOSITORY"] ? { repository: releaseEnv["GITHUB_REPOSITORY"] } : {},
3954
- ...releaseEnv["GITHUB_SERVER_URL"] ? { serverUrl: releaseEnv["GITHUB_SERVER_URL"] } : {}
3955
- };
3956
- let noteDocument = await buildReleaseNoteDocument(options.cwd, previousVersions, metadata);
3957
- if (github.enrichReleaseNote) noteDocument = await github.enrichReleaseNote(noteDocument);
3958
4654
  await github.ensurePullRequest({
3959
4655
  head: releaseBranch,
3960
4656
  base: "main",
@@ -3982,6 +4678,14 @@ async function recoverUnpublished(options) {
3982
4678
  ], options);
3983
4679
  if (actualVersion !== packageVersion) throw new ReleaseCommandError(`expected ${packageName}@${packageVersion} in the workspace, found ${actualVersion}`);
3984
4680
  await runQualityScripts(options);
4681
+ const github = resolveGitHub(options);
4682
+ if (github.readReleaseState && github.writeReleaseState) return publishLifecycle({
4683
+ ...options,
4684
+ github
4685
+ }, [{
4686
+ name: packageName,
4687
+ version: packageVersion
4688
+ }]);
3985
4689
  runReleaseHooks("beforePublish", options);
3986
4690
  await clearPublishSummary(options.cwd);
3987
4691
  await publishWithRetry([
@@ -4002,22 +4706,36 @@ async function recoverUnpublished(options) {
4002
4706
  return packages;
4003
4707
  }
4004
4708
  function resolveMode(options) {
4005
- const requested = options.mode || getReleaseEnv(options)["REPO_RELEASE_MODE"]?.trim();
4709
+ const requested = options.mode && options.mode !== "auto" ? options.mode : getReleaseEnv(options)["REPO_RELEASE_MODE"]?.trim();
4006
4710
  if (requested && requested !== "auto") return requested;
4007
4711
  return "auto";
4008
4712
  }
4713
+ async function publishStableCi(options) {
4714
+ const github = resolveGitHub(options);
4715
+ if (github.readReleaseState && github.writeReleaseState) {
4716
+ await assertStablePublish(options, !(options.dryRun ?? getReleaseEnv(options)["REPO_RELEASE_DRY_RUN"] === "true"));
4717
+ return publishLifecycle({
4718
+ ...options,
4719
+ github
4720
+ });
4721
+ }
4722
+ const packages = await publishStable(options);
4723
+ await publishMetadata(packages, options);
4724
+ runAfterPublishHooks(packages, options);
4725
+ return packages;
4726
+ }
4009
4727
  async function releaseCi(options) {
4010
4728
  const mode = resolveMode(options);
4729
+ const source = options.sourceSha ?? getReleaseEnv(options)["REPO_RELEASE_RECOVERY_SOURCE_SHA"]?.trim();
4730
+ if (source) return recoverSource({
4731
+ ...options,
4732
+ mode
4733
+ }, source);
4011
4734
  if (mode === "prepare") {
4012
4735
  await createReleasePullRequest(options);
4013
4736
  return;
4014
4737
  }
4015
- if (mode === "publish") {
4016
- const packages = await publishStable(options);
4017
- await publishMetadata(packages, options);
4018
- runAfterPublishHooks(packages, options);
4019
- return packages;
4020
- }
4738
+ if (mode === "publish") return publishStableCi(options);
4021
4739
  if (mode === "publish-unpublished") return recoverUnpublished(options);
4022
4740
  if (mode === "reconcile") return reconcileRelease({
4023
4741
  ...options,
@@ -4033,6 +4751,27 @@ async function releaseCi(options) {
4033
4751
  }
4034
4752
  const branch = resolveBranch(options);
4035
4753
  if (prereleaseBranches$1.has(branch)) {
4754
+ const github = resolveGitHub(options);
4755
+ if (github.readReleaseState && github.writeReleaseState) {
4756
+ if (options.dryRun ?? getReleaseEnv(options)["REPO_RELEASE_DRY_RUN"] === "true") {
4757
+ if (await hasPendingIntents(options.cwd)) throw new ReleaseCommandError("Prerelease dry-run requires an already prepared version commit");
4758
+ return publishLifecycle({
4759
+ ...options,
4760
+ github
4761
+ }, void 0, branch);
4762
+ }
4763
+ return releasePrerelease({
4764
+ ...options,
4765
+ github
4766
+ }, () => publishLifecycle({
4767
+ ...options,
4768
+ github,
4769
+ env: {
4770
+ ...getReleaseEnv(options),
4771
+ GITHUB_SHA: capture("git", ["rev-parse", "HEAD"], options)
4772
+ }
4773
+ }, void 0, branch));
4774
+ }
4036
4775
  const packages = await releasePrerelease(options);
4037
4776
  if (!packages) return;
4038
4777
  await publishMetadata(packages, options, true);
@@ -4044,10 +4783,7 @@ async function releaseCi(options) {
4044
4783
  await createReleasePullRequest(options);
4045
4784
  return;
4046
4785
  }
4047
- const packages = await publishStable(options);
4048
- await publishMetadata(packages, options);
4049
- runAfterPublishHooks(packages, options);
4050
- return packages;
4786
+ return publishStableCi(options);
4051
4787
  }
4052
4788
  //#endregion
4053
4789
  //#region src/commands/release/repair.ts
@@ -4933,4 +5669,4 @@ var commands_exports = /* @__PURE__ */ __exportAll({
4933
5669
  verifyStagedTypecheck: () => verifyStagedTypecheck
4934
5670
  });
4935
5671
  //#endregion
4936
- export { runRecommendedCheck as $, defaultTemplate as A, escapeStringRegexp as B, createContext as C, collectEnvSupportBundle as D, collectEnvSnapshot as E, inspectMonorepoConfig as F, isGitignoreFile as G, setByPath as H, cleanProjects as I, toWorkspaceGitignorePath as J, toPublishGitignorePath as K, getSkillTargetPaths as L, getTemplateMap as M, resolveCreateNewProjectPlan as N, runDoctor as O, templateMap as P, resolveRecommendedCheckPlan as Q, skillTargets as R, normalizeInitToolingTargets as S, collectEnvPaths as T, getFileHash as U, isMatch as V, isFileChanged as W, getKnownRepoCheckCommands as X, updateIssueTemplateConfig as Y, resolveFullWorkspaceCheckPlan as Z, parsePublishSummary as _, createReleasePullRequest as a, defaultAgenticBaseDir as at, initMetadata as b, prepareStable as c, loadAgenticTasks as ct, reconcileRelease as d, verifyCommitMsg as et, enterPrerelease as f, GitHubClient as g, GitHubApiError as h, repairReleaseNotes as i, createTimestampFolderName as it, getCreateChoices as j, createNewProject as k, publishStable as l, GitClient as lt, releasePrerelease as m, upgradeMonorepo as n, verifyPrePush as nt, recoverUnpublished as o, generateAgenticTemplate as ot, exitPrerelease as p, toWorkspaceAssetPath as q, checkTemplates as r, verifyStagedTypecheck as rt, releaseCi as s, generateAgenticTemplates as st, commands_exports as t, verifyPreCommit as tt, releaseStable as u, setVscodeBinaryMirror as v, collectEnvInfo as w, initTooling as x, init as y, syncSkills as z };
5672
+ export { runRecommendedCheck as $, defaultTemplate as A, escapeStringRegexp as B, createContext as C, collectEnvSupportBundle as D, collectEnvSnapshot as E, inspectMonorepoConfig as F, isGitignoreFile as G, setByPath as H, cleanProjects as I, toWorkspaceGitignorePath as J, toPublishGitignorePath as K, getSkillTargetPaths as L, getTemplateMap as M, resolveCreateNewProjectPlan as N, runDoctor as O, templateMap as P, resolveRecommendedCheckPlan as Q, skillTargets as R, normalizeInitToolingTargets as S, collectEnvPaths as T, getFileHash as U, isMatch as V, isFileChanged as W, getKnownRepoCheckCommands as X, updateIssueTemplateConfig as Y, resolveFullWorkspaceCheckPlan as Z, parsePublishSummary as _, createReleasePullRequest as a, defaultAgenticBaseDir as at, initMetadata as b, prepareStable as c, loadAgenticTasks as ct, reconcileRelease as d, verifyCommitMsg as et, enterPrerelease as f, GitHubApiError as g, GitHubClient as h, repairReleaseNotes as i, createTimestampFolderName as it, getCreateChoices as j, createNewProject as k, publishStable as l, GitClient as lt, releasePrerelease as m, upgradeMonorepo as n, verifyPrePush as nt, recoverUnpublished as o, generateAgenticTemplate as ot, exitPrerelease as p, toWorkspaceAssetPath as q, checkTemplates as r, verifyStagedTypecheck as rt, releaseCi as s, generateAgenticTemplates as st, commands_exports as t, verifyPreCommit as tt, releaseStable as u, setVscodeBinaryMirror as v, collectEnvInfo as w, initTooling as x, init as y, syncSkills as z };