@bensandee/tooling 0.105.0 → 0.106.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -173,7 +173,7 @@ function loadEnvFileForBin(rawArgs, bin, io = processIo) {
173
173
  // src/env-file-preload.ts
174
174
  const envFileLoad = loadEnvFileForBin(process.argv.slice(2), {
175
175
  name: "bst",
176
- version: "0.105.0"
176
+ version: "0.106.0"
177
177
  });
178
178
  // ../cli-kit/src/logger.ts
179
179
  const RANK = {
@@ -1643,15 +1643,23 @@ function resolveDocsConfig(targetDir) {
1643
1643
  }
1644
1644
  // src/utils/tooling-config.ts
1645
1645
  const CONFIG_FILE = ".tooling.json";
1646
- const ReleaseAssetSchema = z.strictObject({
1646
+ const ReleaseAssetSchema$1 = z.strictObject({
1647
1647
  command: z.array(z.string()).nonempty().optional().meta({ description: "argv passed directly to the child process (no shell interpolation), e.g. [\"pnpm\",\"build\"]" }),
1648
- file: z.string().meta({ description: "Path to the asset file to upload, relative to the project root" }),
1649
- name: z.string().optional().meta({ description: "Asset name in the release (defaults to the file's basename)" })
1648
+ file: z.string().optional().meta({ description: "Path to the single asset file to upload, relative to the project root. Exactly one of file and files" }),
1649
+ files: z.array(z.string()).nonempty().optional().meta({ description: "Glob patterns; every match is uploaded under its basename, after the entry's build runs. Exactly one of file and files" }),
1650
+ name: z.string().optional().meta({ description: "Asset name in the release (defaults to the file's basename; file only)" }),
1651
+ package: z.string().optional().meta({ description: "Workspace package this asset belongs to: the build, its version stamp and its uploads run once per release of that package. In a monorepo, a releaseAssets entry must name one" })
1650
1652
  });
1651
1653
  const VersionStampSchema = z.strictObject({
1652
1654
  file: z.string().meta({ description: "Path to the file whose version line release:assets stamps, relative to the project root" }),
1653
1655
  prefix: z.string().min(1).meta({ description: "Literal string (never a pattern) the target line must start with. Not a regex -- read the output line straight off prefix + version + suffix" }),
1654
- suffix: z.string().optional().meta({ description: "Literal string (never a pattern) the target line must end with (default: none)" })
1656
+ suffix: z.string().optional().meta({ description: "Literal string (never a pattern) the target line must end with (default: none)" }),
1657
+ package: z.string().optional().meta({ description: "Workspace package whose release version this stamp carries; the stamp runs with each release of that package. Omitted: the root package's version, as before" })
1658
+ });
1659
+ const SnapshotConfigSchema = z.strictObject({
1660
+ preid: z.string().regex(/^[a-z][a-z0-9]*$/).meta({ description: "Prerelease identifier the snapshot versions carry, e.g. `alpha` in `1.2.6-alpha.42`" }),
1661
+ keep: z.number().int().min(1).optional().meta({ description: "How many snapshot releases to keep per package before the oldest are pruned (default: 3)" }),
1662
+ packages: z.array(z.string()).nonempty().optional().meta({ description: "Workspace package names to snapshot. Required in a monorepo; in a single-package repo the root package is the default" })
1655
1663
  });
1656
1664
  const DeployConfigSchema = z.strictObject({
1657
1665
  dispatchRepo: z.string().meta({ description: "Target repository (owner/repo) whose workflow the release dispatches to trigger a deploy" }),
@@ -1790,8 +1798,9 @@ const ToolingConfigSchema = z.strictObject({
1790
1798
  dockerCheck: z.union([z.literal(false), DockerCheckConfigSchema]).optional().meta({ description: "Docker health check configuration or false to disable" }),
1791
1799
  registryHost: z.string().optional().meta({ description: "Docker registry hostname (e.g. ghcr.io, code.example.com)" }),
1792
1800
  registryNamespace: z.string().optional().meta({ description: "Docker registry namespace (e.g. ghcr.io/myorg, code.example.com/myorg)" }),
1793
- releaseAssets: z.array(ReleaseAssetSchema).optional().meta({ description: "Custom assets to build and upload to the release" }),
1801
+ releaseAssets: z.array(ReleaseAssetSchema$1).optional().meta({ description: "Custom assets to build and upload to the release" }),
1794
1802
  versionStamp: z.array(VersionStampSchema).optional().meta({ description: "Files release:assets stamps with the release version before building assets, and verifies afterward. For a repo whose released artifact carries its version somewhere other than package.json (e.g. a WordPress theme's style.css Version: header). Fails loudly when a file's prefix/suffix does not match exactly one line." }),
1803
+ snapshot: SnapshotConfigSchema.optional().meta({ description: "Snapshot channel: a push to the default branch that cuts no real release gets a prerelease <version>-<preid>.<build> per listed package, built with the release-assets machinery and uploaded as a prerelease, pruning all but the newest `keep` per package." }),
1795
1804
  postReleaseHook: z.string().optional().meta({ description: "Override the post-release hook command (default: POST to POST_RELEASE_HOOK_URL with HMAC-SHA256 auth)" }),
1796
1805
  postReleaseHookSecrets: z.array(z.string()).optional().meta({ description: "Additional secret names to inject as env vars in the post-release hook step (e.g. ['WEBHOOK_SECRET'])" }),
1797
1806
  coverage: z.union([z.literal(false), CoverageConfigSchema]).optional().meta({ description: "Coverage tracking configuration. Set to false to disable; omit for default-on (when a vitest config is present)." }),
@@ -1832,8 +1841,9 @@ const TolerantToolingConfigSchema = z.object({
1832
1841
  lint: tolerantBlock(LintConfigSchema).optional(),
1833
1842
  agent: TolerantAgentConfigSchema.optional(),
1834
1843
  branchPrune: tolerantBlock(BranchPruneConfigSchema).optional(),
1835
- releaseAssets: z.array(tolerantBlock(ReleaseAssetSchema)).optional(),
1844
+ releaseAssets: z.array(tolerantBlock(ReleaseAssetSchema$1)).optional(),
1836
1845
  versionStamp: z.array(tolerantBlock(VersionStampSchema)).optional(),
1846
+ snapshot: tolerantBlock(SnapshotConfigSchema).optional(),
1837
1847
  issues: tolerantBlock(IssuesConfigSchema).optional(),
1838
1848
  egress: tolerantBlock(EgressConfigSchema).optional()
1839
1849
  });
@@ -3148,6 +3158,22 @@ function createRealExecutor$1(logger = rootLogger) {
3148
3158
  return [];
3149
3159
  }
3150
3160
  },
3161
+ globFiles(cwd, patterns) {
3162
+ const found = /* @__PURE__ */ new Set();
3163
+ for (const pattern of patterns) {
3164
+ let matches;
3165
+ try {
3166
+ matches = globSync(pattern, {
3167
+ cwd,
3168
+ withFileTypes: true
3169
+ });
3170
+ } catch {
3171
+ continue;
3172
+ }
3173
+ for (const entry of matches) if (entry.isFile()) found.add(path.join(entry.parentPath, entry.name));
3174
+ }
3175
+ return [...found];
3176
+ },
3151
3177
  readFile(filePath) {
3152
3178
  try {
3153
3179
  return readFileSync(filePath, "utf-8");
@@ -3267,14 +3293,14 @@ function parseReleaseVersion(version) {
3267
3293
  prerelease: match[4] === void 0 ? [] : match[4].split(".")
3268
3294
  };
3269
3295
  }
3270
- function isPrerelease(version) {
3296
+ function isPrerelease$1(version) {
3271
3297
  return (parseReleaseVersion(version)?.prerelease.length ?? 0) > 0;
3272
3298
  }
3273
3299
  const TRAILING_TAG_VERSION = /(?:^|[^\d.])(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+[0-9A-Za-z.-]+)?$/u;
3274
3300
  function tagIsPrerelease(tag) {
3275
3301
  const version = TRAILING_TAG_VERSION.exec(tag)?.[1];
3276
3302
  if (version === void 0) return false;
3277
- return isPrerelease(version);
3303
+ return isPrerelease$1(version);
3278
3304
  }
3279
3305
  function comparePrereleaseIdentifier(a, b) {
3280
3306
  const aNumeric = /^\d+$/.test(a);
@@ -3352,7 +3378,7 @@ function highestVersionAtSha(family, remote, sha) {
3352
3378
  function planFloatingTagMoves(family, version, remote) {
3353
3379
  const targetSha = remote.get(family.exact(version))?.commit;
3354
3380
  const planned = [];
3355
- if (isPrerelease(version)) {
3381
+ if (isPrerelease$1(version)) {
3356
3382
  for (const tag of family.floating(version)) {
3357
3383
  const observed = remote.get(tag);
3358
3384
  planned.push({
@@ -4193,7 +4219,7 @@ function runDockerBuild(executor, config) {
4193
4219
  }
4194
4220
  function tagAndPushPackage(executor, config, pkg, outcome) {
4195
4221
  const version = pkg.version ?? "";
4196
- const prerelease = isPrerelease(version);
4222
+ const prerelease = isPrerelease$1(version);
4197
4223
  const tags = generateTags(version);
4198
4224
  const exactTag = exactImageTag(version);
4199
4225
  const exactRef = imageRef(config.registryNamespace, pkg.imageName, exactTag);
@@ -4803,6 +4829,7 @@ function buildWorkflowYaml(options) {
4803
4829
  ...def["continue-on-error"] && { "continue-on-error": true },
4804
4830
  "runs-on": def.runsOn ?? runnerExpr("vars.BST_RUNNER || 'ubuntu-latest'"),
4805
4831
  ...def.env && { env: def.env },
4832
+ ...def.outputs && { outputs: def.outputs },
4806
4833
  steps: def.steps.map((s) => s.step)
4807
4834
  };
4808
4835
  doc["jobs"] = jobs;
@@ -4992,7 +5019,7 @@ const PostReleaseHookSchema = z.object({
4992
5019
  postReleaseHook: z.string().optional(),
4993
5020
  postReleaseHookSecrets: z.array(z.string()).optional()
4994
5021
  });
4995
- const ReleaseAssetsSchema = z.object({ releaseAssets: z.array(ReleaseAssetSchema).optional() });
5022
+ const ReleaseAssetsSchema = z.object({ releaseAssets: z.array(ReleaseAssetSchema$1).optional() });
4996
5023
  const VersionStampConfigSchema = z.object({ versionStamp: z.array(VersionStampSchema).optional() });
4997
5024
  const DeploySchema = z.object({ deploy: DeployConfigSchema.optional() });
4998
5025
  function getDeployConfig(ctx) {
@@ -5806,7 +5833,7 @@ function buildManagedDevDeps(ctx) {
5806
5833
  const devDeps = { ...rootDevDeps(ctx.config) };
5807
5834
  if (!isMonorepo) Object.assign(devDeps, perPackageDevDeps(ctx.config));
5808
5835
  if (ctx.config.stack !== "none") devDeps["@bensandee/config"] = isWorkspacePackage(ctx, "@bensandee/config") ? "workspace:*" : "0.15.1";
5809
- if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.105.0";
5836
+ if (!isWorkspacePackage(ctx, "@bensandee/tooling")) devDeps["@bensandee/tooling"] = "0.106.0";
5810
5837
  if (ctx.config.useEslintPlugin && ctx.config.stack !== "none") devDeps["@bensandee/eslint-plugin"] = isWorkspacePackage(ctx, "@bensandee/eslint-plugin") ? "workspace:*" : "0.18.0";
5811
5838
  if (wantsAgentCli(ctx)) devDeps[AGENT_CLI_PACKAGE] = "0.3.2";
5812
5839
  if (ctx.config.formatter === "oxfmt") devDeps["oxfmt"] = {
@@ -6259,9 +6286,10 @@ const PackageEntrySchema = z.object({
6259
6286
  const CoverageBaselineSchema = z.object({
6260
6287
  totals: TotalsSchema,
6261
6288
  packages: z.record(z.string(), PackageEntrySchema),
6262
- scope: z.literal("include").optional()
6289
+ scope: z.literal("include")
6263
6290
  });
6264
6291
  const CoverageRecordSchema = CoverageBaselineSchema.extend({
6292
+ scope: z.literal("include").optional(),
6265
6293
  sha: z.string(),
6266
6294
  timestamp: z.string()
6267
6295
  });
@@ -7244,11 +7272,24 @@ async function deleteTag(executor, conn, tag) {
7244
7272
  resource: tag
7245
7273
  }));
7246
7274
  }
7247
- z.looseObject({
7275
+ const TagSchema = z.looseObject({
7248
7276
  name: z.string(),
7249
7277
  id: z.string(),
7250
7278
  commit: z.object({ sha: z.string().regex(/^[0-9a-f]{40}$/) })
7251
7279
  });
7280
+ async function getTagCommit(executor, conn, tag) {
7281
+ const encodedTag = encodeURIComponent(tag);
7282
+ const url = `${conn.serverUrl}/api/v1/repos/${conn.repository}/tags/${encodedTag}`;
7283
+ const res = await executor.fetch(url, { headers: { Authorization: `token ${conn.token}` } });
7284
+ if (res.status === 404) return null;
7285
+ if (!res.ok) throw new TransientError(await forgejoErrorMessage(res, {
7286
+ verb: "read tag",
7287
+ resource: tag
7288
+ }));
7289
+ const parsed = TagSchema.safeParse(await res.json());
7290
+ if (!parsed.success) throw new UnexpectedError(`Unexpected tag response: ${parsed.error.message}`);
7291
+ return parsed.data.commit.sha;
7292
+ }
7252
7293
  async function deleteRelease(executor, conn, releaseId) {
7253
7294
  const url = `${conn.serverUrl}/api/v1/repos/${conn.repository}/releases/${String(releaseId)}`;
7254
7295
  const res = await executor.fetch(url, {
@@ -7371,6 +7412,31 @@ async function settleBackoff(attempt, baseDelayMs) {
7371
7412
  const delay = Math.min(baseDelayMs * 2 ** (attempt - 1), SETTLE_MAX_DELAY_MS);
7372
7413
  await new Promise((resolve) => setTimeout(resolve, delay));
7373
7414
  }
7415
+ const ReleaseAssetSchema = z.object({
7416
+ id: z.number(),
7417
+ name: z.string()
7418
+ });
7419
+ const UploadReleaseRowSchema = z.object({
7420
+ id: z.number(),
7421
+ assets: z.array(ReleaseAssetSchema).nullish()
7422
+ });
7423
+ async function deleteReleaseAssetsNamed(executor, conn, release, tag, assetName) {
7424
+ for (const asset of release.assets ?? []) {
7425
+ if (asset.name !== assetName) continue;
7426
+ const url = `${conn.serverUrl}/api/v1/repos/${conn.repository}/releases/${String(release.id)}/assets/${String(asset.id)}`;
7427
+ const res = await executor.fetch(url, {
7428
+ method: "DELETE",
7429
+ headers: { Authorization: `token ${conn.token}` }
7430
+ });
7431
+ if (!res.ok) {
7432
+ const detail = await forgejoErrorMessage(res, {
7433
+ verb: "delete asset",
7434
+ resource: `${assetName} on ${tag}`
7435
+ });
7436
+ throw new TransientError(`Cannot replace asset ${assetName} on ${tag}: the forge refused to delete the existing copy (asset ${String(asset.id)}, HTTP ${String(res.status)}).\n${detail}`);
7437
+ }
7438
+ }
7439
+ }
7374
7440
  async function uploadReleaseAsset(executor, conn, tag, options) {
7375
7441
  const encodedTag = encodeURIComponent(tag);
7376
7442
  const releaseUrl = `${conn.serverUrl}/api/v1/repos/${conn.repository}/releases/tags/${encodedTag}`;
@@ -7379,9 +7445,11 @@ async function uploadReleaseAsset(executor, conn, tag, options) {
7379
7445
  verb: "get release",
7380
7446
  resource: tag
7381
7447
  }));
7382
- const parsed = z.object({ id: z.number() }).safeParse(await releaseRes.json());
7448
+ const parsed = UploadReleaseRowSchema.safeParse(await releaseRes.json());
7383
7449
  if (!parsed.success) throw new UnexpectedError(`Unexpected release response: ${parsed.error.message}`);
7384
- const releaseId = parsed.data.id;
7450
+ const release = parsed.data;
7451
+ const releaseId = release.id;
7452
+ if (options.replace) await deleteReleaseAssetsNamed(executor, conn, release, tag, options.assetName);
7385
7453
  const uploadUrl = `${conn.serverUrl}/api/v1/repos/${conn.repository}/releases/${String(releaseId)}/assets?name=${encodeURIComponent(options.assetName)}`;
7386
7454
  const form = new FormData();
7387
7455
  form.append("attachment", new Blob([new Uint8Array(options.fileBuffer)]), options.assetName);
@@ -7395,7 +7463,9 @@ async function uploadReleaseAsset(executor, conn, tag, options) {
7395
7463
  resource: `${options.assetName} to ${tag}`
7396
7464
  }));
7397
7465
  }
7398
- z.looseObject({
7466
+ const LIST_PAGE_SIZE = 50;
7467
+ const LIST_MAX_PAGES = 20;
7468
+ const ReleaseListRowSchema = z.looseObject({
7399
7469
  id: z.number(),
7400
7470
  tag_name: z.string(),
7401
7471
  name: z.string().nullish(),
@@ -7413,6 +7483,68 @@ z.looseObject({
7413
7483
  created: z.string().nullish()
7414
7484
  })
7415
7485
  });
7486
+ async function readListPages(executor, conn, path, options, all) {
7487
+ const rows = [];
7488
+ const stopAt = all ? Number.POSITIVE_INFINITY : options.limit;
7489
+ const pageSize = Math.min(Math.max(options.limit, 1), LIST_PAGE_SIZE);
7490
+ for (let page = 1; page <= LIST_MAX_PAGES && rows.length < stopAt; page++) {
7491
+ const params = new URLSearchParams({
7492
+ page: String(page),
7493
+ limit: String(pageSize)
7494
+ });
7495
+ const url = `${conn.serverUrl}/api/v1/repos/${conn.repository}/${path}?${params.toString()}`;
7496
+ const res = await executor.fetch(url, { headers: { Authorization: `token ${conn.token}` } });
7497
+ if (!res.ok) throw new TransientError(await forgejoErrorMessage(res, {
7498
+ verb: `list ${path}`,
7499
+ resource: conn.repository
7500
+ }));
7501
+ const body = await res.json();
7502
+ if (!Array.isArray(body)) throw new UnexpectedError(`Unexpected ${path} list response: not an array`);
7503
+ if (body.length === 0) break;
7504
+ rows.push(...body);
7505
+ }
7506
+ return rows;
7507
+ }
7508
+ async function listReleases(executor, conn, options) {
7509
+ const parsed = ReleaseListRowSchema.array().safeParse(await readListPages(executor, conn, "releases", options, false));
7510
+ if (!parsed.success) throw new UnexpectedError(`Unexpected release list response: ${parsed.error.message}`);
7511
+ const rows = parsed.data.slice(0, options.limit);
7512
+ return Promise.all(rows.map(async (row) => ({
7513
+ tag: row.tag_name,
7514
+ name: row.name ?? row.tag_name,
7515
+ commitSha: await getTagCommit(executor, conn, row.tag_name),
7516
+ target: row.target_commitish ?? null,
7517
+ createdAt: row.created_at ?? null,
7518
+ url: row.html_url ?? null,
7519
+ draft: row.draft ?? false,
7520
+ prerelease: row.prerelease ?? false,
7521
+ assetCount: row.assets?.length ?? 0
7522
+ })));
7523
+ }
7524
+ // src/release/publish/release-tag.ts
7525
+ function releaseTag(pkg) {
7526
+ if (pkg.root) return `v${pkg.version}`;
7527
+ return `${pkg.name}@${pkg.version}`;
7528
+ }
7529
+ const TAG_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]*)?$/;
7530
+ function parseReleaseTag(tag, rootName) {
7531
+ if (tag.startsWith("v") && rootName !== null) {
7532
+ const version = tag.slice(1);
7533
+ if (TAG_VERSION.test(version)) return {
7534
+ packageName: rootName,
7535
+ version
7536
+ };
7537
+ }
7538
+ const at = tag.lastIndexOf("@");
7539
+ if (at > 0) {
7540
+ const version = tag.slice(at + 1);
7541
+ if (TAG_VERSION.test(version)) return {
7542
+ packageName: tag.slice(0, at),
7543
+ version
7544
+ };
7545
+ }
7546
+ return null;
7547
+ }
7416
7548
  // src/release/publish/version-of-record.ts
7417
7549
  const FOREIGN_VERSION_FILES = [{
7418
7550
  file: "Cargo.toml",
@@ -7498,26 +7630,53 @@ function stampContent(content, entry, version) {
7498
7630
  return joinLines(split);
7499
7631
  }
7500
7632
  // src/release/publish/assets.ts
7633
+ function releaseContextEnv(context) {
7634
+ return {
7635
+ RELEASE_VERSION: context.version,
7636
+ RELEASE_TAG: context.tag,
7637
+ RELEASE_PRERELEASE: String(context.prerelease),
7638
+ RELEASE_BUILD_NUMBER: context.buildNumber
7639
+ };
7640
+ }
7501
7641
  const CONVENTION_SCRIPT = "build:release-assets";
7502
7642
  const CONVENTION_OUTPUT_DIR = "release-assets";
7503
- function configuredTargets(cwd, toolingConfig) {
7504
- return (toolingConfig?.releaseAssets ?? []).map((asset) => ({
7505
- commandCwd: cwd,
7506
- command: asset.command,
7507
- files: [{
7508
- path: path.resolve(cwd, asset.file),
7509
- ...asset.name && { name: asset.name }
7510
- }]
7511
- }));
7643
+ function configuredTargets(cwd, toolingConfig, rootName) {
7644
+ return (toolingConfig?.releaseAssets ?? []).map((asset) => {
7645
+ const owner = asset.package ?? rootName;
7646
+ if (asset.file === void 0 === (asset.files === void 0)) throw new FatalError(`releaseAssets entry must set exactly one of file and files: ${JSON.stringify(asset)}`);
7647
+ if (asset.file === void 0) {
7648
+ const patterns = asset.files ?? [];
7649
+ return {
7650
+ owner,
7651
+ commandCwd: cwd,
7652
+ command: asset.command,
7653
+ files: [],
7654
+ globs: patterns,
7655
+ label: `files ${JSON.stringify(patterns)}`
7656
+ };
7657
+ }
7658
+ return {
7659
+ owner,
7660
+ commandCwd: cwd,
7661
+ command: asset.command,
7662
+ files: [{
7663
+ path: path.resolve(cwd, asset.file),
7664
+ ...asset.name && { name: asset.name }
7665
+ }],
7666
+ label: `file ${asset.file}`
7667
+ };
7668
+ });
7512
7669
  }
7513
- function conventionTargets(executor, cwd) {
7670
+ function conventionTargets(executor, cwd, rootName) {
7514
7671
  const targets = [];
7515
- const checkDir = (relDir) => {
7672
+ const checkDir = (relDir, isRoot) => {
7516
7673
  const absDir = path.resolve(cwd, relDir);
7517
7674
  const raw = executor.readFile(path.join(absDir, "package.json"));
7518
7675
  if (!raw) return;
7519
- if (!parsePackageJson(raw)?.scripts?.[CONVENTION_SCRIPT]) return;
7676
+ const pkg = parsePackageJson(raw);
7677
+ if (!pkg?.scripts?.[CONVENTION_SCRIPT]) return;
7520
7678
  targets.push({
7679
+ owner: isRoot || rootName !== null ? rootName : pkg.name ?? null,
7521
7680
  commandCwd: absDir,
7522
7681
  command: [
7523
7682
  "pnpm",
@@ -7528,10 +7687,24 @@ function conventionTargets(executor, cwd) {
7528
7687
  collectFromDir: path.join(absDir, CONVENTION_OUTPUT_DIR)
7529
7688
  });
7530
7689
  };
7531
- checkDir(".");
7532
- for (const dir of executor.listPackageDirs(cwd)) checkDir(path.join("packages", dir));
7690
+ checkDir(".", true);
7691
+ for (const dir of executor.listPackageDirs(cwd)) checkDir(path.join("packages", dir), false);
7533
7692
  return targets;
7534
7693
  }
7694
+ function allTargets(executor, cwd, toolingConfig, rootName) {
7695
+ return [...configuredTargets(cwd, toolingConfig, rootName), ...conventionTargets(executor, cwd, rootName)];
7696
+ }
7697
+ function isMonorepoRepo$1(executor, cwd, toolingConfig) {
7698
+ if (toolingConfig?.structure !== void 0) return toolingConfig.structure === "monorepo";
7699
+ return executor.readFile(path.join(cwd, "pnpm-workspace.yaml")) !== null;
7700
+ }
7701
+ function rootPackageName(executor, cwd) {
7702
+ const raw = executor.readFile(path.join(cwd, "package.json"));
7703
+ return (raw === null ? void 0 : parsePackageJson(raw))?.name ?? "";
7704
+ }
7705
+ function ownedTargets(executor, cwd, toolingConfig, packageName, isMonorepo) {
7706
+ return allTargets(executor, cwd, toolingConfig, isMonorepo ? null : rootPackageName(executor, cwd)).filter((target) => target.owner === packageName);
7707
+ }
7535
7708
  function resolveStampVersion(executor, cwd) {
7536
7709
  const pkgPath = path.join(cwd, "package.json");
7537
7710
  const raw = executor.readFile(pkgPath);
@@ -7540,8 +7713,7 @@ function resolveStampVersion(executor, cwd) {
7540
7713
  if (!pkg?.version) throw new FatalError(`release:assets could not find a "version" field in package.json at ${pkgPath}. versionStamp needs a version to stamp.`);
7541
7714
  return pkg.version;
7542
7715
  }
7543
- function stampVersionFiles(executor, cwd, toolingConfig, version) {
7544
- const entries = toolingConfig?.versionStamp ?? [];
7716
+ function stampVersionFiles(executor, cwd, entries, version) {
7545
7717
  const stamped = [];
7546
7718
  for (const entry of entries) {
7547
7719
  const filePath = path.resolve(cwd, entry.file);
@@ -7565,27 +7737,53 @@ function verifyStamp(executor, stamped) {
7565
7737
  if (matches !== 1) throw new FatalError(`versionStamp verify failed for ${filePath}: expected exactly one line "${expectedLine}" after the build, found ${matches}. The build likely overwrote the stamp -- check for a script that regenerates or copies over this file.`);
7566
7738
  }
7567
7739
  }
7568
- function runVersionStampPhase(executor, config) {
7569
- if ((config.toolingConfig?.versionStamp ?? []).length === 0) return [];
7570
- const conflict = detectForeignVersionOfRecord(config.cwd);
7571
- if (conflict) throw new FatalError(`release:assets stamps package.json's version into versionStamp files, but this repo's version-of-record is ${conflict}. A stamp would carry a version the ${conflict} artifact never gets. Release this repo through its own toolchain, or remove the versionStamp block.`);
7572
- const version = resolveStampVersion(executor, config.cwd);
7573
- return stampVersionFiles(executor, config.cwd, config.toolingConfig, version);
7740
+ function refuseForeignVersionOfRecord(cwd) {
7741
+ const conflict = detectForeignVersionOfRecord(cwd);
7742
+ if (conflict) throw new FatalError(`bst stamps package.json's version into versionStamp files, but this repo's version-of-record is ${conflict}. A stamp would carry a version the ${conflict} artifact never gets. Release this repo through its own toolchain, or remove the versionStamp block.`);
7574
7743
  }
7575
- function runBuild(executor, target, config) {
7744
+ function stampOwnedVersionFiles(executor, cwd, toolingConfig, context, isMonorepo) {
7745
+ const rootName = isMonorepo ? null : rootPackageName(executor, cwd);
7746
+ const owned = (toolingConfig?.versionStamp ?? []).filter((entry) => stampOwner(entry, rootName) === context.packageName);
7747
+ if (owned.length === 0) return [];
7748
+ refuseForeignVersionOfRecord(cwd);
7749
+ return stampVersionFiles(executor, cwd, owned, context.version);
7750
+ }
7751
+ function stampWithRootVersion(executor, cwd, entries) {
7752
+ if (entries.length === 0) return [];
7753
+ return stampVersionFiles(executor, cwd, entries, resolveStampVersion(executor, cwd));
7754
+ }
7755
+ function runBuild(executor, target, context, opts) {
7576
7756
  if (!target.command || target.command.length === 0) return;
7577
7757
  const [file, ...args] = target.command;
7578
7758
  if (!file) return;
7579
- const label = target.commandCwd === config.cwd ? "root" : path.relative(config.cwd, target.commandCwd);
7759
+ const label = target.commandCwd === opts.cwd ? "root" : path.relative(opts.cwd, target.commandCwd);
7580
7760
  log$1.info(`Building assets in ${label}: ${target.command.join(" ")}`);
7581
- executor.execInherit(file, args, { cwd: target.commandCwd });
7582
- debug(config, `Asset build completed for ${label}`);
7761
+ const options = context === null ? { cwd: target.commandCwd } : {
7762
+ cwd: target.commandCwd,
7763
+ env: releaseContextEnv(context)
7764
+ };
7765
+ executor.execInherit(file, args, options);
7766
+ debug(opts, `Asset build completed for ${label}`);
7583
7767
  }
7584
7768
  function collectFromDir(executor, target) {
7585
- if (!target.collectFromDir) return;
7586
- const before = target.files.length;
7587
- for (const entry of executor.listFiles(target.collectFromDir)) target.files.push({ path: path.join(target.collectFromDir, entry) });
7588
- if (target.files.length === before) throw new FatalError(`${CONVENTION_SCRIPT} ran in ${target.commandCwd} but emitted no files to ${target.collectFromDir}. Update your script to write artifacts there, or declare assets explicitly via releaseAssets in .tooling.json.`);
7769
+ if (!target.collectFromDir) return [];
7770
+ const files = executor.listFiles(target.collectFromDir).map((entry) => ({ path: path.join(target.collectFromDir ?? "", entry) }));
7771
+ if (files.length === 0) throw new FatalError(`${CONVENTION_SCRIPT} ran in ${target.commandCwd} but emitted no files to ${target.collectFromDir}. Update your script to write artifacts there, or declare assets explicitly via releaseAssets in .tooling.json.`);
7772
+ return files;
7773
+ }
7774
+ function collectFromGlobs(executor, cwd, target) {
7775
+ if (!target.globs) return [];
7776
+ const matches = executor.globFiles(cwd, target.globs);
7777
+ if (matches.length === 0) throw new FatalError(`releaseAssets entry with ${target.label ?? "globs"} matched no files under ${cwd} after its build ran. Check the glob and where the build writes its output.`);
7778
+ return matches.map((match) => ({ path: match }));
7779
+ }
7780
+ function buildTargets(executor, targets, context, opts) {
7781
+ const built = [];
7782
+ for (const target of targets) {
7783
+ runBuild(executor, target, context, opts);
7784
+ built.push(...target.files, ...collectFromDir(executor, target), ...collectFromGlobs(executor, opts.cwd, target));
7785
+ }
7786
+ return built;
7589
7787
  }
7590
7788
  function uploadToGitHub(executor, config, tag, asset) {
7591
7789
  const assetName = asset.name ?? path.basename(asset.path);
@@ -7610,48 +7808,106 @@ async function uploadToForgejo(executor, conn, tag, asset) {
7610
7808
  });
7611
7809
  log$1.info(`Uploaded ${assetName} to ${tag} (Forgejo)`);
7612
7810
  }
7613
- async function runReleaseAssets(executor, config) {
7614
- debug(config, `Config: dryRun=${String(config.dryRun)} cwd=${config.cwd}`);
7615
- const targets = [...configuredTargets(config.cwd, config.toolingConfig), ...conventionTargets(executor, config.cwd)];
7616
- const stampedFiles = runVersionStampPhase(executor, config);
7617
- for (const target of targets) {
7618
- runBuild(executor, target, config);
7619
- collectFromDir(executor, target);
7620
- }
7621
- verifyStamp(executor, stampedFiles);
7622
- if (targets.length === 0) {
7623
- log$1.info(`No release assets configured in .tooling.json or by convention (${CONVENTION_SCRIPT} script)`);
7624
- return;
7625
- }
7626
- if (config.dryRun) {
7627
- log$1.info("[dry-run] Skipping upload");
7628
- return;
7629
- }
7630
- if (!config.platform) throw new FatalError("Platform connection is required for asset upload");
7811
+ function isPrerelease(version) {
7812
+ const [core = ""] = version.split("+");
7813
+ return core.includes("-");
7814
+ }
7815
+ async function findReleasesAtHead(executor, config, rootName) {
7631
7816
  const tagResult = executor.exec("git", [
7632
7817
  "tag",
7633
7818
  "--points-at",
7634
7819
  "HEAD"
7635
7820
  ], { cwd: config.cwd });
7636
7821
  debugExec(config, "git tag --points-at HEAD", tagResult);
7637
- if (tagResult.exitCode !== 0) throw new FatalError("Could not determine current tags");
7638
- const tags = tagResult.stdout.trim().split("\n").filter(Boolean);
7639
- if (tags.length === 0) {
7640
- log$1.info("No tags pointing to HEAD, skipping upload");
7641
- return;
7822
+ if (tagResult.exitCode !== 0) {
7823
+ if (config.dryRun) return [];
7824
+ throw new FatalError("Could not determine current tags");
7642
7825
  }
7643
- let uploaded = 0;
7826
+ const tags = tagResult.stdout.trim().split("\n").filter(Boolean);
7827
+ const buildNumber = process.env["GITHUB_RUN_NUMBER"] ?? "";
7828
+ const releases = [];
7644
7829
  for (const tag of tags) {
7645
- if (!await releaseExists(executor, config, tag)) {
7830
+ if (!config.dryRun && !await releaseExists(executor, config, tag)) {
7646
7831
  log$1.info(`No release found for ${tag}, skipping (likely a sliding tag)`);
7647
7832
  continue;
7648
7833
  }
7649
- log$1.info(`Uploading assets to release ${tag}`);
7650
- for (const target of targets) for (const asset of target.files) if (config.platform.type === "github") uploadToGitHub(executor, config, tag, asset);
7651
- else await uploadToForgejo(executor, config.platform.conn, tag, asset);
7652
- uploaded++;
7834
+ const parsed = parseReleaseTag(tag, rootName);
7835
+ const context = parsed === null ? null : {
7836
+ ...parsed,
7837
+ tag,
7838
+ prerelease: isPrerelease(parsed.version),
7839
+ buildNumber
7840
+ };
7841
+ releases.push({
7842
+ tag,
7843
+ context
7844
+ });
7845
+ }
7846
+ return releases;
7847
+ }
7848
+ async function uploadFiles(executor, config, tag, files) {
7849
+ if (config.dryRun) {
7850
+ log$1.info(`[dry-run] Skipping upload to ${tag}`);
7851
+ return;
7852
+ }
7853
+ if (!config.platform) throw new FatalError("Platform connection is required for asset upload");
7854
+ log$1.info(`Uploading assets to release ${tag}`);
7855
+ for (const asset of files) if (config.platform.type === "github") uploadToGitHub(executor, config, tag, asset);
7856
+ else await uploadToForgejo(executor, config.platform.conn, tag, asset);
7857
+ }
7858
+ async function runReleaseAssets(executor, config) {
7859
+ debug(config, `Config: dryRun=${String(config.dryRun)} cwd=${config.cwd}`);
7860
+ const isMonorepo = isMonorepoRepo$1(executor, config.cwd, config.toolingConfig);
7861
+ const rootName = isMonorepo ? null : rootPackageName(executor, config.cwd);
7862
+ const targets = allTargets(executor, config.cwd, config.toolingConfig, rootName);
7863
+ const stampEntries = config.toolingConfig?.versionStamp ?? [];
7864
+ if (targets.length === 0 && stampEntries.length === 0) {
7865
+ log$1.info(`No release assets configured in .tooling.json or by convention (${CONVENTION_SCRIPT} script)`);
7866
+ return;
7867
+ }
7868
+ if (stampEntries.length > 0) refuseForeignVersionOfRecord(config.cwd);
7869
+ if (!config.dryRun && !config.platform && targets.length > 0) throw new FatalError("Platform connection is required for asset upload");
7870
+ const releases = await findReleasesAtHead(executor, config, rootName);
7871
+ const plan = {
7872
+ targets,
7873
+ stampEntries,
7874
+ isMonorepo,
7875
+ releases
7876
+ };
7877
+ if (releases.every((release) => release.context === null)) {
7878
+ await buildOnceForEveryRelease(executor, config, plan, null);
7879
+ return;
7880
+ }
7881
+ await buildPerPackageRelease(executor, config, plan);
7882
+ const unowned = {
7883
+ ...plan,
7884
+ targets: targets.filter((target) => target.owner === null),
7885
+ stampEntries: stampEntries.filter((entry) => stampOwner(entry, rootName) === null)
7886
+ };
7887
+ if (unowned.targets.length === 0 && unowned.stampEntries.length === 0) return;
7888
+ await buildOnceForEveryRelease(executor, config, unowned, (releases.length === 1 ? releases[0] : void 0)?.context ?? null);
7889
+ }
7890
+ function stampOwner(entry, rootName) {
7891
+ return entry.package ?? rootName;
7892
+ }
7893
+ async function buildOnceForEveryRelease(executor, config, plan, context) {
7894
+ const stamped = stampWithRootVersion(executor, config.cwd, plan.stampEntries);
7895
+ const files = buildTargets(executor, plan.targets, context, config);
7896
+ verifyStamp(executor, stamped);
7897
+ if (plan.releases.length === 0) log$1.info("No release found at HEAD, skipping upload");
7898
+ for (const release of plan.releases) await uploadFiles(executor, config, release.tag, files);
7899
+ }
7900
+ async function buildPerPackageRelease(executor, config, plan) {
7901
+ for (const release of plan.releases) {
7902
+ const context = release.context;
7903
+ if (context === null) continue;
7904
+ const owned = plan.targets.filter((target) => target.owner === context.packageName);
7905
+ const stamped = stampOwnedVersionFiles(executor, config.cwd, config.toolingConfig, context, plan.isMonorepo);
7906
+ if (owned.length === 0 && stamped.length === 0) continue;
7907
+ const files = buildTargets(executor, owned, context, config);
7908
+ verifyStamp(executor, stamped);
7909
+ await uploadFiles(executor, config, release.tag, files);
7653
7910
  }
7654
- if (uploaded === 0) log$1.info("No releases found for any tag pointing to HEAD, skipping upload");
7655
7911
  }
7656
7912
  async function releaseExists(executor, config, tag) {
7657
7913
  if (!config.platform) return false;
@@ -7880,7 +8136,7 @@ function deployDispatchStep(opts) {
7880
8136
  env: {
7881
8137
  ...opts.releaseEnv,
7882
8138
  ...secretsEnv(opts.secrets),
7883
- RELEASE_TAG: actionsExpr("steps.release.outputs.tag")
8139
+ RELEASE_TAG: opts.releaseTagExpr
7884
8140
  },
7885
8141
  run: command
7886
8142
  } };
@@ -8032,6 +8288,7 @@ async function generateReleaseCi(ctx) {
8032
8288
  deploy,
8033
8289
  packageName: ctx.config.name,
8034
8290
  releaseEnv: connectionEnv(ctx.config.ci),
8291
+ releaseTagExpr: actionsExpr("steps.release.outputs.tag"),
8035
8292
  condition: "steps.release.outputs.pushed == 'true'",
8036
8293
  secrets: hookSecrets
8037
8294
  }));
@@ -8199,6 +8456,26 @@ function checkSteps(ci, coverageEnabled, emitDockerSweepStep) {
8199
8456
  function ciWorkflowPath(ci, releaseStrategy) {
8200
8457
  return `${ci === "github" ? ".github/workflows" : ".forgejo/workflows"}/${releaseStrategy === "changesets" ? "ci.yml" : "check.yml"}`;
8201
8458
  }
8459
+ const SnapshotSliceSchema = z.object({ snapshot: SnapshotConfigSchema.optional() });
8460
+ function snapshotJob(defaultBranch, ci, releaseEnv) {
8461
+ return {
8462
+ needs: "check",
8463
+ if: onlyOnDefaultBranch(defaultBranch, "needs.check.outputs.published != 'true'"),
8464
+ runsOn: actionsExpr(TRUSTED_RUNNER_EXPR),
8465
+ outputs: {
8466
+ published: actionsExpr("steps.snapshot.outputs.published"),
8467
+ version: actionsExpr("steps.snapshot.outputs.version"),
8468
+ tag: actionsExpr("steps.snapshot.outputs.tag"),
8469
+ packages: actionsExpr("steps.snapshot.outputs.packages")
8470
+ },
8471
+ steps: [...commonSteps(ci), { step: {
8472
+ id: "snapshot",
8473
+ name: "Snapshot release",
8474
+ env: releaseEnv,
8475
+ run: "pnpm exec bst release:snapshot"
8476
+ } }]
8477
+ };
8478
+ }
8202
8479
  async function generateCi(ctx) {
8203
8480
  if (ctx.config.ci === "none") return {
8204
8481
  filePath: "ci",
@@ -8222,14 +8499,16 @@ async function generateCi(ctx) {
8222
8499
  const host = hasDocker ? resolveGenTimeHost(ctx) : null;
8223
8500
  const publishedIf = "steps.release.outputs.published == 'true'";
8224
8501
  const publishedOnDefaultIf = onlyOnDefaultBranch(defaultBranch, publishedIf);
8502
+ const publishedTagJq = ctx.config.structure === "monorepo" ? ".[0] | \"\\(.name)@\\(.version)\"" : ".[0] | \"v\\(.version)\"";
8225
8503
  const githubChangesetsDeriveTagStep = { step: {
8226
8504
  name: "Derive release tag",
8227
8505
  id: "derive-tag",
8228
8506
  if: publishedIf,
8229
8507
  env: { PUBLISHED_PACKAGES: actionsExpr("steps.release.outputs.publishedPackages") },
8230
- run: "echo \"tag=$(echo \"$PUBLISHED_PACKAGES\" | jq -r '.[0] | \"\\(.name)@\\(.version)\"')\" >> \"$GITHUB_OUTPUT\""
8508
+ run: `echo "tag=$(echo "$PUBLISHED_PACKAGES" | jq -r '${publishedTagJq}')" >> "$GITHUB_OUTPUT"\necho "version=\$(echo "\$PUBLISHED_PACKAGES" | jq -r '.[0].version')" >> "\$GITHUB_OUTPUT"`
8231
8509
  } };
8232
8510
  const changesetsTagOutputExpr = isGitHub ? actionsExpr("steps.derive-tag.outputs.tag") : actionsExpr("steps.release.outputs.tag");
8511
+ const changesetsVersionOutputExpr = isGitHub ? actionsExpr("steps.derive-tag.outputs.version") : actionsExpr("steps.release.outputs.version");
8233
8512
  const releaseEnv = {};
8234
8513
  if (isGitHub) releaseEnv["GITHUB_TOKEN"] = actionsExpr("secrets.RELEASE_TOKEN");
8235
8514
  else {
@@ -8260,6 +8539,7 @@ async function generateCi(ctx) {
8260
8539
  deploy,
8261
8540
  packageName: ctx.config.name,
8262
8541
  releaseEnv,
8542
+ releaseTagExpr: changesetsTagOutputExpr,
8263
8543
  condition: publishedOnDefaultIf,
8264
8544
  secrets: hookSecrets
8265
8545
  })] : []
@@ -8269,7 +8549,8 @@ async function generateCi(ctx) {
8269
8549
  if (isChangesets) {
8270
8550
  jobOutputs = {
8271
8551
  published: actionsExpr("steps.release.outputs.published"),
8272
- tag: changesetsTagOutputExpr
8552
+ tag: changesetsTagOutputExpr,
8553
+ version: changesetsVersionOutputExpr
8273
8554
  };
8274
8555
  extraJobs = { "post-release-hook": postReleaseHookJob({
8275
8556
  defaultBranch,
@@ -8281,6 +8562,7 @@ async function generateCi(ctx) {
8281
8562
  command: hookCommand,
8282
8563
  secrets: hookSecrets
8283
8564
  }) };
8565
+ if (parseToolingConfigSlice(ctx.read(".tooling.json"), SnapshotSliceSchema, { block: "snapshot" })?.snapshot) extraJobs["snapshot"] = snapshotJob(defaultBranch, ctx.config.ci, { ...releaseEnv });
8284
8566
  }
8285
8567
  const checkJobEnv = emitCoverageSteps || emitHealthHistory ? defaultBranchJobEnv(defaultBranch) : {};
8286
8568
  const checksSlice = parseToolingConfigSlice(ctx.read(".tooling.json"), z.object({ checks: ChecksConfigSchema.optional() }), { block: "checks" });
@@ -8994,7 +9276,7 @@ async function generateReleaseIt(ctx) {
8994
9276
  };
8995
9277
  }
8996
9278
  // src/generators/release/changesets.ts
8997
- function buildConfig$2(defaultBranch) {
9279
+ function buildConfig$2(defaultBranch, privateRoot) {
8998
9280
  return {
8999
9281
  $schema: "https://unpkg.com/@changesets/config@3.1.1/schema.json",
9000
9282
  changelog: "@changesets/cli/changelog",
@@ -9004,7 +9286,11 @@ function buildConfig$2(defaultBranch) {
9004
9286
  access: "public",
9005
9287
  baseBranch: defaultBranch,
9006
9288
  updateInternalDependencies: "patch",
9007
- ignore: []
9289
+ ignore: [],
9290
+ ...privateRoot ? { privatePackages: {
9291
+ version: true,
9292
+ tag: true
9293
+ } } : {}
9008
9294
  };
9009
9295
  }
9010
9296
  async function generateChangesets(ctx) {
@@ -9014,9 +9300,9 @@ async function generateChangesets(ctx) {
9014
9300
  action: "skipped",
9015
9301
  description: "Changesets not requested"
9016
9302
  };
9017
- const content = JSON.stringify(buildConfig$2(configuredDefaultBranch(ctx.read(".tooling.json"))), null, 2) + "\n";
9018
- const existing = ctx.read(filePath);
9019
- if (existing) return {
9303
+ const privateRoot = ctx.config.structure !== "monorepo" && ctx.packageJson?.private === true;
9304
+ const content = JSON.stringify(buildConfig$2(configuredDefaultBranch(ctx.read(".tooling.json")), privateRoot), null, 2) + "\n";
9305
+ if (ctx.read(filePath)) return {
9020
9306
  filePath,
9021
9307
  action: "skipped",
9022
9308
  description: "Existing changesets config preserved"
@@ -9024,7 +9310,7 @@ async function generateChangesets(ctx) {
9024
9310
  ctx.write(filePath, content);
9025
9311
  return {
9026
9312
  filePath,
9027
- action: existing ? "updated" : "created",
9313
+ action: "created",
9028
9314
  description: "Generated .changeset/config.json"
9029
9315
  };
9030
9316
  }
@@ -10441,7 +10727,7 @@ function reportFailures(failed, command) {
10441
10727
  function generateMigratePrompt(results, config, detected) {
10442
10728
  const sections = [];
10443
10729
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
10444
- sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.105.0 repo:sync\` on ${timestamp}_\n`);
10730
+ sections.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.106.0 repo:sync\` on ${timestamp}_\n`);
10445
10731
  const changed = results.filter((r) => r.action === "created" || r.action === "updated" || r.action === "archived");
10446
10732
  if (changed.length > 0) {
10447
10733
  const items = changed.map((r) => {
@@ -12655,6 +12941,91 @@ function runVersionStampGate(config, targetDir, releaseStrategy) {
12655
12941
  }
12656
12942
  return offenders;
12657
12943
  }
12944
+ function describeAssetEntry(entry, index) {
12945
+ const named = entry.file ?? (entry.files === void 0 ? "" : entry.files.join(", "));
12946
+ return named === "" ? `releaseAssets[${String(index)}]` : `releaseAssets[${String(index)}] ("${named}")`;
12947
+ }
12948
+ function runSnapshotConfigGate(config, targetDir, structure) {
12949
+ let offenders = 0;
12950
+ const releaseAssets = config?.releaseAssets ?? [];
12951
+ for (const [index, entry] of releaseAssets.entries()) {
12952
+ if (entry.file === void 0 !== (entry.files === void 0)) continue;
12953
+ log$1.error(`.tooling.json ${describeAssetEntry(entry, index)} sets ${entry.file === void 0 ? "neither" : "both"} file and files. Exactly one names the asset: keep file for a single path, or files for the globs the build writes.`);
12954
+ offenders++;
12955
+ }
12956
+ const snapshot = config?.snapshot;
12957
+ if (!snapshot) return offenders;
12958
+ const knownPackages = getMonorepoPackages(targetDir).map((pkg) => pkg.name);
12959
+ if (structure !== "monorepo") {
12960
+ const rootName = readPackageJson(targetDir)?.name;
12961
+ if (rootName !== void 0) knownPackages.push(rootName);
12962
+ }
12963
+ const listed = snapshot.packages;
12964
+ if ((listed === void 0 || listed.length === 0) && structure === "monorepo") {
12965
+ log$1.error(`.tooling.json#snapshot is set on a monorepo but names no packages, and bst will not choose them for you: most monorepos have packages nobody installs from a snapshot. List the ones to snapshot under snapshot.packages. This repo has: ${knownPackages.length === 0 ? "none under packages/" : knownPackages.join(", ")}.`);
12966
+ offenders++;
12967
+ }
12968
+ for (const name of listed ?? []) {
12969
+ if (knownPackages.includes(name)) continue;
12970
+ log$1.error(`.tooling.json#snapshot.packages names "${name}", which has no package.json behind it. release:snapshot resolves every name to a package directory, and would fail mid-publish over this one. Fix the name or drop it. This repo has: ${knownPackages.join(", ")}.`);
12971
+ offenders++;
12972
+ }
12973
+ if (structure !== "monorepo") return offenders;
12974
+ for (const [index, entry] of releaseAssets.entries()) {
12975
+ if (entry.package !== void 0) continue;
12976
+ log$1.error(`.tooling.json ${describeAssetEntry(entry, index)} names no package, but snapshot is set on a monorepo and a snapshot is cut per package, so it must know which package this asset serves. Set package to the package it serves (this repo has: ${knownPackages.join(", ")}).`);
12977
+ offenders++;
12978
+ }
12979
+ for (const [index, entry] of (config?.versionStamp ?? []).entries()) {
12980
+ if (entry.package !== void 0) continue;
12981
+ log$1.error(`.tooling.json versionStamp[${String(index)}] ("${entry.file}") names no package, but snapshot is set on a monorepo and a stamp carries the version of the release it belongs to. Set package to the package whose release it stamps (this repo has: ${knownPackages.join(", ")}).`);
12982
+ offenders++;
12983
+ }
12984
+ return offenders;
12985
+ }
12986
+ const ChangesetPrivatePackagesSchema = z.looseObject({ privatePackages: z.union([z.boolean(), z.looseObject({
12987
+ version: z.boolean().optional(),
12988
+ tag: z.boolean().optional()
12989
+ })]).optional() });
12990
+ function changesetsTagsPrivatePackages(targetDir) {
12991
+ const configPath = path.join(targetDir, ".changeset", "config.json");
12992
+ if (!existsSync(configPath)) return void 0;
12993
+ let data;
12994
+ try {
12995
+ data = JSON.parse(readFileSync(configPath, "utf-8"));
12996
+ } catch (_error) {
12997
+ return;
12998
+ }
12999
+ const parsed = ChangesetPrivatePackagesSchema.safeParse(data);
13000
+ if (!parsed.success) return void 0;
13001
+ const privatePackages = parsed.data.privatePackages;
13002
+ if (privatePackages === void 0) return false;
13003
+ if (typeof privatePackages === "boolean") return privatePackages;
13004
+ return privatePackages.tag === true;
13005
+ }
13006
+ function runPrivateReleaseAdvisory(config, saved, targetDir) {
13007
+ if (config.ci !== "github" || config.releaseStrategy !== "changesets") return [];
13008
+ const messages = [];
13009
+ const tagFix = "Set \"privatePackages\": { \"version\": true, \"tag\": true } in .changeset/config.json";
13010
+ if (config.structure === "monorepo") {
13011
+ if (changesetsTagsPrivatePackages(targetDir) === true) return [];
13012
+ const workspacePackages = getMonorepoPackages(targetDir);
13013
+ for (const name of saved?.snapshot?.packages ?? []) {
13014
+ const pkg = workspacePackages.find((candidate) => candidate.name === name);
13015
+ if (pkg === void 0 || readPackageJson(pkg.dir)?.private !== true) continue;
13016
+ const message = `.tooling.json#snapshot.packages names "${name}", whose package.json is private. Its snapshots ship, because bst cuts them itself, but changesets skips a private package, so its stable releases never will. ${tagFix}, or drop "${name}" from snapshot.packages.`;
13017
+ log$1.warn(message);
13018
+ messages.push(message);
13019
+ }
13020
+ return messages;
13021
+ }
13022
+ if (readPackageJson(targetDir)?.private !== true) return [];
13023
+ if (changesetsTagsPrivatePackages(targetDir) !== false) return [];
13024
+ const message = `The root package is private, and .changeset/config.json never turns privatePackages.tag on, so changesets skips it: this repo versions nothing, tags nothing and publishes nothing. ${tagFix}, or drop "private": true from package.json.`;
13025
+ log$1.warn(message);
13026
+ messages.push(message);
13027
+ return messages;
13028
+ }
12658
13029
  function warnStaleChecksAdd(config) {
12659
13030
  const stale = staleChecksAddNames(config);
12660
13031
  if (stale.length === 0) return;
@@ -12839,7 +13210,7 @@ const syncCommand = defineCommand({
12839
13210
  },
12840
13211
  json: {
12841
13212
  type: "boolean",
12842
- description: "Emit one JSON document: status (up-to-date | drift | workflow-drift | failed), actionable, failed, checkOnlyImages, aptSteps, inertAgentKeys, warnCount, exitCode. --check only: the write mode prompts and inherits child streams."
13213
+ description: "Emit one JSON document: status (up-to-date | drift | workflow-drift | failed), actionable, failed, checkOnlyImages, aptSteps, inertAgentKeys, privateRelease, warnCount, exitCode. --check only: the write mode prompts and inherits child streams."
12843
13214
  }
12844
13215
  },
12845
13216
  async run({ args }) {
@@ -12904,6 +13275,15 @@ async function runUpdateReport(targetDir, flags = {}, options = {}) {
12904
13275
  const config = mergeWithSavedConfig(buildDefaultConfig(targetDir, flags), saved);
12905
13276
  runReleaseTargetGate(config, targetDir);
12906
13277
  runVersionStampGate(saved, targetDir, config.releaseStrategy);
13278
+ if (runSnapshotConfigGate(saved, targetDir, config.structure) > 0) {
13279
+ process.exitCode = 1;
13280
+ return {
13281
+ status: "stopped",
13282
+ results: [],
13283
+ install: "not-run"
13284
+ };
13285
+ }
13286
+ runPrivateReleaseAdvisory(config, saved, targetDir);
12907
13287
  if (runPublishConfigGate(config, targetDir) > 0) {
12908
13288
  process.exitCode = 1;
12909
13289
  return {
@@ -12933,12 +13313,13 @@ function gateFailure() {
12933
13313
  checkOnlyImages: [],
12934
13314
  aptSteps: [],
12935
13315
  inertAgentKeys: [],
13316
+ privateRelease: [],
12936
13317
  warnCount: 0,
12937
13318
  exitCode: 1
12938
13319
  };
12939
13320
  }
12940
13321
  function advisoryWarnCount(advisories) {
12941
- return advisories.checkOnlyImages.length + advisories.aptSteps.length + (advisories.inertAgentKeys.length > 0 ? 1 : 0);
13322
+ return advisories.checkOnlyImages.length + advisories.aptSteps.length + advisories.privateRelease.length + (advisories.inertAgentKeys.length > 0 ? 1 : 0);
12942
13323
  }
12943
13324
  function upToDateReport(advisories) {
12944
13325
  const warnCount = advisoryWarnCount(advisories);
@@ -12952,6 +13333,7 @@ function upToDateReport(advisories) {
12952
13333
  checkOnlyImages: advisories.checkOnlyImages,
12953
13334
  aptSteps: advisories.aptSteps,
12954
13335
  inertAgentKeys: advisories.inertAgentKeys,
13336
+ privateRelease: advisories.privateRelease,
12955
13337
  warnCount,
12956
13338
  exitCode: 0
12957
13339
  };
@@ -12969,12 +13351,14 @@ async function runCheckReport(targetDir) {
12969
13351
  const config = saved ? mergeWithSavedConfig(detected, saved) : detected;
12970
13352
  if (runReleaseTargetGate(config, targetDir)) return gateFailure();
12971
13353
  if (runVersionStampGate(saved, targetDir, config.releaseStrategy) > 0) return gateFailure();
13354
+ if (runSnapshotConfigGate(saved, targetDir, config.structure) > 0) return gateFailure();
12972
13355
  if (runPublishConfigGate(config, targetDir) > 0) return gateFailure();
12973
13356
  if (runToolchainGate(targetDir) > 0) return gateFailure();
12974
13357
  const advisories = {
12975
13358
  checkOnlyImages: runCheckOnlyImageGate(config, targetDir, dockerDiscovery),
12976
13359
  aptSteps: runWorkflowAptGate(targetDir),
12977
- inertAgentKeys: runInertAgentSettingsGate(saved)
13360
+ inertAgentKeys: runInertAgentSettingsGate(saved),
13361
+ privateRelease: runPrivateReleaseAdvisory(config, saved, targetDir)
12978
13362
  };
12979
13363
  const { ctx, pendingWrites } = createDryRunContext(config, dockerDiscovery);
12980
13364
  logDetectionSummary(ctx);
@@ -12991,6 +13375,7 @@ async function runCheckReport(targetDir) {
12991
13375
  checkOnlyImages: [],
12992
13376
  aptSteps: [],
12993
13377
  inertAgentKeys: [],
13378
+ privateRelease: [],
12994
13379
  warnCount: 0,
12995
13380
  exitCode: 1
12996
13381
  };
@@ -13006,6 +13391,7 @@ async function runCheckReport(targetDir) {
13006
13391
  checkOnlyImages: advisories.checkOnlyImages,
13007
13392
  aptSteps: advisories.aptSteps,
13008
13393
  inertAgentKeys: advisories.inertAgentKeys,
13394
+ privateRelease: advisories.privateRelease,
13009
13395
  warnCount,
13010
13396
  exitCode: 0
13011
13397
  };
@@ -13017,6 +13403,7 @@ async function runCheckReport(targetDir) {
13017
13403
  checkOnlyImages: [],
13018
13404
  aptSteps: [],
13019
13405
  inertAgentKeys: [],
13406
+ privateRelease: [],
13020
13407
  warnCount: 0,
13021
13408
  exitCode: 1
13022
13409
  };
@@ -13127,6 +13514,7 @@ async function findOpenPr(executor, conn, head, signal = null) {
13127
13514
  const PullListItemSchema = z.object({
13128
13515
  number: z.number(),
13129
13516
  title: z.string().nullish(),
13517
+ body: z.string().nullish(),
13130
13518
  head: z.object({
13131
13519
  ref: z.string(),
13132
13520
  repo: z.object({ full_name: z.string() }).nullish()
@@ -13174,6 +13562,7 @@ async function listPulls(executor, conn, options = {}) {
13174
13562
  const items = parsed.data.map((pr) => ({
13175
13563
  number: pr.number,
13176
13564
  title: pr.title ?? null,
13565
+ body: pr.body ?? null,
13177
13566
  headRef: pr.head.ref,
13178
13567
  headRepo: pr.head.repo?.full_name ?? null,
13179
13568
  baseRef: pr.base?.ref ?? null,
@@ -13456,7 +13845,6 @@ function readRootPackage(executor, cwd) {
13456
13845
  if (!content) return null;
13457
13846
  const pkg = parsePackageJson(content);
13458
13847
  if (!pkg?.name || !pkg.version) return null;
13459
- if (pkg.private) return null;
13460
13848
  return {
13461
13849
  name: pkg.name,
13462
13850
  version: pkg.version
@@ -13730,7 +14118,7 @@ function floatingFamilies(packages, remoteSet, pushedTags) {
13730
14118
  function prereleaseTag(families, tag) {
13731
14119
  for (const entry of families) {
13732
14120
  const version = entry.family.versionOfExact(tag);
13733
- if (version !== void 0) return isPrerelease(version);
14121
+ if (version !== void 0) return isPrerelease$1(version);
13734
14122
  }
13735
14123
  return false;
13736
14124
  }
@@ -13785,7 +14173,7 @@ async function runPublishMode(executor, config, bumped) {
13785
14173
  family: changesetsTagFamily(p.name),
13786
14174
  version: p.version
13787
14175
  }));
13788
- const bumpedPrerelease = new Map(bumped.map((p) => [p.tag, isPrerelease(p.version)]));
14176
+ const bumpedPrerelease = new Map(bumped.map((p) => [p.tag, isPrerelease$1(p.version)]));
13789
14177
  function prereleaseFor(tag) {
13790
14178
  const own = bumpedPrerelease.get(tag);
13791
14179
  if (own !== void 0) return own;
@@ -13924,7 +14312,11 @@ function readBumpedSet(executor, config) {
13924
14312
  bumped.push({
13925
14313
  name: after.name,
13926
14314
  version,
13927
- tag: candidate.root ? `v${version}` : `${after.name}@${version}`,
14315
+ tag: releaseTag({
14316
+ name: after.name,
14317
+ version,
14318
+ root: candidate.root
14319
+ }),
13928
14320
  private: after.private ?? false,
13929
14321
  access: readAccess(after.publishConfig)
13930
14322
  });
@@ -14061,12 +14453,19 @@ const releaseForgejoCommand = defineCommand({
14061
14453
  const outputFile = process.env["GITHUB_OUTPUT"];
14062
14454
  if (outputFile) try {
14063
14455
  const tag = result.tags[0] ?? "";
14064
- appendFileSync(outputFile, `published=true\ntag=${tag}\n`);
14456
+ appendFileSync(outputFile, `published=true\ntag=${tag}\nversion=${versionFromTag(tag)}\n`);
14065
14457
  } catch (_error) {}
14066
14458
  }
14067
14459
  if (result.mode === "none") process.exitCode = 0;
14068
14460
  }
14069
14461
  });
14462
+ function versionFromTag(tag) {
14463
+ if (tag === "") return "";
14464
+ if (tag.startsWith("v") && !tag.includes("@")) return tag.slice(1);
14465
+ const at = tag.lastIndexOf("@");
14466
+ if (at <= 0) return "";
14467
+ return tag.slice(at + 1);
14468
+ }
14070
14469
  function releasePayload(result, dryRun) {
14071
14470
  if (result.mode === "version") return {
14072
14471
  mode: "version",
@@ -18571,6 +18970,30 @@ function walkUnits(text, boxes) {
18571
18970
  if (section !== void 0) return section.index;
18572
18971
  return loneBoxUnit;
18573
18972
  };
18973
+ const walkHeading = (heading, index) => {
18974
+ const level = (heading[1] ?? "").length;
18975
+ while (open.length > 0 && (open[open.length - 1]?.level ?? 0) >= level) open.pop();
18976
+ loneBoxUnit = null;
18977
+ const headingText = (heading[2] ?? "").trim();
18978
+ const label = taskLabelId(headingText);
18979
+ if (label === null) {
18980
+ unitAtLine[index] = inEffect();
18981
+ return;
18982
+ }
18983
+ const unit = {
18984
+ key: headingText,
18985
+ task: planTask(headingText, label),
18986
+ boxes: []
18987
+ };
18988
+ const unitIndex = units.length;
18989
+ units.push(unit);
18990
+ open.push({
18991
+ level,
18992
+ unit,
18993
+ index: unitIndex
18994
+ });
18995
+ unitAtLine[index] = unitIndex;
18996
+ };
18574
18997
  for (const [index, rawLine] of lines.entries()) {
18575
18998
  const line = rawLine ?? "";
18576
18999
  if (fenced[index] === true) {
@@ -18579,28 +19002,7 @@ function walkUnits(text, boxes) {
18579
19002
  }
18580
19003
  const heading = HEADING.exec(line);
18581
19004
  if (heading !== null) {
18582
- const level = (heading[1] ?? "").length;
18583
- while (open.length > 0 && (open[open.length - 1]?.level ?? 0) >= level) open.pop();
18584
- loneBoxUnit = null;
18585
- const headingText = (heading[2] ?? "").trim();
18586
- const label = taskLabelId(headingText);
18587
- if (label === null) {
18588
- unitAtLine[index] = inEffect();
18589
- continue;
18590
- }
18591
- const unit = {
18592
- key: headingText,
18593
- task: planTask(headingText, label),
18594
- boxes: []
18595
- };
18596
- const unitIndex = units.length;
18597
- units.push(unit);
18598
- open.push({
18599
- level,
18600
- unit,
18601
- index: unitIndex
18602
- });
18603
- unitAtLine[index] = unitIndex;
19005
+ walkHeading(heading, index);
18604
19006
  continue;
18605
19007
  }
18606
19008
  const box = boxAtLine.get(index);
@@ -19059,7 +19461,7 @@ function issueFacts(issue) {
19059
19461
  url: issue.url
19060
19462
  };
19061
19463
  }
19062
- async function resolveTarget(git, forge, defaultBranch, ref, checkoutHead) {
19464
+ async function resolveTarget$1(git, forge, defaultBranch, ref, checkoutHead) {
19063
19465
  const resolved = {
19064
19466
  kind: ref === null ? "branch" : "issue",
19065
19467
  branch: null,
@@ -19326,7 +19728,7 @@ async function commitsSection({ git, resolved }) {
19326
19728
  }
19327
19729
  async function buildWorkStatus(deps, ref) {
19328
19730
  const { git, forge, docsExtraDirs, defaultBranch, agentLogin, checkoutHead = false } = deps;
19329
- const resolved = await resolveTarget(git, forge, defaultBranch, ref, checkoutHead);
19731
+ const resolved = await resolveTarget$1(git, forge, defaultBranch, ref, checkoutHead);
19330
19732
  const forgeDown = resolved.failed ?? resolved.forgeDown;
19331
19733
  const inputs = {
19332
19734
  git,
@@ -21026,7 +21428,7 @@ async function runSimpleRelease(executor, config) {
21026
21428
  if (!tag) throw new FatalError("Could not determine the new tag from git describe");
21027
21429
  log$1.info(`Version ${version} tagged as ${tag}`);
21028
21430
  if (config.dryRun) {
21029
- const prerelease = isPrerelease(version);
21431
+ const prerelease = isPrerelease$1(version);
21030
21432
  let slidingTags = [];
21031
21433
  if (!config.noSlidingTags && !prerelease) slidingTags = computeSlidingTags(version);
21032
21434
  log$1.info(`[dry-run] Would push to origin with --follow-tags`);
@@ -21112,7 +21514,7 @@ async function createPlatformRelease(executor, config, tag, version) {
21112
21514
  const target = resolveTagCommit(executor, config.cwd, tag);
21113
21515
  const { status: releaseStatus } = await ensureRelease(executor, config.platform.conn, tag, {
21114
21516
  target,
21115
- prerelease: isPrerelease(version)
21517
+ prerelease: isPrerelease$1(version)
21116
21518
  });
21117
21519
  if (releaseStatus === "exists") {
21118
21520
  debug(config, `Release for ${tag} already exists, skipping`);
@@ -21127,7 +21529,7 @@ async function createPlatformRelease(executor, config, tag, version) {
21127
21529
  tag,
21128
21530
  "--generate-notes"
21129
21531
  ];
21130
- if (isPrerelease(version)) ghArgs.push("--prerelease");
21532
+ if (isPrerelease$1(version)) ghArgs.push("--prerelease");
21131
21533
  const ghResult = executor.exec("gh", ghArgs, { cwd: config.cwd });
21132
21534
  debugExec(config, "gh release create", ghResult);
21133
21535
  if (ghResult.exitCode !== 0) {
@@ -21262,6 +21664,446 @@ const releaseAssetsCommand = defineCommand({
21262
21664
  await runReleaseAssets(createRealExecutor$1(), config);
21263
21665
  }
21264
21666
  });
21667
+ // src/release/publish/snapshot-forge.ts
21668
+ const LIST_LIMIT = 100;
21669
+ function createSnapshotForge(executor, platform, cwd) {
21670
+ return platform.type === "github" ? githubForge(executor, cwd) : forgejoForge(executor, platform.conn);
21671
+ }
21672
+ function gh(executor, cwd, args, verb) {
21673
+ const result = executor.exec("gh", args, { cwd });
21674
+ if (result.exitCode !== 0) throw new TransientError(`GitHub ${verb} failed (exit ${String(result.exitCode)}):\n${childOutput(result)}`);
21675
+ return result;
21676
+ }
21677
+ const GitHubReleaseListSchema = z.array(z.looseObject({
21678
+ tagName: z.string(),
21679
+ createdAt: z.string().nullish()
21680
+ }));
21681
+ function parseGitHubReleaseList(stdout) {
21682
+ let json;
21683
+ try {
21684
+ json = JSON.parse(stdout);
21685
+ } catch {
21686
+ throw new UnexpectedError(`Unexpected GitHub release list output: ${stdout.slice(0, 200)}`);
21687
+ }
21688
+ const parsed = GitHubReleaseListSchema.safeParse(json);
21689
+ if (!parsed.success) throw new UnexpectedError(`Unexpected GitHub release list response: ${parsed.error.message}`);
21690
+ return parsed.data.map((row) => ({
21691
+ tag: row.tagName,
21692
+ createdAt: row.createdAt ?? null
21693
+ }));
21694
+ }
21695
+ function githubForge(executor, cwd) {
21696
+ return {
21697
+ async releaseExists(tag) {
21698
+ return executor.exec("gh", [
21699
+ "release",
21700
+ "view",
21701
+ tag
21702
+ ], { cwd }).exitCode === 0;
21703
+ },
21704
+ async createPrerelease(tag, options) {
21705
+ gh(executor, cwd, [
21706
+ "release",
21707
+ "create",
21708
+ tag,
21709
+ "--prerelease",
21710
+ "--target",
21711
+ options.target,
21712
+ "--title",
21713
+ tag,
21714
+ "--notes",
21715
+ options.notes
21716
+ ], `release create ${tag}`);
21717
+ log$1.info(`Created prerelease ${tag} (GitHub)`);
21718
+ },
21719
+ async uploadAsset(tag, file) {
21720
+ gh(executor, cwd, [
21721
+ "release",
21722
+ "upload",
21723
+ tag,
21724
+ file.path,
21725
+ "--clobber"
21726
+ ], `release upload ${file.name} to ${tag}`);
21727
+ log$1.info(`Uploaded ${file.name} to ${tag} (GitHub)`);
21728
+ },
21729
+ async listReleases() {
21730
+ return parseGitHubReleaseList(gh(executor, cwd, [
21731
+ "release",
21732
+ "list",
21733
+ "--json",
21734
+ "tagName,createdAt",
21735
+ "--limit",
21736
+ String(LIST_LIMIT)
21737
+ ], "release list").stdout);
21738
+ },
21739
+ async deleteRelease(tag) {
21740
+ gh(executor, cwd, [
21741
+ "release",
21742
+ "delete",
21743
+ tag,
21744
+ "--cleanup-tag",
21745
+ "--yes"
21746
+ ], `release delete ${tag}`);
21747
+ log$1.info(`Deleted ${tag} (GitHub)`);
21748
+ }
21749
+ };
21750
+ }
21751
+ function forgejoForge(executor, conn) {
21752
+ return {
21753
+ async releaseExists(tag) {
21754
+ return findRelease(executor, conn, tag);
21755
+ },
21756
+ async createPrerelease(tag, options) {
21757
+ await createRelease(executor, conn, tag, {
21758
+ prerelease: true,
21759
+ target: options.target,
21760
+ name: tag,
21761
+ body: options.notes
21762
+ });
21763
+ log$1.info(`Created prerelease ${tag} (Forgejo)`);
21764
+ },
21765
+ async uploadAsset(tag, file) {
21766
+ const fileBuffer = executor.readFileBuffer(file.path);
21767
+ if (fileBuffer === null) throw new FatalError(`Snapshot asset file not found: ${file.path}`);
21768
+ await uploadReleaseAsset(executor, conn, tag, {
21769
+ assetName: file.name,
21770
+ fileBuffer,
21771
+ replace: true
21772
+ });
21773
+ log$1.info(`Uploaded ${file.name} to ${tag} (Forgejo)`);
21774
+ },
21775
+ async listReleases() {
21776
+ return (await listReleases(executor, conn, { limit: LIST_LIMIT })).map((row) => ({
21777
+ tag: row.tag,
21778
+ createdAt: row.createdAt
21779
+ }));
21780
+ },
21781
+ async deleteRelease(tag) {
21782
+ const release = await getReleaseByTag(executor, conn, tag);
21783
+ if (release !== null) await deleteRelease(executor, conn, release.id);
21784
+ await deleteTag(executor, conn, tag);
21785
+ log$1.info(`Deleted ${tag} (Forgejo)`);
21786
+ }
21787
+ };
21788
+ }
21789
+ // src/release/publish/snapshot-version.ts
21790
+ const STATUS_FILE = ".bst-changeset-status.json";
21791
+ const ChangesetStatusSchema = z.looseObject({
21792
+ releases: z.array(z.looseObject({
21793
+ name: z.string(),
21794
+ newVersion: z.string()
21795
+ })),
21796
+ changesets: z.array(z.looseObject({
21797
+ summary: z.string(),
21798
+ releases: z.array(z.looseObject({ name: z.string() }))
21799
+ }))
21800
+ });
21801
+ function readChangesetStatus(executor, cwd) {
21802
+ const result = executor.exec("pnpm", [
21803
+ "changeset",
21804
+ "status",
21805
+ "--output",
21806
+ STATUS_FILE
21807
+ ], { cwd });
21808
+ const statusPath = path.join(cwd, STATUS_FILE);
21809
+ try {
21810
+ if (result.exitCode !== 0) throw new FatalError(`\`changeset status\` failed (exit ${String(result.exitCode)}) -- a snapshot needs the version the pending changesets would give, and there is no fallback version:\n` + childOutput(result));
21811
+ const raw = executor.readFile(statusPath);
21812
+ if (raw === null) throw new FatalError(`\`changeset status\` exited zero but wrote no ${STATUS_FILE}:\n` + childOutput(result));
21813
+ const status = parseStatus(raw);
21814
+ if (status === null) throw new FatalError(`\`changeset status\` wrote a ${STATUS_FILE} this run cannot read:\n` + childOutput(result));
21815
+ return status;
21816
+ } finally {
21817
+ executor.removeDir(statusPath);
21818
+ }
21819
+ }
21820
+ function parseStatus(raw) {
21821
+ let json;
21822
+ try {
21823
+ json = JSON.parse(raw);
21824
+ } catch {
21825
+ return null;
21826
+ }
21827
+ const parsed = ChangesetStatusSchema.safeParse(json);
21828
+ return parsed.success ? parsed.data : null;
21829
+ }
21830
+ const SEMVER_CORE = /^(\d+)\.(\d+)\.(\d+)/;
21831
+ function snapshotVersion(input) {
21832
+ return `${input.nextVersion ?? raisePatch(input.currentVersion)}-${input.preid}.${input.build}`;
21833
+ }
21834
+ function raisePatch(currentVersion) {
21835
+ const [major, minor, patch] = SEMVER_CORE.exec(currentVersion)?.slice(1) ?? [];
21836
+ if (major === void 0 || minor === void 0 || patch === void 0) throw new FatalError(`Cannot snapshot ${currentVersion}: it carries no x.y.z core to raise a patch from, and no pending changeset gives this package a next version.`);
21837
+ return `${major}.${minor}.${String(Number(patch) + 1)}`;
21838
+ }
21839
+ // src/release/publish/snapshot.ts
21840
+ const DEFAULT_KEEP = 3;
21841
+ async function runReleaseSnapshot(executor, config) {
21842
+ const settings = readSnapshotSettings(config);
21843
+ const isMonorepo = isMonorepoRepo(executor, config);
21844
+ refuseUnownedEntries(config, isMonorepo);
21845
+ const packages = resolvePackages(executor, config, settings, isMonorepo);
21846
+ const build = resolveBuild(config);
21847
+ const target = resolveTarget(config);
21848
+ const status = readChangesetStatus(executor, config.cwd);
21849
+ debug(config, `Snapshotting ${String(packages.length)} package(s) at build ${build}`);
21850
+ const run = {
21851
+ executor,
21852
+ buildExecutor: config.captureBuildOutput ? capturingExecutor(executor) : executor,
21853
+ forge: config.dryRun ? inertForge() : createRealForge(executor, config),
21854
+ config,
21855
+ status,
21856
+ settings,
21857
+ target,
21858
+ build,
21859
+ isMonorepo
21860
+ };
21861
+ const results = [];
21862
+ let published = !config.dryRun && packages.length > 0;
21863
+ for (const pkg of packages) {
21864
+ const cut = await snapshotPackage(run, pkg);
21865
+ results.push(cut.result);
21866
+ published = published && cut.exists;
21867
+ }
21868
+ const result = {
21869
+ published,
21870
+ packages: results
21871
+ };
21872
+ appendOutputs(executor, config, result);
21873
+ return result;
21874
+ }
21875
+ function readSnapshotSettings(config) {
21876
+ const snapshot = config.toolingConfig?.snapshot;
21877
+ if (snapshot === void 0) throw new FatalError("release:snapshot needs a `snapshot` block in .tooling.json. Its `preid` is the prerelease identifier every snapshot version carries, and bst will not pick one for your channel.");
21878
+ return {
21879
+ preid: snapshot.preid,
21880
+ keep: snapshot.keep ?? DEFAULT_KEEP,
21881
+ packages: snapshot.packages
21882
+ };
21883
+ }
21884
+ function isMonorepoRepo(executor, config) {
21885
+ const structure = config.toolingConfig?.structure;
21886
+ if (structure !== void 0) return structure === "monorepo";
21887
+ return executor.readFile(path.join(config.cwd, "pnpm-workspace.yaml")) !== null;
21888
+ }
21889
+ function refuseUnownedEntries(config, isMonorepo) {
21890
+ if (!isMonorepo) return;
21891
+ const unowned = (config.toolingConfig?.releaseAssets ?? []).filter((entry) => entry.package === void 0);
21892
+ if (unowned.length > 0) {
21893
+ const entry = unowned[0];
21894
+ throw new FatalError(`release:snapshot cannot build a releaseAssets entry that names no package in a monorepo: ${JSON.stringify(entry)}. A snapshot uploads to one package's prerelease, so name the package the entry builds for.`);
21895
+ }
21896
+ const unownedStamp = (config.toolingConfig?.versionStamp ?? []).find((entry) => entry.package === void 0);
21897
+ if (unownedStamp !== void 0) throw new FatalError(`release:snapshot cannot stamp a versionStamp entry that names no package in a monorepo: ${JSON.stringify(unownedStamp)}. A snapshot cuts one version per package, so name the package whose release this entry stamps.`);
21898
+ }
21899
+ function resolvePackages(executor, config, settings, isMonorepo) {
21900
+ if (isMonorepo) {
21901
+ const listed = settings.packages;
21902
+ if (listed === void 0 || listed.length === 0) throw new FatalError("release:snapshot needs `snapshot.packages` in a monorepo: which packages a tester installs is the repo owner's call, and bst does not guess it.");
21903
+ const workspace = executor.listWorkspacePackages(config.cwd);
21904
+ return listed.map((name) => {
21905
+ const found = workspace.find((pkg) => pkg.name === name);
21906
+ if (found === void 0) throw unknownPackageName(name);
21907
+ return {
21908
+ name,
21909
+ currentVersion: found.version,
21910
+ dir: path.join(config.cwd, "packages", found.dir),
21911
+ root: false
21912
+ };
21913
+ });
21914
+ }
21915
+ const root = rootPackage(executor, config.cwd);
21916
+ for (const name of settings.packages ?? []) if (name !== root.name) throw unknownPackageName(name);
21917
+ return [root];
21918
+ }
21919
+ function unknownPackageName(name) {
21920
+ return new FatalError(`snapshot.packages names ${name}, which is not a workspace package of this repo. Spell it as its package.json does.`);
21921
+ }
21922
+ function rootPackage(executor, cwd) {
21923
+ const manifestPath = path.join(cwd, "package.json");
21924
+ const raw = executor.readFile(manifestPath);
21925
+ const pkg = raw === null ? void 0 : parsePackageJson(raw);
21926
+ if (pkg?.name === void 0 || pkg.version === void 0) throw new FatalError(`release:snapshot cannot snapshot the root package: ${manifestPath} carries no name or no version, and a snapshot version is raised from the version it holds.`);
21927
+ return {
21928
+ name: pkg.name,
21929
+ currentVersion: pkg.version,
21930
+ dir: cwd,
21931
+ root: true
21932
+ };
21933
+ }
21934
+ function resolveBuild(config) {
21935
+ const build = process.env["GITHUB_RUN_NUMBER"] ?? config.build;
21936
+ if (build === void 0 || build === "") throw new FatalError("release:snapshot needs a build number: GITHUB_RUN_NUMBER is what a CI job supplies, and outside CI --build <n> is the only source. Two cuts sharing a suffix collide on one tag.");
21937
+ return build;
21938
+ }
21939
+ function resolveTarget(config) {
21940
+ const target = process.env["GITHUB_SHA"] ?? "";
21941
+ if (target === "" && !config.dryRun) throw new FatalError("release:snapshot needs GITHUB_SHA: the prerelease targets the exact commit the job checked out, so the tag names the code it was built from. --dry-run is the only run that may go without it.");
21942
+ return target;
21943
+ }
21944
+ function createRealForge(executor, config) {
21945
+ if (config.platform === void 0) throw new FatalError("Platform connection is required for a snapshot release");
21946
+ return createSnapshotForge(executor, config.platform, config.cwd);
21947
+ }
21948
+ function inertForge() {
21949
+ return {
21950
+ async releaseExists() {
21951
+ return false;
21952
+ },
21953
+ async createPrerelease() {},
21954
+ async uploadAsset() {},
21955
+ async listReleases() {
21956
+ return [];
21957
+ },
21958
+ async deleteRelease() {}
21959
+ };
21960
+ }
21961
+ async function snapshotPackage(run, pkg) {
21962
+ const version = snapshotVersion({
21963
+ currentVersion: pkg.currentVersion,
21964
+ nextVersion: nextVersionFor(run.status, pkg.name),
21965
+ preid: run.settings.preid,
21966
+ build: run.build
21967
+ });
21968
+ const tag = releaseTag({
21969
+ name: pkg.name,
21970
+ version,
21971
+ root: pkg.root
21972
+ });
21973
+ const context = {
21974
+ packageName: pkg.name,
21975
+ version,
21976
+ tag,
21977
+ prerelease: true,
21978
+ buildNumber: run.build
21979
+ };
21980
+ if (run.config.dryRun) {
21981
+ log$1.info(`[dry-run] ${pkg.name} -> ${tag} (no forge call)`);
21982
+ return {
21983
+ result: {
21984
+ name: pkg.name,
21985
+ version,
21986
+ tag
21987
+ },
21988
+ exists: false
21989
+ };
21990
+ }
21991
+ writeWorkingTreeVersion(run, path.join(pkg.dir, "package.json"), version);
21992
+ const stamped = stampOwnedVersionFiles(run.executor, run.config.cwd, run.config.toolingConfig, context, run.isMonorepo);
21993
+ if (await run.forge.releaseExists(tag)) log$1.info(`Prerelease ${tag} already exists, uploading its assets with replacement`);
21994
+ else await run.forge.createPrerelease(tag, {
21995
+ target: run.target,
21996
+ notes: releaseNotes(run.status, pkg.name)
21997
+ });
21998
+ const targets = ownedTargets(run.executor, run.config.cwd, run.config.toolingConfig, pkg.name, run.isMonorepo);
21999
+ const files = buildTargets(run.buildExecutor, targets, context, run.config);
22000
+ verifyStamp(run.executor, stamped);
22001
+ for (const file of files) await run.forge.uploadAsset(tag, {
22002
+ path: file.path,
22003
+ name: file.name ?? path.basename(file.path)
22004
+ });
22005
+ await pruneSnapshots(run.forge, pkg, run.settings);
22006
+ return {
22007
+ result: {
22008
+ name: pkg.name,
22009
+ version,
22010
+ tag
22011
+ },
22012
+ exists: true
22013
+ };
22014
+ }
22015
+ function nextVersionFor(status, packageName) {
22016
+ return status.releases.find((release) => release.name === packageName)?.newVersion ?? null;
22017
+ }
22018
+ function releaseNotes(status, packageName) {
22019
+ return status.changesets.filter((changeset) => changeset.releases.some((release) => release.name === packageName)).map((changeset) => `- ${changeset.summary.trim()}`).join("\n");
22020
+ }
22021
+ function writeWorkingTreeVersion(run, manifestPath, version) {
22022
+ const raw = run.executor.readFile(manifestPath);
22023
+ if (raw === null) throw new FatalError(`Cannot write the snapshot version: ${manifestPath} is not readable.`);
22024
+ run.executor.writeFile(manifestPath, applyEdits(raw, modify(raw, ["version"], version, {})));
22025
+ debug(run.config, `Wrote ${version} into ${manifestPath} (working tree only)`);
22026
+ }
22027
+ async function pruneSnapshots(forge, pkg, settings) {
22028
+ const prefix = pkg.root ? "v" : `${pkg.name}@`;
22029
+ const pattern = new RegExp(`^${escapeRegExp$1(prefix)}\\d+\\.\\d+\\.\\d+-${escapeRegExp$1(settings.preid)}\\.\\d+$`);
22030
+ const rows = (await forge.listReleases()).filter((row) => pattern.test(row.tag)).toSorted(byNewestFirst);
22031
+ for (const row of rows.slice(settings.keep)) await forge.deleteRelease(row.tag);
22032
+ }
22033
+ function escapeRegExp$1(value) {
22034
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22035
+ }
22036
+ function byNewestFirst(a, b) {
22037
+ const left = a.createdAt ?? "";
22038
+ const right = b.createdAt ?? "";
22039
+ if (left === right) return 0;
22040
+ return left < right ? 1 : -1;
22041
+ }
22042
+ function capturingExecutor(executor) {
22043
+ return {
22044
+ ...executor,
22045
+ execInherit(file, args, options) {
22046
+ const result = executor.exec(file, args, options);
22047
+ if (result.exitCode !== 0) throw new FatalError(`Asset build failed (exit ${String(result.exitCode)}):\n${childOutput(result)}`);
22048
+ }
22049
+ };
22050
+ }
22051
+ function appendOutputs(executor, config, result) {
22052
+ const outputFile = process.env["GITHUB_OUTPUT"];
22053
+ if (outputFile === void 0 || outputFile === "") return;
22054
+ const first = result.packages[0];
22055
+ executor.appendFile(outputFile, `published=${String(result.published)}\nversion=${first?.version ?? ""}\ntag=${first?.tag ?? ""}\npackages=${JSON.stringify(result.packages)}\n`);
22056
+ debug(config, `Wrote snapshot outputs to ${outputFile}`);
22057
+ }
22058
+ // src/commands/release/release-snapshot.ts
22059
+ const releaseSnapshotCommand = defineCommand({
22060
+ meta: {
22061
+ name: "release:snapshot",
22062
+ description: "Cut the snapshot-channel prereleases configured in .tooling.json#snapshot: one prerelease per listed package at <version>-<preid>.<build>, with its assets, pruned back to `keep`. Never commits, never moves a floating tag."
22063
+ },
22064
+ args: {
22065
+ build: {
22066
+ type: "string",
22067
+ description: "Build number for the snapshot suffix. Outside CI, where GITHUB_RUN_NUMBER is unset, this is the only source and the command refuses without it"
22068
+ },
22069
+ "dry-run": {
22070
+ type: "boolean",
22071
+ description: "Compute and print the cut; write nothing and call no forge"
22072
+ },
22073
+ json: {
22074
+ type: "boolean",
22075
+ description: "Emit one JSON document: published (boolean) and packages (array of { name, version, tag }). Every key is always present. Asset builds run captured so the document is the only thing on either stream."
22076
+ },
22077
+ verbose: {
22078
+ type: "boolean",
22079
+ description: "Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)"
22080
+ }
22081
+ },
22082
+ async run({ args }) {
22083
+ const out = createCliOutput(args.json === true);
22084
+ const cwd = process.cwd();
22085
+ const dryRun = args["dry-run"] === true;
22086
+ let platform;
22087
+ if (!dryRun) {
22088
+ const resolved = resolveConnection(cwd);
22089
+ platform = resolved.type === "forgejo" ? {
22090
+ type: "forgejo",
22091
+ conn: resolved.conn
22092
+ } : { type: "github" };
22093
+ }
22094
+ const config = {
22095
+ cwd,
22096
+ dryRun,
22097
+ verbose: args.verbose === true || isEnvVerbose(),
22098
+ toolingConfig: loadToolingConfig(cwd),
22099
+ platform,
22100
+ build: args.build,
22101
+ captureBuildOutput: args.json === true
22102
+ };
22103
+ const result = await runReleaseSnapshot(createRealExecutor$1(), config);
22104
+ out.json(result);
22105
+ }
22106
+ });
21265
22107
  // src/lint-types/executor.ts
21266
22108
  function runViaShim(args, cwd) {
21267
22109
  const result = spawnViaShim("pnpm", args, {
@@ -23530,7 +24372,6 @@ function serializeBaseline(baseline) {
23530
24372
  // src/commands/coverage-tracking/coverage-check.ts
23531
24373
  const COVERAGE_SUMMARY_FILE$1 = "coverage/coverage-summary.json";
23532
24374
  const BASELINE_FILE$2 = "coverage-baseline.json";
23533
- const MIGRATION_NOTICE = `${BASELINE_FILE$2} predates coverage.include scoping (no scope marker). Totals may have shifted because previously-untested files entered the denominator for the first time -- that is not necessarily a regression. This comparison is advisory only until the baseline is migrated: run \`pnpm test:coverage && pnpm exec bst coverage:check --update-baseline --reset\` once to adopt the honest, marked baseline. Normal gating resumes after that.`;
23534
24375
  function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23535
24376
  const { reset, floorPp } = options;
23536
24377
  if (reset) {
@@ -23552,7 +24393,7 @@ function applyBaselineUpdate$1(out, baselinePath, baseline, current, options) {
23552
24393
  const coverageCheckCommand = defineCommand({
23553
24394
  meta: {
23554
24395
  name: "coverage:check",
23555
- description: "Compare the latest coverage run against coverage-baseline.json. Exits 1 when a total fails the comparison, except against a baseline that predates coverage.include scoping."
24396
+ description: "Compare the latest coverage run against coverage-baseline.json. Exits 1 when a total fails the comparison."
23556
24397
  },
23557
24398
  args: {
23558
24399
  dir: {
@@ -23567,7 +24408,7 @@ const coverageCheckCommand = defineCommand({
23567
24408
  },
23568
24409
  reset: {
23569
24410
  type: "boolean",
23570
- description: "With --update-baseline, rewrite coverage-baseline.json unconditionally, even when totals dropped. The one-shot migration to adopt an honest coverage.include-scoped baseline: pnpm test:coverage && pnpm exec bst coverage:check --update-baseline --reset."
24411
+ description: "With --update-baseline, rewrite coverage-baseline.json unconditionally, even when totals dropped."
23571
24412
  },
23572
24413
  "fail-on-missing-baseline": {
23573
24414
  type: "boolean",
@@ -23576,7 +24417,7 @@ const coverageCheckCommand = defineCommand({
23576
24417
  },
23577
24418
  json: {
23578
24419
  type: "boolean",
23579
- description: "Emit one JSON document: status (disabled | baseline-created | missing-baseline | compared | migration-notice), reason?, totals?, pass?, tolerancePp?, floorPp?. reason comes only with disabled; totals is {lines, statements, branches, functions} with baseline-created and missing-baseline, and [{key, baseline, current, delta, pass}] after a comparison, which alone carries pass, tolerancePp and floorPp?."
24420
+ description: "Emit one JSON document: status (disabled | baseline-created | missing-baseline | compared), reason?, totals?, pass?, tolerancePp?, floorPp?. reason comes only with disabled; totals is {lines, statements, branches, functions} with baseline-created and missing-baseline, and [{key, baseline, current, delta, pass}] after a comparison, which alone carries pass, tolerancePp and floorPp?."
23580
24421
  }
23581
24422
  },
23582
24423
  run({ args }) {
@@ -23618,18 +24459,16 @@ const coverageCheckCommand = defineCommand({
23618
24459
  }
23619
24460
  const baseline = parseBaseline(readFileSync(baselinePath, "utf-8"));
23620
24461
  const result = compareTotals(baseline.totals, current.totals, config.tolerancePp, config.floorPp);
23621
- const isLegacyBaseline = baseline.scope !== "include";
23622
24462
  out.text(formatCompareDiff$1(result));
23623
- if (isLegacyBaseline) out.notice(MIGRATION_NOTICE);
23624
24463
  out.json({
23625
- status: isLegacyBaseline ? "migration-notice" : "compared",
24464
+ status: "compared",
23626
24465
  ...result
23627
24466
  });
23628
24467
  if (args["update-baseline"] === true) applyBaselineUpdate$1(out, baselinePath, baseline, current, {
23629
24468
  reset: args.reset === true,
23630
24469
  floorPp: config.floorPp
23631
24470
  });
23632
- if (!result.pass && !isLegacyBaseline) process.exitCode = 1;
24471
+ if (!result.pass) process.exitCode = 1;
23633
24472
  }
23634
24473
  });
23635
24474
  // src/commands/coverage-tracking/coverage-record.ts
@@ -30257,7 +31096,7 @@ async function runCli(config) {
30257
31096
  // src/cli-main.ts
30258
31097
  setLogLevel(resolveLogLevel({}));
30259
31098
  setForgejoLogger(log$1);
30260
- const displayVersion = "0.105.0";
31099
+ const displayVersion = "0.106.0";
30261
31100
  const bstSubCommands = {
30262
31101
  "repo:sync": syncCommand,
30263
31102
  "checks:run": runChecksCommand,
@@ -30274,6 +31113,7 @@ const bstSubCommands = {
30274
31113
  "pr:update": prUpdateCommand,
30275
31114
  "release:simple": releaseSimpleCommand,
30276
31115
  "release:assets": releaseAssetsCommand,
31116
+ "release:snapshot": releaseSnapshotCommand,
30277
31117
  "docker:publish": publishDockerCommand,
30278
31118
  "docker:build": dockerBuildCommand,
30279
31119
  "docker:check": dockerCheckCommand,