// Pure helpers for `scripts/promote-release.ts`, which checks a release before the promotion // workflow moves `latest` to it. All registry and file I/O lives in that script. import { ignoresLevels, parseVersion, releaseOfRootVersion, tagOfLevel, } from '../packages/0-shared/publish-surface/src/release-plan.ts'; import { wasEverGa } from './publish-packages-utils.mjs'; export interface ReleasePackage { readonly name: string; readonly version: string; } export interface RegistryState { readonly versions: readonly string[]; readonly latest: string | undefined; /** When each version was published, as an ISO date: the registry's `time` field. */ readonly published: Readonly>; } export interface Move extends ReleasePackage { readonly from: string | undefined; /** The move takes `latest` to an older version than the one it is on. */ readonly back: boolean; } export interface Promotion { /** Packages whose `latest` moves to the release's version. */ readonly moves: readonly Move[]; /** Packages whose `latest` is already at the release's version. */ readonly unchanged: readonly ReleasePackage[]; /** Packages the release put under their level's tag, whose `latest` stays where it is. */ readonly leveled: readonly (ReleasePackage & { readonly tag: string })[]; } /** What the promote job moves: every package the release puts under `latest`. */ export interface PromotionPlan { readonly version: string; readonly packages: readonly ReleasePackage[]; } export class PromotionError extends Error {} const EMPTY: RegistryState = { versions: [], latest: undefined, published: {} }; /** * A package's state from the output of a registry `view versions dist-tags time --json`. * A package the registry does not have is empty; any other failure stops the promotion. */ export function registryStateFrom( name: string, result: { status: number | null; stdout: string; stderr: string }, ): RegistryState { if (result.status !== 0) { if (/E404|404 Not Found/.test(`${result.stdout}${result.stderr}`)) return EMPTY; throw new PromotionError(`Could not read ${name} from the registry:\n${result.stderr}`); } if (result.stdout.trim() === '') return EMPTY; const view: { versions?: string | string[]; 'dist-tags'?: Record; time?: Record; } = JSON.parse(result.stdout); const versions = view.versions ?? []; return { versions: Array.isArray(versions) ? versions : [versions], latest: view['dist-tags']?.latest, published: view.time ?? {}, }; } /** Why the release data checked out cannot be the release asked for, or `undefined` when it is. */ export function releaseRootMismatch(rootVersion: string, requested: string): string | undefined { if (rootVersion === requested) return undefined; return `The release data is release ${rootVersion}, not ${requested}. Check out the release's tag, v${requested}, as the release data, and run again.`; } /** * Semantic Versioning precedence of two `X.Y.Z` or `X.Y.Z-pre.release` versions: negative when `a` * sorts below `b`. */ export function compareVersions(a: string, b: string): number { const [left, right] = [a, b].map(semverParts); for (let index = 0; index < 3; index++) { const difference = (left?.core[index] ?? 0) - (right?.core[index] ?? 0); if (difference !== 0) return difference; } const [leftPre, rightPre] = [left?.pre ?? [], right?.pre ?? []]; if (leftPre.length === 0 || rightPre.length === 0) return rightPre.length - leftPre.length; for (let index = 0; index < Math.min(leftPre.length, rightPre.length); index++) { const difference = compareIdentifiers(leftPre[index] ?? '', rightPre[index] ?? ''); if (difference !== 0) return difference; } return leftPre.length - rightPre.length; } function semverParts(version: string): { core: number[]; pre: string[] } { const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version); if (match === null) throw new PromotionError(`"${version}" is not a version`); return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] === undefined ? [] : match[4].split('.'), }; } function compareIdentifiers(a: string, b: string): number { const [aNumeric, bNumeric] = [/^\d+$/.test(a), /^\d+$/.test(b)]; if (aNumeric && bNumeric) return Number(a) - Number(b); if (aNumeric !== bNumeric) return aNumeric ? -1 : 1; return a < b ? -1 : a > b ? 1 : 0; } function isDevelopmentBuild(version: string): boolean { return /-dev\.\d+$/.test(version); } /** * The tag the release gave a package, from data that does not change after the release: the * package's level, which its version holds, and whether it had a GA version published before * this one. On the release candidates every package is under `latest`. */ export function releaseTagOf( rootVersion: string, pkg: ReleasePackage, state: RegistryState, ): string { if (ignoresLevels(releaseOfRootVersion(rootVersion))) return 'latest'; const level = parseVersion(pkg.version).level?.name ?? 'ga'; const publishedAt = state.published[pkg.version]; const earlier = state.versions.filter((version) => { const at = state.published[version]; return publishedAt === undefined || (at !== undefined && at < publishedAt); }); return tagOfLevel(level, wasEverGa(earlier)); } /** * What promoting a release does to each package. A package the release put under `latest` moves * `latest` to its version; one under its level's tag is left alone. Refuses, naming them, when * any package's version is not on the registry, so a promotion changes all packages or none, and * when a move takes `latest` back to an older version, unless `allowDowngrade`. A `latest` on a * development build is not a release, so moving off it is never a move back. */ export function planPromotion(options: { rootVersion: string; packages: readonly ReleasePackage[]; registry: ReadonlyMap; allowDowngrade: boolean; }): Promotion { const packages = [...options.packages].sort((a, b) => (a.name < b.name ? -1 : 1)); const stateOf = (name: string) => options.registry.get(name) ?? EMPTY; const missing = packages.filter(({ name, version }) => !stateOf(name).versions.includes(version)); if (missing.length > 0) { throw new PromotionError( [ 'These packages are not on the registry at the release version, so latest moves for none of them:', ...missing.map(({ name, version }) => ` ${name}@${version}`), 'If the release was published only minutes ago, the registry may still be catching up: wait a few minutes and run again.', 'Otherwise publish the release first: rerun its "Publish to npm" run, or dispatch that workflow from main with dist-tag=next and dry-run=false.', ].join('\n'), ); } const moves: Move[] = []; const unchanged: ReleasePackage[] = []; const leveled: (ReleasePackage & { tag: string })[] = []; for (const pkg of packages) { const state = stateOf(pkg.name); const tag = releaseTagOf(options.rootVersion, pkg, state); const from = state.latest; if (tag !== 'latest') leveled.push({ ...pkg, tag }); else if (from === pkg.version) unchanged.push(pkg); else { const back = from !== undefined && !isDevelopmentBuild(from) && compareVersions(pkg.version, from) < 0; moves.push({ ...pkg, from, back }); } } const backwards = moves.filter(({ back }) => back); if (backwards.length > 0 && !options.allowDowngrade) { throw new PromotionError( [ 'Promoting this release would move latest back to an older version for these packages:', ...backwards.map(({ name, version, from }) => ` ${name}: ${from} -> ${version}`), 'To roll latest back on purpose, run the promotion again with allow-downgrade on.', ].join('\n'), ); } return { moves, unchanged, leveled }; } export function formatPromotion(promotion: Promotion): string { return [ ...promotion.moves.map( ({ name, version, from, back }) => `${name}: latest moves ${back ? 'back ' : ''}${from ?? '(none)'} -> ${version}`, ), ...promotion.unchanged.map(({ name, version }) => `${name}: latest is already ${version}`), ...promotion.leveled.map( ({ name, version, tag }) => `${name}: ${version} is under ${tag}; latest stays`, ), `${promotion.moves.length} to move, ${promotion.unchanged.length} already there, ${promotion.leveled.length} under a level's tag.`, ].join('\n'); } export function promotionPlan(version: string, promotion: Promotion): PromotionPlan { return { version, packages: [...promotion.moves, ...promotion.unchanged] .map(({ name, version: packageVersion }) => ({ name, version: packageVersion })) .sort((a, b) => (a.name < b.name ? -1 : 1)), }; }