@icebreakers/monorepo 5.5.7 → 5.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-DpfpqJWb.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-W9fwiyx8.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";
@@ -15,7 +15,7 @@ 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";
18
+ import crypto, { createHash, randomUUID } from "node:crypto";
19
19
  import os from "node:os";
20
20
  import pc from "picocolors";
21
21
  import { coerce, gte, minVersion, satisfies } from "semver";
@@ -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",
@@ -1933,21 +1933,21 @@ var package_default = {
1933
1933
  "@icebreakers/eslint-config": "workspace:*",
1934
1934
  "@icebreakers/monorepo": "workspace:*",
1935
1935
  "@icebreakers/stylelint-config": "workspace:*",
1936
- "@types/node": "^26.6.2",
1937
- "@vitest/coverage-v8": "~5.0.1",
1936
+ "@types/node": "^26.6.3",
1937
+ "@vitest/coverage-v8": "~5.0.2",
1938
1938
  "eslint": "^10.11.0",
1939
1939
  "execa": "^10.0.1",
1940
1940
  "husky": "^9.1.7",
1941
- "lint-staged": "^17.5.1",
1941
+ "lint-staged": "^17.6.0",
1942
1942
  "only-allow": "^1.2.2",
1943
1943
  "repoctl": "workspace:*",
1944
1944
  "stylelint": "^17.15.0",
1945
1945
  "tailwindcss": "^4.3.3",
1946
1946
  "tsd": "^0.33.0",
1947
1947
  "tsdown": "0.23.0",
1948
- "turbo": "^2.11.3",
1948
+ "turbo": "^2.11.5",
1949
1949
  "typescript": "^6.0.3",
1950
- "vitest": "~5.0.1",
1950
+ "vitest": "~5.0.2",
1951
1951
  "yaml": "^2.9.1"
1952
1952
  },
1953
1953
  publishConfig: {
@@ -2920,6 +2920,100 @@ function buildGitHubReleaseBodyFromChangelog(packageName, packageVersion, change
2920
2920
  }], metadata), metadata);
2921
2921
  }
2922
2922
  //#endregion
2923
+ //#region src/commands/release/workspace-protocol.ts
2924
+ const EXPECTED_WORKSPACE_SPEC = "workspace:*";
2925
+ const DEPENDENCY_SECTIONS = [
2926
+ "dependencies",
2927
+ "devDependencies",
2928
+ "optionalDependencies",
2929
+ "peerDependencies"
2930
+ ];
2931
+ function displayPath(workspaceDir, packagePath) {
2932
+ return path.relative(workspaceDir, packagePath).replaceAll("\\", "/");
2933
+ }
2934
+ function collectWorkspaceProtocolViolations(options) {
2935
+ const violations = [];
2936
+ for (const entry of options.packages) {
2937
+ if (entry.packageJson.private === true || typeof entry.packageJson.name !== "string") continue;
2938
+ for (const section of DEPENDENCY_SECTIONS) {
2939
+ const dependencies = entry.packageJson[section];
2940
+ if (!dependencies) continue;
2941
+ 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}`);
2942
+ }
2943
+ }
2944
+ return violations;
2945
+ }
2946
+ async function readPackageManifest(file) {
2947
+ return JSON.parse(await readFile(file, "utf8"));
2948
+ }
2949
+ async function assertWorkspaceDependencyProtocols(cwd) {
2950
+ const { workspaceDir, packages } = await getWorkspaceData(cwd, { ignorePrivatePackage: false });
2951
+ const manifests = await Promise.all(packages.map(async (pkg) => ({
2952
+ file: pkg.pkgJsonPath,
2953
+ packageJson: await readPackageManifest(pkg.pkgJsonPath)
2954
+ })));
2955
+ const violations = collectWorkspaceProtocolViolations({
2956
+ workspaceDir,
2957
+ packages: manifests,
2958
+ workspacePackageNames: new Set(manifests.map(({ packageJson }) => packageJson.name).filter((name) => typeof name === "string"))
2959
+ });
2960
+ if (violations.length > 0) throw new ReleaseCommandError([`Expected publishable workspace dependencies to use ${EXPECTED_WORKSPACE_SPEC}:`, ...violations.map((violation) => `- ${violation}`)].join("\n"));
2961
+ }
2962
+ //#endregion
2963
+ //#region src/commands/release/hooks.ts
2964
+ const defaultQualityScripts = [
2965
+ "build",
2966
+ "lint",
2967
+ "test"
2968
+ ];
2969
+ function validateScriptName(script) {
2970
+ const normalizedScript = script.trim();
2971
+ if (!normalizedScript) throw new ReleaseCommandError("release script name must not be empty");
2972
+ return normalizedScript;
2973
+ }
2974
+ function runScripts(scripts, options, extraEnv) {
2975
+ for (const script of scripts) run("pnpm", ["run", validateScriptName(script)], {
2976
+ ...options,
2977
+ ...extraEnv ? { env: {
2978
+ ...options.env ?? process.env,
2979
+ ...extraEnv
2980
+ } } : {}
2981
+ });
2982
+ }
2983
+ async function runQualityScripts(options) {
2984
+ await assertWorkspaceDependencyProtocols(options.cwd);
2985
+ runScripts(options.config?.qualityScripts ?? defaultQualityScripts, options);
2986
+ runScripts(options.config?.hooks?.verify ?? [], options);
2987
+ }
2988
+ function runReleaseHooks(phase, options) {
2989
+ runScripts(options.config?.hooks?.[phase] ?? [], options);
2990
+ }
2991
+ function runAfterPublishHooks(packages, options) {
2992
+ if (!packages.length) return;
2993
+ const extraEnv = {
2994
+ REPO_RELEASE_PUBLISHED_PACKAGES: JSON.stringify(packages),
2995
+ REPO_RELEASE_PUBLISH_SUMMARY: path.resolve(options.cwd, "pnpm-publish-summary.json")
2996
+ };
2997
+ for (const hook of options.config?.hooks?.afterPublish ?? []) try {
2998
+ runScripts([hook.script], options, extraEnv);
2999
+ } catch (error) {
3000
+ if (!hook.continueOnError) throw error;
3001
+ logger.warn(`release afterPublish hook failed and was ignored: ${hook.script}`);
3002
+ }
3003
+ }
3004
+ //#endregion
3005
+ //#region src/commands/release/github/errors.ts
3006
+ var GitHubApiError = class extends ReleaseCommandError {
3007
+ status;
3008
+ responseBody;
3009
+ constructor(message, status, responseBody) {
3010
+ super(message);
3011
+ this.status = status;
3012
+ this.responseBody = responseBody;
3013
+ this.name = "GitHubApiError";
3014
+ }
3015
+ };
3016
+ //#endregion
2923
3017
  //#region src/commands/release/github/metadata.ts
2924
3018
  function parseReleasePullRequestContributors(body) {
2925
3019
  if (!body) return [];
@@ -2968,17 +3062,100 @@ async function enrichReleaseNote(request, document) {
2968
3062
  };
2969
3063
  }
2970
3064
  //#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";
3065
+ //#region src/commands/release/github/state.ts
3066
+ const branch = "repoctl-release-state";
3067
+ function missing(error) {
3068
+ return error instanceof Error && "status" in error && error.status === 404;
3069
+ }
3070
+ function statePath(key) {
3071
+ if (!/^[a-f0-9]{64}$/.test(key)) throw new ReleaseCommandError("Invalid release state key");
3072
+ return `/contents/.repoctl-release/${key}.json`;
3073
+ }
3074
+ async function readReleaseState(request, key) {
3075
+ try {
3076
+ const { data } = await request("GET", `${statePath(key)}?ref=${branch}`);
3077
+ if (!data?.sha || !data.content) throw new ReleaseCommandError("GitHub returned an invalid release checkpoint");
3078
+ return {
3079
+ revision: data.sha,
3080
+ state: JSON.parse(Buffer.from(data.content, "base64").toString("utf8"))
3081
+ };
3082
+ } catch (error) {
3083
+ if (missing(error)) return;
3084
+ throw error;
2980
3085
  }
2981
- };
3086
+ }
3087
+ async function writeReleaseState(request, key, state, revision) {
3088
+ if (!revision) try {
3089
+ await request("GET", `/git/ref/heads/${branch}`);
3090
+ } catch (error) {
3091
+ if (!missing(error)) throw error;
3092
+ try {
3093
+ await request("POST", "/git/refs", {
3094
+ ref: `refs/heads/${branch}`,
3095
+ sha: state.packages[0]?.target
3096
+ });
3097
+ } catch {
3098
+ await request("GET", `/git/ref/heads/${branch}`);
3099
+ }
3100
+ }
3101
+ const content = JSON.stringify(state);
3102
+ try {
3103
+ const { data } = await request("PUT", statePath(key), {
3104
+ message: "chore(release): checkpoint release lifecycle [skip ci]",
3105
+ branch,
3106
+ content: Buffer.from(content).toString("base64"),
3107
+ ...revision ? { sha: revision } : {}
3108
+ });
3109
+ if (!data?.content.sha) throw new ReleaseCommandError("GitHub returned no release checkpoint revision");
3110
+ return data.content.sha;
3111
+ } catch (error) {
3112
+ const recovered = await readReleaseState(request, key);
3113
+ if (recovered && JSON.stringify(recovered.state) === content) return recovered.revision;
3114
+ 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)}`);
3115
+ }
3116
+ }
3117
+ //#endregion
3118
+ //#region src/commands/release/github/tags.ts
3119
+ async function readTagTarget(request, tag) {
3120
+ let object;
3121
+ try {
3122
+ object = (await request("GET", `/git/ref/tags/${encodeURIComponent(tag)}`)).data?.object;
3123
+ } catch (error) {
3124
+ if (error instanceof GitHubApiError && error.status === 404) return;
3125
+ throw error;
3126
+ }
3127
+ for (let depth = 0; object?.type === "tag" && depth < 10; depth++) object = (await request("GET", `/git/tags/${object.sha}`)).data?.object;
3128
+ if (object?.type !== "commit") throw new ReleaseCommandError(`Cannot resolve tag target for ${tag}`);
3129
+ return object.sha;
3130
+ }
3131
+ async function ensureTag(request, options) {
3132
+ const verify = async () => {
3133
+ const target = await readTagTarget(request, options.tag);
3134
+ if (target === void 0) return false;
3135
+ if (target !== options.target) throw new ReleaseCommandError(`Tag target conflict for ${options.tag}: expected ${options.target}, got ${target}; refusing to move the tag`);
3136
+ return true;
3137
+ };
3138
+ if (await verify()) return;
3139
+ try {
3140
+ await request("POST", "/git/refs", {
3141
+ ref: `refs/tags/${options.tag}`,
3142
+ sha: options.target
3143
+ });
3144
+ } catch (error) {
3145
+ if (!(error instanceof GitHubApiError) || ![
3146
+ 0,
3147
+ 422,
3148
+ 429,
3149
+ 500,
3150
+ 502,
3151
+ 503,
3152
+ 504
3153
+ ].includes(error.status)) throw error;
3154
+ if (!await verify()) throw error;
3155
+ }
3156
+ }
3157
+ //#endregion
3158
+ //#region src/commands/release/github/client.ts
2982
3159
  var GitHubClient = class {
2983
3160
  token;
2984
3161
  repository;
@@ -3008,6 +3185,7 @@ var GitHubClient = class {
3008
3185
  try {
3009
3186
  response = await this.requestFetch(`${this.apiUrl}/repos/${repository}${endpoint}`, {
3010
3187
  method,
3188
+ signal: AbortSignal.timeout(3e4),
3011
3189
  headers: {
3012
3190
  "Accept": "application/vnd.github+json",
3013
3191
  "Authorization": `Bearer ${this.token}`,
@@ -3017,7 +3195,7 @@ var GitHubClient = class {
3017
3195
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
3018
3196
  });
3019
3197
  } catch (error) {
3020
- if (method !== "POST" && attempt < this.retryAttempts) {
3198
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3021
3199
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3022
3200
  continue;
3023
3201
  }
@@ -3027,7 +3205,7 @@ var GitHubClient = class {
3027
3205
  try {
3028
3206
  text = await response.text();
3029
3207
  } catch (error) {
3030
- if (method !== "POST" && attempt < this.retryAttempts) {
3208
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3031
3209
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3032
3210
  continue;
3033
3211
  }
@@ -3037,21 +3215,21 @@ var GitHubClient = class {
3037
3215
  if (text) try {
3038
3216
  data = JSON.parse(text);
3039
3217
  } catch {
3040
- if (attempt < this.retryAttempts) {
3218
+ if (method !== "POST" && method !== "PUT" && attempt < this.retryAttempts) {
3041
3219
  await this.sleep(this.retryDelay * 2 ** (attempt - 1));
3042
3220
  continue;
3043
3221
  }
3044
- throw new GitHubApiError(`GitHub API returned invalid JSON for ${method} ${endpoint}`, response.status, text);
3222
+ throw new GitHubApiError(`GitHub API returned invalid JSON for ${method} ${endpoint}`, method === "POST" || method === "PUT" ? 0 : response.status, text);
3045
3223
  }
3046
3224
  if (!response.ok) {
3047
3225
  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) {
3226
+ if (method !== "POST" && method !== "PUT" && (response.status === 429 || response.status >= 500) && attempt < this.retryAttempts) {
3049
3227
  const retryAfter = response.headers.get("retry-after");
3050
3228
  const reset = response.headers.get("x-ratelimit-reset");
3051
3229
  const retrySeconds = retryAfter && /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) : retryAfter ? Math.max(0, (Date.parse(retryAfter) - Date.now()) / 1e3) : 0;
3052
3230
  const resetSeconds = reset && /^\d+$/.test(reset) ? Math.max(0, Number(reset) - Date.now() / 1e3) : 0;
3053
3231
  const delay = Math.max(this.retryDelay * 2 ** (attempt - 1), retrySeconds * 1e3, resetSeconds * 1e3);
3054
- await this.sleep(delay);
3232
+ await this.sleep(Math.min(delay, 3e4));
3055
3233
  continue;
3056
3234
  }
3057
3235
  throw new GitHubApiError(`GitHub API ${method} ${endpoint} failed (${response.status}): ${message}`, response.status, text);
@@ -3066,6 +3244,12 @@ var GitHubClient = class {
3066
3244
  getRequest() {
3067
3245
  return this.request.bind(this);
3068
3246
  }
3247
+ async readReleaseState(key) {
3248
+ return readReleaseState(this.getRequest(), key);
3249
+ }
3250
+ async writeReleaseState(key, state, revision) {
3251
+ return writeReleaseState(this.getRequest(), key, state, revision);
3252
+ }
3069
3253
  async ensurePullRequest(options) {
3070
3254
  const [owner] = this.getRepository().split("/");
3071
3255
  const head = options.head.includes(":") ? options.head : `${owner}:${options.head}`;
@@ -3137,7 +3321,8 @@ var GitHubClient = class {
3137
3321
  if (options.body !== void 0 || options.name !== void 0) return (await this.request("PATCH", `/releases/${existing.id}`, {
3138
3322
  ...options.name === void 0 ? {} : { name: options.name },
3139
3323
  ...options.body === void 0 ? {} : { body: options.body },
3140
- prerelease: options.prerelease ?? false
3324
+ prerelease: options.prerelease ?? false,
3325
+ draft: false
3141
3326
  })).data ?? existing;
3142
3327
  return existing;
3143
3328
  }
@@ -3201,106 +3386,136 @@ var GitHubClient = class {
3201
3386
  async readReleasePullRequestContributors(target) {
3202
3387
  return readReleasePullRequestContributors(this.getRequest(), target);
3203
3388
  }
3389
+ async readTagTarget(tag) {
3390
+ return readTagTarget(this.getRequest(), tag);
3391
+ }
3204
3392
  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
- }
3393
+ return ensureTag(this.getRequest(), options);
3221
3394
  }
3222
3395
  };
3223
3396
  //#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;
3397
+ //#region src/commands/release/metadata.ts
3398
+ function gitRefExists(ref, options) {
3399
+ return (options.spawn ?? spawnSync)("git", [
3400
+ "rev-parse",
3401
+ "--verify",
3402
+ "--quiet",
3403
+ ref
3404
+ ], {
3405
+ cwd: options.cwd,
3406
+ encoding: "utf8",
3407
+ shell: false,
3408
+ stdio: "ignore"
3409
+ }).status === 0;
3246
3410
  }
3247
- async function readPackageManifest(file) {
3248
- return JSON.parse(await readFile(file, "utf8"));
3411
+ function remoteTagExists(tag, options) {
3412
+ return (options.spawn ?? spawnSync)("git", [
3413
+ "ls-remote",
3414
+ "--exit-code",
3415
+ "--refs",
3416
+ "origin",
3417
+ `refs/tags/${tag}`
3418
+ ], {
3419
+ cwd: options.cwd,
3420
+ encoding: "utf8",
3421
+ shell: false,
3422
+ stdio: "ignore"
3423
+ }).status === 0;
3249
3424
  }
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"))
3425
+ function resolveGitHub(options) {
3426
+ const env = getReleaseEnv(options);
3427
+ return options.github ?? new GitHubClient({
3428
+ ...env["GITHUB_TOKEN"] ? { token: env["GITHUB_TOKEN"] } : {},
3429
+ ...env["GITHUB_REPOSITORY"] ? { repository: env["GITHUB_REPOSITORY"] } : {},
3430
+ ...env["GITHUB_API_URL"] ? { apiUrl: env["GITHUB_API_URL"] } : {}
3260
3431
  });
3261
- if (violations.length > 0) throw new ReleaseCommandError([`Expected publishable workspace dependencies to use ${EXPECTED_WORKSPACE_SPEC}:`, ...violations.map((violation) => `- ${violation}`)].join("\n"));
3262
- }
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;
3274
3432
  }
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
- });
3433
+ function resolveTarget(options) {
3434
+ return getReleaseEnv(options)["GITHUB_SHA"]?.trim() || capture("git", ["rev-parse", "HEAD"], options);
3283
3435
  }
3284
- async function runQualityScripts(options) {
3285
- await assertWorkspaceDependencyProtocols(options.cwd);
3286
- runScripts(options.config?.qualityScripts ?? defaultQualityScripts, options);
3287
- runScripts(options.config?.hooks?.verify ?? [], options);
3436
+ function resolveReleaseLocale(options) {
3437
+ return resolveRepoctlLocale({ env: getReleaseEnv(options) });
3288
3438
  }
3289
- function runReleaseHooks(phase, options) {
3290
- runScripts(options.config?.hooks?.[phase] ?? [], options);
3439
+ function formatPublishedPackageSummary(packages) {
3440
+ return ["Published packages:", ...packages.length ? packages.map((pkg) => ` - ${pkg.name}@${pkg.version}`) : [" (none)"]].join("\n");
3291
3441
  }
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);
3442
+ async function publishMetadata(packages, options, prerelease = false) {
3443
+ if (!packages.length) {
3444
+ logger.success(formatPublishedPackageSummary(packages));
3445
+ return;
3446
+ }
3447
+ const github = resolveGitHub(options);
3448
+ const target = resolveTarget(options);
3449
+ const releaseEnv = getReleaseEnv(options);
3450
+ let releaseContributors = [];
3451
+ if (github.readReleasePullRequestContributors) try {
3452
+ releaseContributors = await github.readReleasePullRequestContributors(target);
3300
3453
  } catch (error) {
3301
- if (!hook.continueOnError) throw error;
3302
- logger.warn(`release afterPublish hook failed and was ignored: ${hook.script}`);
3454
+ const message = error instanceof Error ? error.message : String(error);
3455
+ logger.warn(`GitHub release PR contributor lookup skipped: ${message}`);
3456
+ }
3457
+ const metadata = {
3458
+ locale: resolveReleaseLocale(options),
3459
+ ...releaseContributors.length ? { contributors: releaseContributors } : {},
3460
+ ...releaseEnv["GITHUB_REPOSITORY"] ? { repository: releaseEnv["GITHUB_REPOSITORY"] } : {},
3461
+ ...releaseEnv["GITHUB_SERVER_URL"] ? { serverUrl: releaseEnv["GITHUB_SERVER_URL"] } : {}
3462
+ };
3463
+ const publishedPackageNames = new Set(packages.map((pkg) => pkg.name));
3464
+ let noteDocument = await buildReleaseNoteDocument(options.cwd, void 0, metadata, publishedPackageNames);
3465
+ if (github.enrichReleaseNote) noteDocument = await github.enrichReleaseNote(noteDocument);
3466
+ for (const pkg of packages) {
3467
+ const tag = `${pkg.name}@${pkg.version}`;
3468
+ const body = renderGitHubRelease({
3469
+ ...noteDocument,
3470
+ packages: noteDocument.packages.filter((item) => item.name === pkg.name && item.version === pkg.version),
3471
+ entries: noteDocument.entries.filter((entry) => entry.packageName === pkg.name && entry.version === pkg.version),
3472
+ compareUrls: noteDocument.compareUrls.filter((url) => url.includes(encodeURIComponent(`${pkg.name}@`)))
3473
+ }, metadata);
3474
+ if (github.ensureTag) {
3475
+ await github.ensureTag({
3476
+ tag,
3477
+ target
3478
+ });
3479
+ await github.ensureRelease({
3480
+ tag,
3481
+ target,
3482
+ prerelease,
3483
+ name: tag,
3484
+ body
3485
+ });
3486
+ continue;
3487
+ }
3488
+ if (remoteTagExists(tag, options)) {
3489
+ await github.ensureRelease({
3490
+ tag,
3491
+ target,
3492
+ prerelease,
3493
+ name: tag,
3494
+ body
3495
+ });
3496
+ continue;
3497
+ }
3498
+ if (!gitRefExists(tag, options)) run("git", [
3499
+ "tag",
3500
+ "-a",
3501
+ tag,
3502
+ "-m",
3503
+ tag
3504
+ ], options);
3505
+ run("git", [
3506
+ "push",
3507
+ "origin",
3508
+ `refs/tags/${tag}`
3509
+ ], options);
3510
+ await github.ensureRelease({
3511
+ tag,
3512
+ target,
3513
+ prerelease,
3514
+ name: tag,
3515
+ body
3516
+ });
3303
3517
  }
3518
+ logger.success(formatPublishedPackageSummary(packages));
3304
3519
  }
3305
3520
  //#endregion
3306
3521
  //#region src/commands/release/publish/evidence.ts
@@ -3365,11 +3580,13 @@ async function writeJsonAtomic(filename, value) {
3365
3580
  /** Evidence is monotonic for this invocation; old on-disk reports are never trusted. */
3366
3581
  var PublishState = class {
3367
3582
  candidates;
3583
+ checkpoint;
3368
3584
  accepted = /* @__PURE__ */ new Map();
3369
3585
  confirmed = /* @__PURE__ */ new Set();
3370
3586
  allowed;
3371
- constructor(candidates) {
3587
+ constructor(candidates, checkpoint) {
3372
3588
  this.candidates = candidates;
3589
+ this.checkpoint = checkpoint;
3373
3590
  this.allowed = new Set(candidates.map(packageKey));
3374
3591
  }
3375
3592
  accept(packages) {
@@ -3398,6 +3615,7 @@ var PublishState = class {
3398
3615
  confirmedPackages: acceptedPackages.filter((pkg) => this.confirmed.has(packageKey(pkg)))
3399
3616
  });
3400
3617
  await writeJsonAtomic(path.join(cwd, "pnpm-publish-summary.json"), { publishedPackages: acceptedPackages });
3618
+ await this.checkpoint?.(acceptedPackages);
3401
3619
  }
3402
3620
  };
3403
3621
  //#endregion
@@ -3408,9 +3626,14 @@ function sleep(milliseconds, options) {
3408
3626
  return options.sleep?.(milliseconds) ?? new Promise((resolve) => setTimeout(resolve, milliseconds));
3409
3627
  }
3410
3628
  async function refreshRegistry(state, options, packages = state.candidates, deadline = performance.now() + visibilityBudget) {
3411
- for (const pkg of state.unconfirmed(packages)) {
3629
+ const unknown = [];
3630
+ const pending = state.unconfirmed(packages);
3631
+ for (const [index, pkg] of pending.entries()) {
3412
3632
  const remaining = Math.floor(deadline - performance.now());
3413
- if (remaining <= 0) break;
3633
+ if (remaining <= 0) {
3634
+ unknown.push(...pending.slice(index));
3635
+ break;
3636
+ }
3414
3637
  const result = (options.spawn ?? spawnSync)("npm", [
3415
3638
  "view",
3416
3639
  packageKey(pkg),
@@ -3431,8 +3654,9 @@ async function refreshRegistry(state, options, packages = state.candidates, dead
3431
3654
  if (result.status === 0 && outputText(result.stdout).trim() === pkg.version) {
3432
3655
  state.confirm(pkg);
3433
3656
  await state.save(options.cwd, "confirming");
3434
- }
3657
+ } else if (result.error || result.status === 0 || !/\bE404\b/.test(outputText(result.stderr))) unknown.push(pkg);
3435
3658
  }
3659
+ return unknown;
3436
3660
  }
3437
3661
  async function confirmVisibility(state, options, packages, initialDelay = 0) {
3438
3662
  let remaining = visibilityBudget;
@@ -3466,8 +3690,9 @@ async function getPublishCandidates(cwd) {
3466
3690
  return candidates;
3467
3691
  }
3468
3692
  /** 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);
3693
+ async function publishWithRetry(args, options, candidates, confirmAll = false, recovery) {
3694
+ const state = new PublishState(candidates, recovery?.save);
3695
+ state.accept(recovery?.accepted ?? []);
3471
3696
  let attemptArgs = args;
3472
3697
  let recovering = confirmAll;
3473
3698
  try {
@@ -3497,14 +3722,16 @@ async function publishWithRetry(args, options, candidates, confirmAll = false) {
3497
3722
  const delay = retryDelays[attempt - 1];
3498
3723
  logger.warn(`npm publish transient failure; reconciling before retry in ${delay / 1e3}s (attempt ${attempt + 1}/${publishAttempts}).`);
3499
3724
  await sleep(delay, options);
3500
- await refreshRegistry(state, options);
3725
+ const unknown = await refreshRegistry(state, options);
3501
3726
  await state.save(options.cwd, "publishing");
3727
+ const unresolved = unknown.filter((pkg) => state.pendingUploads.some((pending) => packageKey(pending) === packageKey(pkg)));
3728
+ if (unresolved.length) throw new ReleaseCommandError(`npm registry state is unknown; refusing to retry uploads for: ${unresolved.map(packageKey).join(", ")}`);
3502
3729
  if (!state.pendingUploads.length) {
3503
3730
  await confirmVisibility(state, options, candidates);
3504
3731
  await state.save(options.cwd, "complete");
3505
3732
  return;
3506
3733
  }
3507
- attemptArgs = [...args, ...state.pendingUploads.flatMap((pkg) => ["--filter", pkg.name])];
3734
+ attemptArgs = [...args.filter((arg, index) => arg !== "--filter" && args[index - 1] !== "--filter"), ...state.pendingUploads.flatMap((pkg) => ["--filter", pkg.name])];
3508
3735
  }
3509
3736
  } catch (error) {
3510
3737
  await state.save(options.cwd, "failed");
@@ -3513,6 +3740,294 @@ async function publishWithRetry(args, options, candidates, confirmAll = false) {
3513
3740
  }
3514
3741
  }
3515
3742
  //#endregion
3743
+ //#region src/commands/release/lifecycle/hooks.ts
3744
+ async function finishHooks(state, save, options) {
3745
+ const acknowledged = new Set((getReleaseEnv(options)["REPO_RELEASE_ACKNOWLEDGE_HOOKS"] ?? "").split(",").filter(Boolean));
3746
+ for (const hook of options.config?.hooks?.afterPublish ?? []) {
3747
+ const status = state.hooks[hook.script];
3748
+ if (status === "complete" || status === "ignored") continue;
3749
+ if (acknowledged.has(hook.script)) {
3750
+ state.hooks[hook.script] = "complete";
3751
+ await save();
3752
+ continue;
3753
+ }
3754
+ 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`);
3755
+ state.hooks[hook.script] = "running";
3756
+ await save();
3757
+ try {
3758
+ runAfterPublishHooks(state.packages.map(({ name, version }) => ({
3759
+ name,
3760
+ version
3761
+ })), {
3762
+ ...options,
3763
+ config: {
3764
+ ...options.config,
3765
+ hooks: { afterPublish: [{
3766
+ ...hook,
3767
+ continueOnError: false
3768
+ }] }
3769
+ }
3770
+ });
3771
+ state.hooks[hook.script] = "complete";
3772
+ } catch (error) {
3773
+ if (!hook.continueOnError) throw error;
3774
+ state.hooks[hook.script] = "ignored";
3775
+ }
3776
+ await save();
3777
+ }
3778
+ }
3779
+ //#endregion
3780
+ //#region src/commands/release/lifecycle/identity.ts
3781
+ /** 用原提交中的 manifest/changelog 校验版本归属,禁止以重跑 HEAD 偷换来源。 */
3782
+ async function verifySource(pkg, target, options) {
3783
+ 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`);
3784
+ const workspace = (await getWorkspacePackages(options.cwd)).find((item) => item.manifest.name === pkg.name);
3785
+ if (!workspace) throw new ReleaseCommandError(`Release package is absent from workspace: ${pkg.name}`);
3786
+ const relative = path.relative(await realpath(options.cwd), workspace.pkgJsonPath);
3787
+ const original = JSON.parse(capture("git", ["show", `${target}:${relative}`], options));
3788
+ if (original.name !== pkg.name || original.version !== pkg.version) throw new ReleaseCommandError(`Original commit does not contain ${pkg.name}@${pkg.version}`);
3789
+ const changelog = path.join(path.dirname(relative), "CHANGELOG.md");
3790
+ let current;
3791
+ try {
3792
+ current = await readFile(path.join(options.cwd, changelog), "utf8");
3793
+ } catch (error) {
3794
+ if (error.code === "ENOENT") return;
3795
+ throw error;
3796
+ }
3797
+ 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`);
3798
+ }
3799
+ /** 从完整 Git 历史定位当前版本首次进入主线的提交,忽略后续 CI 修复。 */
3800
+ async function findVersionCommit(pkg, options) {
3801
+ const workspace = (await getWorkspacePackages(options.cwd)).find((item) => item.manifest.name === pkg.name);
3802
+ if (!workspace || capture("git", ["rev-parse", "--is-shallow-repository"], options) !== "false") throw new ReleaseCommandError("Release source discovery requires a full checkout (fetch-depth: 0)");
3803
+ const relative = path.relative(await realpath(options.cwd), workspace.pkgJsonPath);
3804
+ const commits = capture("git", [
3805
+ "log",
3806
+ "--format=%H",
3807
+ "--",
3808
+ relative
3809
+ ], options).split("\n").filter(Boolean);
3810
+ let target = "";
3811
+ for (const commit of commits) {
3812
+ const original = JSON.parse(capture("git", ["show", `${commit}:${relative}`], options));
3813
+ if (original.name !== pkg.name || original.version !== pkg.version) break;
3814
+ target = commit;
3815
+ }
3816
+ if (!target) throw new ReleaseCommandError(`Cannot find version commit for ${pkg.name}@${pkg.version}; commit the prepared versions first`);
3817
+ return target;
3818
+ }
3819
+ //#endregion
3820
+ //#region src/commands/release/lifecycle/registry.ts
3821
+ /** 明确的 E404 才代表不存在;其余失败不能作为重新上传的依据。 */
3822
+ async function inspectRegistry(pkg, options) {
3823
+ for (let attempt = 0; attempt < 3; attempt++) {
3824
+ const result = (options.spawn ?? spawnSync)("npm", [
3825
+ "view",
3826
+ packageKey(pkg),
3827
+ "--json"
3828
+ ], {
3829
+ cwd: options.cwd,
3830
+ env: getReleaseEnv(options),
3831
+ encoding: "utf8",
3832
+ shell: false,
3833
+ stdio: [
3834
+ "ignore",
3835
+ "pipe",
3836
+ "pipe"
3837
+ ],
3838
+ timeout: 1e4,
3839
+ killSignal: "SIGKILL"
3840
+ });
3841
+ const output = `${String(result.stdout ?? "")}
3842
+ ${String(result.stderr ?? "")}`;
3843
+ if (result.status === 0) {
3844
+ try {
3845
+ const data = JSON.parse(String(result.stdout));
3846
+ if (data.version === pkg.version) return data;
3847
+ } catch {}
3848
+ throw new ReleaseCommandError(`npm returned invalid metadata for ${packageKey(pkg)}; registry state is unknown`);
3849
+ }
3850
+ if (/\bE404\b/.test(output) && !result.error) return;
3851
+ if (/\b(?:E401|E403|ENEEDAUTH)\b/.test(output)) throw new ReleaseCommandError(`npm authentication failed for ${packageKey(pkg)}`);
3852
+ if (attempt < 2) await sleep(1e3 * 2 ** attempt, options);
3853
+ }
3854
+ throw new ReleaseCommandError(`npm registry state is unknown for ${packageKey(pkg)} after bounded retries; no upload attempted`);
3855
+ }
3856
+ //#endregion
3857
+ //#region src/commands/release/lifecycle/index.ts
3858
+ async function publishLifecycle(options, selected, distTag = "latest") {
3859
+ const github = resolveGitHub(options);
3860
+ if (!github.readReleaseState || !github.writeReleaseState || !github.ensureTag || !github.listReleases) throw new ReleaseCommandError("Release recovery requires checkpoint, tag and release query operations");
3861
+ const env = getReleaseEnv(options);
3862
+ const repository = env["GITHUB_REPOSITORY"];
3863
+ if (!repository || !/^[^/]+\/[^/]+$/.test(repository)) throw new ReleaseCommandError("GITHUB_REPOSITORY is required for durable release recovery");
3864
+ const candidates = selected ?? await getPublishCandidates(options.cwd);
3865
+ const identity = JSON.stringify({
3866
+ repository,
3867
+ distTag,
3868
+ packages: candidates.map(packageKey).sort()
3869
+ });
3870
+ const key = createHash("sha256").update(identity).digest("hex");
3871
+ const snapshot = await github.readReleaseState(key);
3872
+ let revision = snapshot?.revision;
3873
+ const releases = new Map((await github.listReleases()).map((release) => [release.tag_name, release]));
3874
+ const registry = /* @__PURE__ */ new Map();
3875
+ for (const pkg of candidates) registry.set(packageKey(pkg), await inspectRegistry(pkg, options));
3876
+ const tags = /* @__PURE__ */ new Map();
3877
+ if (github.readTagTarget) for (const pkg of candidates) tags.set(packageKey(pkg), await github.readTagTarget(packageKey(pkg)));
3878
+ let state;
3879
+ if (snapshot) {
3880
+ state = snapshot.state;
3881
+ 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");
3882
+ } else {
3883
+ const packages = [];
3884
+ for (const pkg of candidates) {
3885
+ const published = registry.get(packageKey(pkg));
3886
+ const release = releases.get(packageKey(pkg));
3887
+ const tagTarget = tags.get(packageKey(pkg));
3888
+ if (published && release && !release.draft && Boolean(release.prerelease) === (distTag !== "latest") && (!github.readTagTarget || tagTarget)) {
3889
+ if (published.gitHead && tagTarget && published.gitHead !== tagTarget) throw new ReleaseCommandError(`Tag target conflict for ${packageKey(pkg)}`);
3890
+ continue;
3891
+ }
3892
+ const target = published ? published.gitHead ?? env["REPO_RELEASE_SOURCE_SHA"] ?? "" : env["REPO_RELEASE_SOURCE_SHA"] ?? await findVersionCommit(pkg, options);
3893
+ await verifySource(pkg, target, options);
3894
+ packages.push({
3895
+ ...pkg,
3896
+ target
3897
+ });
3898
+ }
3899
+ const targets = new Set(packages.map((pkg) => pkg.target));
3900
+ for (const pkg of candidates) {
3901
+ const source = registry.get(packageKey(pkg))?.gitHead;
3902
+ if (source && targets.has(source) && !packages.some((item) => packageKey(item) === packageKey(pkg))) {
3903
+ await verifySource(pkg, source, options);
3904
+ packages.push({
3905
+ ...pkg,
3906
+ target: source
3907
+ });
3908
+ }
3909
+ }
3910
+ if (!packages.length) {
3911
+ logger.info("No unfinished release targets found.");
3912
+ return [];
3913
+ }
3914
+ const legacy = packages.some((pkg) => registry.has(packageKey(pkg)) && registry.get(packageKey(pkg)));
3915
+ state = {
3916
+ schemaVersion: 1,
3917
+ writer: "",
3918
+ repository,
3919
+ candidates,
3920
+ packages,
3921
+ accepted: packages.filter((pkg) => registry.get(packageKey(pkg))).map(({ name, version }) => ({
3922
+ name,
3923
+ version
3924
+ })),
3925
+ npm: "pending",
3926
+ metadata: [],
3927
+ complete: false,
3928
+ hooks: Object.fromEntries((options.config?.hooks?.afterPublish ?? []).map((hook) => [hook.script, legacy ? "running" : "pending"]))
3929
+ };
3930
+ }
3931
+ const scripts = (options.config?.hooks?.afterPublish ?? []).map((hook) => hook.script);
3932
+ 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");
3933
+ for (const pkg of state.packages) {
3934
+ await verifySource(pkg, pkg.target, options);
3935
+ const target = tags.get(packageKey(pkg));
3936
+ if (target && target !== pkg.target) throw new ReleaseCommandError(`Tag target conflict for ${packageKey(pkg)}`);
3937
+ }
3938
+ if (options.dryRun ?? env["REPO_RELEASE_DRY_RUN"] === "true") {
3939
+ logger.info(JSON.stringify({
3940
+ key,
3941
+ packages: state.packages,
3942
+ npm: state.npm,
3943
+ tags: state.packages.filter((pkg) => !tags.get(packageKey(pkg))).map(packageKey),
3944
+ metadata: state.packages.filter((pkg) => !releases.has(packageKey(pkg))).map(packageKey),
3945
+ hooks: state.hooks
3946
+ }, null, 2));
3947
+ return state.packages.map(({ name, version }) => ({
3948
+ name,
3949
+ version
3950
+ }));
3951
+ }
3952
+ state.writer = randomUUID();
3953
+ state.complete = false;
3954
+ const save = async () => {
3955
+ await writeFile(path.join(options.cwd, "repoctl-release-progress.json"), `${JSON.stringify(state, null, 2)}\n`);
3956
+ revision = await github.writeReleaseState(key, state, revision);
3957
+ };
3958
+ await save();
3959
+ const packages = state.packages.map(({ name, version }) => ({
3960
+ name,
3961
+ version
3962
+ }));
3963
+ const confirmed = new PublishState(packages);
3964
+ confirmed.accept(state.accepted);
3965
+ for (const pkg of packages) if (registry.get(packageKey(pkg))) confirmed.confirm(pkg);
3966
+ if (state.npm === "running") await confirmVisibility(confirmed, options, packages);
3967
+ else if (confirmed.unconfirmed(state.accepted).length) await confirmVisibility(confirmed, options, state.accepted);
3968
+ const missing = packages.filter((pkg) => !confirmed.acceptedPackages.some((item) => packageKey(item) === packageKey(pkg)));
3969
+ if (missing.length) {
3970
+ runReleaseHooks("beforePublish", options);
3971
+ await clearPublishSummary(options.cwd);
3972
+ state.npm = "running";
3973
+ state.complete = false;
3974
+ await save();
3975
+ try {
3976
+ await publishWithRetry([
3977
+ "publish",
3978
+ "-r",
3979
+ "--report-summary",
3980
+ "--provenance",
3981
+ "--no-git-checks",
3982
+ "--tag",
3983
+ distTag,
3984
+ ...missing.flatMap((pkg) => ["--filter", pkg.name])
3985
+ ], options, packages, true, {
3986
+ accepted: confirmed.acceptedPackages,
3987
+ save: async (accepted) => {
3988
+ state.accepted = accepted;
3989
+ await save();
3990
+ }
3991
+ });
3992
+ } catch (error) {
3993
+ state.npm = "failed";
3994
+ await save();
3995
+ throw error;
3996
+ }
3997
+ }
3998
+ for (const pkg of packages) {
3999
+ const remote = await inspectRegistry(pkg, options);
4000
+ 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`);
4001
+ }
4002
+ state.npm = "complete";
4003
+ state.accepted = packages;
4004
+ await save();
4005
+ await writeFile(path.join(options.cwd, "pnpm-publish-summary.json"), JSON.stringify({ publishedPackages: packages }));
4006
+ for (const pkg of state.packages) {
4007
+ await github.ensureTag({
4008
+ tag: packageKey(pkg),
4009
+ target: pkg.target
4010
+ });
4011
+ const release = releases.get(packageKey(pkg));
4012
+ if (!release || release.draft || Boolean(release.prerelease) !== (distTag !== "latest")) await publishMetadata([pkg], {
4013
+ ...options,
4014
+ env: {
4015
+ ...env,
4016
+ GITHUB_SHA: pkg.target
4017
+ }
4018
+ }, distTag !== "latest");
4019
+ if (!state.metadata.includes(packageKey(pkg))) {
4020
+ state.metadata.push(packageKey(pkg));
4021
+ await save();
4022
+ }
4023
+ }
4024
+ await finishHooks(state, save, options);
4025
+ state.complete = true;
4026
+ await save();
4027
+ logger.success(`Release lifecycle complete: ${packages.map(packageKey).join(", ")}`);
4028
+ return packages;
4029
+ }
4030
+ //#endregion
3516
4031
  //#region src/commands/release/types.ts
3517
4032
  const prereleaseBranches$1 = /* @__PURE__ */ new Set([
3518
4033
  "alpha",
@@ -3522,11 +4037,14 @@ const prereleaseBranches$1 = /* @__PURE__ */ new Set([
3522
4037
  ]);
3523
4038
  //#endregion
3524
4039
  //#region src/commands/release/prerelease.ts
3525
- async function releasePrerelease(options) {
4040
+ async function releasePrerelease(options, publish) {
3526
4041
  const branch = resolveBranch(options);
3527
4042
  if (!prereleaseBranches$1.has(branch)) throw new ReleaseCommandError(`repo release pre is only allowed on alpha, beta, rc, or next branches, got ${branch}`);
3528
4043
  await assertLaneAssignments(branch, options);
3529
- if (!await hasPendingIntents(options.cwd)) return;
4044
+ if (!await hasPendingIntents(options.cwd)) {
4045
+ if (publish) await runQualityScripts(options);
4046
+ return publish?.();
4047
+ }
3530
4048
  runReleaseHooks("beforeVersion", options);
3531
4049
  await runQualityScripts(options);
3532
4050
  run("pnpm", [
@@ -3542,6 +4060,14 @@ async function releasePrerelease(options) {
3542
4060
  "-m",
3543
4061
  `chore(release): ${branch} [skip ci]`
3544
4062
  ], options);
4063
+ if (publish) {
4064
+ run("git", [
4065
+ "push",
4066
+ "origin",
4067
+ `HEAD:${branch}`
4068
+ ], options);
4069
+ return publish();
4070
+ }
3545
4071
  runReleaseHooks("beforePublish", options);
3546
4072
  await clearPublishSummary(options.cwd);
3547
4073
  await publishWithRetry([
@@ -3570,39 +4096,31 @@ async function exitPrerelease(options) {
3570
4096
  }
3571
4097
  //#endregion
3572
4098
  //#region src/commands/release/reconcile.ts
3573
- function remoteTagExists$1(tag, options) {
3574
- return (options.spawn ?? spawnSync)("git", [
4099
+ function remoteTagTarget(tag, options) {
4100
+ const result = (options.spawn ?? spawnSync)("git", [
3575
4101
  "ls-remote",
3576
4102
  "--exit-code",
3577
- "--refs",
3578
4103
  "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"
4104
+ `refs/tags/${tag}`,
4105
+ `refs/tags/${tag}^{}`
3595
4106
  ], {
3596
4107
  cwd: options.cwd,
4108
+ env: getReleaseEnv(options),
3597
4109
  encoding: "utf8",
3598
4110
  shell: false,
3599
4111
  stdio: [
3600
4112
  "ignore",
3601
4113
  "pipe",
3602
- "ignore"
3603
- ]
4114
+ "pipe"
4115
+ ],
4116
+ timeout: 1e4
3604
4117
  });
3605
- return result.status === 0 && String(result.stdout ?? "").trim() === pkg.version;
4118
+ if (result.status === 2) return;
4119
+ if (result.status !== 0) throw new ReleaseCommandError(`Cannot query remote tag ${tag}; state is unknown`);
4120
+ const refs = String(result.stdout ?? "").trim().split("\n");
4121
+ const sha = (refs.find((ref) => ref.endsWith("^{}")) ?? refs[0])?.split(/\s+/)[0];
4122
+ if (!sha || !/^[a-f0-9]{40}$/.test(sha)) throw new ReleaseCommandError(`Invalid remote tag response for ${tag}`);
4123
+ return sha;
3606
4124
  }
3607
4125
  async function reconcileRelease(options) {
3608
4126
  const github = options.github ?? new GitHubClient();
@@ -3612,7 +4130,7 @@ async function reconcileRelease(options) {
3612
4130
  const packages = (await getWorkspacePackages(options.cwd)).flatMap(({ manifest }) => typeof manifest.name === "string" && typeof manifest.version === "string" ? [{
3613
4131
  name: manifest.name,
3614
4132
  version: manifest.version
3615
- }] : []).filter((pkg) => (!options.packageName || pkg.name === options.packageName) && (!options.packageVersion || pkg.version === options.packageVersion)).filter((pkg) => isPublished(pkg, options));
4133
+ }] : []).filter((pkg) => (!options.packageName || pkg.name === options.packageName) && (!options.packageVersion || pkg.version === options.packageVersion));
3616
4134
  const env = getReleaseEnv(options);
3617
4135
  const metadata = {};
3618
4136
  if (env["GITHUB_REPOSITORY"]) metadata.repository = env["GITHUB_REPOSITORY"];
@@ -3620,7 +4138,13 @@ async function reconcileRelease(options) {
3620
4138
  const document = await buildReleaseNoteDocument(options.cwd, void 0, metadata, new Set(packages.map((pkg) => pkg.name)));
3621
4139
  const repaired = [];
3622
4140
  const pending = [];
4141
+ const publishedPackages = [];
3623
4142
  for (const pkg of packages) {
4143
+ const published = await inspectRegistry(pkg, options);
4144
+ if (!published) continue;
4145
+ publishedPackages.push(pkg);
4146
+ const target = published.gitHead ?? env["REPO_RELEASE_SOURCE_SHA"] ?? "";
4147
+ await verifySource(pkg, target, options);
3624
4148
  const tag = `${pkg.name}@${pkg.version}`;
3625
4149
  const release = existing.get(tag);
3626
4150
  const body = renderGitHubRelease({
@@ -3629,18 +4153,20 @@ async function reconcileRelease(options) {
3629
4153
  entries: document.entries.filter((entry) => entry.packageName === pkg.name && entry.version === pkg.version),
3630
4154
  compareUrls: document.compareUrls.filter((url) => url.includes(encodeURIComponent(`${pkg.name}@`)))
3631
4155
  });
3632
- const needsTag = !remoteTagExists$1(tag, options);
4156
+ const tagTarget = github.readTagTarget ? await github.readTagTarget(tag) : remoteTagTarget(tag, options);
4157
+ if (tagTarget && tagTarget !== target) throw new ReleaseCommandError(`Tag target conflict for ${tag}`);
4158
+ const needsTag = !tagTarget;
3633
4159
  const needsRelease = !release || release.name !== tag || release.body !== body;
3634
4160
  if (!needsTag && !needsRelease) continue;
3635
4161
  pending.push(tag);
3636
4162
  if (options.dryRun) continue;
3637
4163
  if (needsTag && github.ensureTag) await github.ensureTag({
3638
4164
  tag,
3639
- target: resolveTarget$1(options)
4165
+ target
3640
4166
  });
3641
4167
  await github.ensureRelease({
3642
4168
  tag,
3643
- target: resolveTarget$1(options),
4169
+ target,
3644
4170
  name: tag,
3645
4171
  body
3646
4172
  });
@@ -3649,7 +4175,7 @@ async function reconcileRelease(options) {
3649
4175
  return {
3650
4176
  repaired,
3651
4177
  pending,
3652
- skipped: packages.filter((pkg) => !pending.includes(`${pkg.name}@${pkg.version}`)).map((pkg) => `${pkg.name}@${pkg.version}`)
4178
+ skipped: publishedPackages.filter((pkg) => !pending.includes(`${pkg.name}@${pkg.version}`)).map((pkg) => `${pkg.name}@${pkg.version}`)
3653
4179
  };
3654
4180
  }
3655
4181
  //#endregion
@@ -3669,12 +4195,15 @@ async function prepareStable(options) {
3669
4195
  runReleaseHooks("afterVersion", options);
3670
4196
  return hasGitChanges(options);
3671
4197
  }
3672
- async function publishStable(options) {
4198
+ async function assertStablePublish(options, quality = true) {
3673
4199
  const branch = resolveBranch(options);
3674
4200
  if (branch !== "main") throw new ReleaseCommandError(`repo release stable publish is only allowed on main, got ${branch}`);
3675
4201
  await assertStableLaneAssignments(options);
3676
4202
  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);
4203
+ if (quality) await runQualityScripts(options);
4204
+ }
4205
+ async function publishStable(options) {
4206
+ await assertStablePublish(options);
3678
4207
  runReleaseHooks("beforePublish", options);
3679
4208
  await clearPublishSummary(options.cwd);
3680
4209
  await publishWithRetry([
@@ -3795,123 +4324,6 @@ async function readReleaseTriggerContext(options) {
3795
4324
  //#endregion
3796
4325
  //#region src/commands/release/ci.ts
3797
4326
  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
- }
3842
- const github = resolveGitHub(options);
3843
- const target = resolveTarget(options);
3844
- 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
- const metadata = {
3853
- locale: resolveReleaseLocale(options),
3854
- ...releaseContributors.length ? { contributors: releaseContributors } : {},
3855
- ...releaseEnv["GITHUB_REPOSITORY"] ? { repository: releaseEnv["GITHUB_REPOSITORY"] } : {},
3856
- ...releaseEnv["GITHUB_SERVER_URL"] ? { serverUrl: releaseEnv["GITHUB_SERVER_URL"] } : {}
3857
- };
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;
3882
- }
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
- }
3913
- logger.success(formatPublishedPackageSummary(packages));
3914
- }
3915
4327
  async function createReleasePullRequest(options) {
3916
4328
  const branch = resolveBranch(options);
3917
4329
  if (branch !== "main") throw new ReleaseCommandError(`repo release stable prepare is only allowed on main, got ${branch}`);
@@ -3982,6 +4394,14 @@ async function recoverUnpublished(options) {
3982
4394
  ], options);
3983
4395
  if (actualVersion !== packageVersion) throw new ReleaseCommandError(`expected ${packageName}@${packageVersion} in the workspace, found ${actualVersion}`);
3984
4396
  await runQualityScripts(options);
4397
+ const github = resolveGitHub(options);
4398
+ if (github.readReleaseState && github.writeReleaseState) return publishLifecycle({
4399
+ ...options,
4400
+ github
4401
+ }, [{
4402
+ name: packageName,
4403
+ version: packageVersion
4404
+ }]);
3985
4405
  runReleaseHooks("beforePublish", options);
3986
4406
  await clearPublishSummary(options.cwd);
3987
4407
  await publishWithRetry([
@@ -4006,18 +4426,27 @@ function resolveMode(options) {
4006
4426
  if (requested && requested !== "auto") return requested;
4007
4427
  return "auto";
4008
4428
  }
4429
+ async function publishStableCi(options) {
4430
+ const github = resolveGitHub(options);
4431
+ if (github.readReleaseState && github.writeReleaseState) {
4432
+ await assertStablePublish(options, !(options.dryRun ?? getReleaseEnv(options)["REPO_RELEASE_DRY_RUN"] === "true"));
4433
+ return publishLifecycle({
4434
+ ...options,
4435
+ github
4436
+ });
4437
+ }
4438
+ const packages = await publishStable(options);
4439
+ await publishMetadata(packages, options);
4440
+ runAfterPublishHooks(packages, options);
4441
+ return packages;
4442
+ }
4009
4443
  async function releaseCi(options) {
4010
4444
  const mode = resolveMode(options);
4011
4445
  if (mode === "prepare") {
4012
4446
  await createReleasePullRequest(options);
4013
4447
  return;
4014
4448
  }
4015
- if (mode === "publish") {
4016
- const packages = await publishStable(options);
4017
- await publishMetadata(packages, options);
4018
- runAfterPublishHooks(packages, options);
4019
- return packages;
4020
- }
4449
+ if (mode === "publish") return publishStableCi(options);
4021
4450
  if (mode === "publish-unpublished") return recoverUnpublished(options);
4022
4451
  if (mode === "reconcile") return reconcileRelease({
4023
4452
  ...options,
@@ -4033,6 +4462,24 @@ async function releaseCi(options) {
4033
4462
  }
4034
4463
  const branch = resolveBranch(options);
4035
4464
  if (prereleaseBranches$1.has(branch)) {
4465
+ const github = resolveGitHub(options);
4466
+ if (github.readReleaseState && github.writeReleaseState) {
4467
+ if (options.dryRun ?? getReleaseEnv(options)["REPO_RELEASE_DRY_RUN"] === "true") {
4468
+ if (await hasPendingIntents(options.cwd)) throw new ReleaseCommandError("Prerelease dry-run requires an already prepared version commit");
4469
+ return publishLifecycle({
4470
+ ...options,
4471
+ github
4472
+ }, void 0, branch);
4473
+ }
4474
+ return releasePrerelease(options, () => publishLifecycle({
4475
+ ...options,
4476
+ github,
4477
+ env: {
4478
+ ...getReleaseEnv(options),
4479
+ GITHUB_SHA: capture("git", ["rev-parse", "HEAD"], options)
4480
+ }
4481
+ }, void 0, branch));
4482
+ }
4036
4483
  const packages = await releasePrerelease(options);
4037
4484
  if (!packages) return;
4038
4485
  await publishMetadata(packages, options, true);
@@ -4044,10 +4491,7 @@ async function releaseCi(options) {
4044
4491
  await createReleasePullRequest(options);
4045
4492
  return;
4046
4493
  }
4047
- const packages = await publishStable(options);
4048
- await publishMetadata(packages, options);
4049
- runAfterPublishHooks(packages, options);
4050
- return packages;
4494
+ return publishStableCi(options);
4051
4495
  }
4052
4496
  //#endregion
4053
4497
  //#region src/commands/release/repair.ts
@@ -4933,4 +5377,4 @@ var commands_exports = /* @__PURE__ */ __exportAll({
4933
5377
  verifyStagedTypecheck: () => verifyStagedTypecheck
4934
5378
  });
4935
5379
  //#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 };
5380
+ 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 };