bump.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /**
  2. * Bump one release family's version and commit it, so the published version is
  3. * readable from the repository rather than derived inside CI
  4. * ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
  5. *
  6. * The dsh family shares one version across its publishable members, private
  7. * package manifests, and the workspace root:
  8. * `major`, `minor`, `patch`, or an explicit `x.y.z` (including a prerelease such
  9. * as `0.0.1-rc.1`). The vendored family has one version line per package, but
  10. * every release advances and publishes the complete family so the next release
  11. * never reuses an unchanged member's existing version from a different
  12. * repository state.
  13. *
  14. * The version lands in the manifests, the lockfile follows, and a human creates
  15. * the tag after the commit merges. CI never writes to the repository.
  16. */
  17. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  18. import { join, matchesGlob } from 'node:path'
  19. import { parseArgs } from 'node:util'
  20. import { releaseFamily, type ReleaseFamily, type ReleaseMember } from './families.ts'
  21. import { capture, isEntry } from './process.ts'
  22. /** Files npm publishes whether or not `files` lists them. */
  23. const ALWAYS_PUBLISHED = ['package.json', 'README*', 'LICENSE*', 'LICENCE*'] as const
  24. /**
  25. * Inputs that decide what a built payload contains. A package whose `files`
  26. * selects `lib/` publishes build output that git does not track, so a change to
  27. * the sources or the build configuration changes the tarball while no published
  28. * path appears in the diff.
  29. */
  30. const BUILD_INPUTS = ['src/**', 'tsconfig*.json', 'tsdown.config.*', 'build.config.*'] as const
  31. /** Release types the dsh family accepts besides an explicit version. */
  32. const RELEASE_TYPES = ['major', 'minor', 'patch'] as const
  33. /** The workspace root manifest, which carries the dsh family's version. */
  34. const ROOT_MANIFEST = 'package.json'
  35. /** One manifest the bump rewrites, and the tag its new version will carry. */
  36. interface PlannedVersion {
  37. /** Repository-relative manifest path. */
  38. readonly manifestPath: string
  39. /** Label for the log line. */
  40. readonly label: string
  41. /** The version the manifest currently carries. */
  42. readonly from: string
  43. /** The version to write. */
  44. readonly to: string
  45. /** The tag this version publishes from, or undefined for a non-published manifest. */
  46. readonly tag: string | undefined
  47. }
  48. /** One private dsh package whose version follows the publishable family. */
  49. interface PrivateDshVersion {
  50. /** Repository-relative manifest path. */
  51. readonly manifestPath: string
  52. /** Package directory used in bump output. */
  53. readonly label: string
  54. /** Current manifest version. */
  55. readonly version: string
  56. }
  57. /**
  58. * Split a version into its release numbers, discarding any prerelease segment.
  59. * @param version - the current version.
  60. * @returns Major, minor, and patch.
  61. */
  62. function releaseNumbers(version: string): [number, number, number] {
  63. const match = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(version)
  64. if (match === null) throw new Error(`cannot read release numbers from version ${version}`)
  65. return [Number(match[1]), Number(match[2]), Number(match[3])]
  66. }
  67. /**
  68. * Order two versions by their release numbers alone.
  69. * @param left - one version.
  70. * @param right - the other version.
  71. * @returns Negative when `left` is lower, positive when higher, zero when equal.
  72. */
  73. function compareReleaseNumbers(left: string, right: string): number {
  74. const [leftMajor, leftMinor, leftPatch] = releaseNumbers(left)
  75. const [rightMajor, rightMinor, rightPatch] = releaseNumbers(right)
  76. return leftMajor - rightMajor || leftMinor - rightMinor || leftPatch - rightPatch
  77. }
  78. /**
  79. * The prerelease segment of a version, or undefined when it has none.
  80. * @param version - the version to read.
  81. * @returns The segment after the first `-`.
  82. */
  83. function prereleaseOf(version: string): string | undefined {
  84. const index = version.indexOf('-')
  85. return index === -1 ? undefined : version.slice(index + 1)
  86. }
  87. /**
  88. * Order two versions by semver precedence.
  89. *
  90. * Git's version sort cannot stand in for this: `--sort=v:refname` places
  91. * `4.0.1-rc.1` above `4.0.1`, while semver gives a prerelease lower precedence
  92. * than the release it precedes. Prerelease identifiers compare field by field,
  93. * numeric fields numerically, so `rc.10` outranks `rc.1`.
  94. * @param left - one version.
  95. * @param right - the other version.
  96. * @returns Negative when `left` is lower, positive when higher, zero when equal.
  97. */
  98. export function compareVersions(left: string, right: string): number {
  99. const numbers = compareReleaseNumbers(left, right)
  100. if (numbers !== 0) return numbers
  101. const leftPre = prereleaseOf(left)
  102. const rightPre = prereleaseOf(right)
  103. if (leftPre === undefined || rightPre === undefined) {
  104. if (leftPre === rightPre) return 0
  105. return leftPre === undefined ? 1 : -1
  106. }
  107. const leftFields = leftPre.split('.')
  108. const rightFields = rightPre.split('.')
  109. for (let index = 0; index < Math.max(leftFields.length, rightFields.length); index += 1) {
  110. const leftField = leftFields[index]
  111. const rightField = rightFields[index]
  112. // A shorter identifier list has lower precedence when all its fields match.
  113. if (leftField === undefined) return -1
  114. if (rightField === undefined) return 1
  115. if (leftField === rightField) continue
  116. const leftNumeric = /^\d+$/.test(leftField)
  117. const rightNumeric = /^\d+$/.test(rightField)
  118. if (leftNumeric && rightNumeric) return Number(leftField) - Number(rightField)
  119. // Numeric fields have lower precedence than alphanumeric ones.
  120. if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1
  121. return leftField < rightField ? -1 : 1
  122. }
  123. return 0
  124. }
  125. /**
  126. * The next dsh version.
  127. * @param current - the family's current shared version.
  128. * @param request - `major`, `minor`, `patch`, or an explicit version.
  129. * @returns The target version.
  130. */
  131. function nextSharedVersion(current: string, request: string): string {
  132. if (!RELEASE_TYPES.includes(request as typeof RELEASE_TYPES[number])) {
  133. if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(request)) {
  134. throw new Error(`usage: release:dsh <major|minor|patch|x.y.z>, got ${request}`)
  135. }
  136. return request
  137. }
  138. const [major, minor, patch] = releaseNumbers(current)
  139. if (request === 'major') return `${String(major + 1)}.0.0`
  140. if (request === 'minor') return `${String(major)}.${String(minor + 1)}.0`
  141. return `${String(major)}.${String(minor)}.${String(patch + 1)}`
  142. }
  143. /**
  144. * The version a vendored package publishes next.
  145. *
  146. * The baseline is the higher of the manifest version and the last tagged
  147. * version: a vendor re-sync restores upstream's version, which is lower than
  148. * the release version this repository already reserved, and incrementing that
  149. * would reuse an existing version.
  150. *
  151. * A prerelease does not consume its own release numbers. Publishing
  152. * `4.0.1-rc.1` leaves `4.0.1` free, so the next stable version is `4.0.1`
  153. * rather than `4.0.2`, and a second prerelease keeps those numbers too.
  154. * @param current - the package's manifest version.
  155. * @param tagged - the version its newest tag names, when it has one.
  156. * @param prerelease - prerelease identifier to append, for a rehearsal publication.
  157. * @returns The target version.
  158. */
  159. export function nextVendorVersion(
  160. current: string,
  161. tagged: string | undefined,
  162. prerelease?: string,
  163. ): string {
  164. const taggedOrder = tagged === undefined ? undefined : compareReleaseNumbers(tagged, current)
  165. const ahead = taggedOrder !== undefined && taggedOrder > 0
  166. const baseline = ahead && tagged !== undefined ? tagged : current
  167. const [major, minor, patch] = releaseNumbers(baseline)
  168. // Reuse the numbers when the tagged version that set them is a prerelease
  169. // of them; increment when a stable release already holds them.
  170. const taggedPrerelease = tagged !== undefined && prereleaseOf(tagged) !== undefined
  171. const sameReleasePrereleases = taggedOrder === 0 && prereleaseOf(current) !== undefined
  172. const reuse = taggedPrerelease && (ahead || sameReleasePrereleases)
  173. const numbers = reuse
  174. ? `${String(major)}.${String(minor)}.${String(patch)}`
  175. : `${String(major)}.${String(minor)}.${String(patch + 1)}`
  176. return prerelease === undefined ? numbers : `${numbers}-${prerelease}`
  177. }
  178. /**
  179. * Whether a repository-relative path reaches the member's published payload.
  180. * @param member - the member the path belongs to.
  181. * @param path - repository-relative path.
  182. * @returns True when `files`, npm's always-published set, or a build input selects it.
  183. */
  184. export function reachesPayload(member: ReleaseMember, path: string): boolean {
  185. const relative = path.slice(member.directory.length + 1)
  186. const files = member.manifest.files
  187. const selected = Array.isArray(files) ? files.filter((entry): entry is string => typeof entry === 'string') : []
  188. const built = selected.some(pattern => pattern.startsWith('lib'))
  189. const patterns = [...ALWAYS_PUBLISHED, ...selected, ...built ? BUILD_INPUTS : []]
  190. return patterns.some(pattern =>
  191. matchesGlob(relative, pattern) || matchesGlob(relative, `${pattern}/**`) || relative === pattern)
  192. }
  193. /**
  194. * The newest version a member tagged.
  195. * @param family - the member's family.
  196. * @param member - the member.
  197. * @returns The version, or undefined when the member has no release tag.
  198. */
  199. function lastTaggedVersion(family: ReleaseFamily, member: ReleaseMember): string | undefined {
  200. const prefix = family.tagPrefixFor(member)
  201. const versions = capture('git', ['tag', '--list', `${prefix}*`])
  202. .split('\n').filter(line => line !== '').map(tag => tag.slice(prefix.length))
  203. if (versions.length === 0) return undefined
  204. return versions.reduce((newest, candidate) => compareVersions(candidate, newest) > 0 ? candidate : newest)
  205. }
  206. /**
  207. * Write a version into a manifest, preserving formatting and key order.
  208. * @param root - repository root.
  209. * @param manifestPath - repository-relative manifest path.
  210. * @param from - the version the manifest currently carries.
  211. * @param to - the target version.
  212. */
  213. function writeVersion(root: string, manifestPath: string, from: string, to: string): void {
  214. const path = join(root, manifestPath)
  215. const text = readFileSync(path, 'utf8')
  216. const line = `"version": "${from}"`
  217. if (!text.includes(line)) throw new Error(`${manifestPath}: cannot locate ${line}`)
  218. writeFileSync(path, text.replace(line, `"version": "${to}"`))
  219. }
  220. /**
  221. * Read the workspace root version.
  222. * @param root - repository root.
  223. * @returns The root manifest version.
  224. */
  225. function rootVersion(root: string): string {
  226. const manifest: unknown = JSON.parse(readFileSync(join(root, ROOT_MANIFEST), 'utf8'))
  227. const version = (manifest as Record<string, unknown>).version
  228. if (typeof version !== 'string') throw new Error('package.json must declare a string version')
  229. return version
  230. }
  231. /**
  232. * Discover private package manifests that share the dsh version without joining
  233. * its publish set.
  234. * @param root - repository root.
  235. * @returns Private package manifests sorted by path.
  236. */
  237. function privateDshVersions(root: string): PrivateDshVersion[] {
  238. return globSync('packages/*/*/package.json', { cwd: root })
  239. .map(path => path.replaceAll('\\', '/'))
  240. .sort()
  241. .flatMap((manifestPath) => {
  242. const parsed: unknown = JSON.parse(readFileSync(join(root, manifestPath), 'utf8'))
  243. if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
  244. throw new Error(`${manifestPath} is not a JSON object`)
  245. }
  246. const manifest = parsed as Record<string, unknown>
  247. if (manifest.private !== true) return []
  248. if (typeof manifest.version !== 'string') {
  249. throw new Error(`${manifestPath} must declare a string version`)
  250. }
  251. return [{
  252. manifestPath,
  253. label: manifestPath.slice(0, -'/package.json'.length),
  254. version: manifest.version,
  255. }]
  256. })
  257. }
  258. /**
  259. * Plan the dsh family's rewrite: one version for every publishable member,
  260. * private package, and the root.
  261. * @param family - the dsh family.
  262. * @param root - repository root.
  263. * @param members - the family's members.
  264. * @param request - `major`, `minor`, `patch`, or an explicit version.
  265. * @returns The manifests to rewrite and the shared target version.
  266. */
  267. export function planShared(
  268. family: ReleaseFamily,
  269. root: string,
  270. members: readonly ReleaseMember[],
  271. request: string,
  272. ): { planned: PlannedVersion[]; version: string } {
  273. const [first] = members
  274. if (first === undefined) throw new Error(`release family ${family.id} has no members`)
  275. const version = nextSharedVersion(first.version, request)
  276. // The workspace root carries the family version too: the workspace constraint
  277. // requires every member's version to equal the root's.
  278. const planned: PlannedVersion[] = [
  279. { manifestPath: ROOT_MANIFEST, label: ROOT_MANIFEST, from: rootVersion(root), to: version, tag: undefined },
  280. ]
  281. for (const member of members) {
  282. planned.push({
  283. manifestPath: `${member.directory}/package.json`,
  284. label: member.directory,
  285. from: member.version,
  286. to: version,
  287. tag: family.tagFor({ ...member, version }),
  288. })
  289. }
  290. const publishableManifests = new Set(members.map(member => `${member.directory}/package.json`))
  291. for (const entry of privateDshVersions(root)) {
  292. if (publishableManifests.has(entry.manifestPath)) continue
  293. planned.push({
  294. manifestPath: entry.manifestPath,
  295. label: entry.label,
  296. from: entry.version,
  297. to: version,
  298. tag: undefined,
  299. })
  300. }
  301. return { planned, version }
  302. }
  303. /**
  304. * Plan the vendored family's rewrite: every package advances together while
  305. * retaining its own version line and tag.
  306. * @param family - the vendored family.
  307. * @param members - the family's members.
  308. * @param prerelease - prerelease identifier to append, for a rehearsal publication.
  309. * @returns The manifests to rewrite.
  310. */
  311. function planPerPackage(
  312. family: ReleaseFamily,
  313. members: readonly ReleaseMember[],
  314. prerelease: string | undefined,
  315. ): PlannedVersion[] {
  316. const planned: PlannedVersion[] = []
  317. for (const member of members) {
  318. const tagged = lastTaggedVersion(family, member)
  319. const to = nextVendorVersion(member.version, tagged, prerelease)
  320. planned.push({
  321. manifestPath: `${member.directory}/package.json`,
  322. label: member.directory,
  323. from: member.version,
  324. to,
  325. tag: family.tagFor({ ...member, version: to }),
  326. })
  327. }
  328. return planned
  329. }
  330. /**
  331. * Bump the family named by `--family` and commit; `--dry-run` only reports the
  332. * plan. `--prerelease rc.1` makes the vendored family publish a rehearsal
  333. * version, which never takes the stable dist-tag.
  334. */
  335. function main(): void {
  336. const { values, positionals } = parseArgs({
  337. options: {
  338. family: { type: 'string' },
  339. prerelease: { type: 'string' },
  340. 'dry-run': { type: 'boolean', default: false },
  341. },
  342. allowPositionals: true,
  343. })
  344. if (values.family === undefined) throw new Error('usage: bump.ts --family <dsh|vendor> [version]')
  345. const family = releaseFamily(values.family)
  346. const root = process.cwd()
  347. const members = family.members(root)
  348. family.verifyVersions(members)
  349. let planned: PlannedVersion[]
  350. let sharedVersion: string | undefined
  351. if (family.id === 'dsh') {
  352. const request = positionals[0]
  353. if (request === undefined) throw new Error('usage: release:dsh <major|minor|patch|x.y.z>')
  354. if (values.prerelease !== undefined) {
  355. throw new Error('release:dsh takes the prerelease in its version argument, as in 0.0.1-rc.1')
  356. }
  357. const shared = planShared(family, root, members, request)
  358. planned = shared.planned
  359. sharedVersion = shared.version
  360. } else {
  361. if (positionals.length > 0) throw new Error('release:vendor takes no version: each package increments its own patch')
  362. if (values.prerelease !== undefined && !/^[0-9A-Za-z.-]+$/.test(values.prerelease)) {
  363. throw new Error(`--prerelease must be a semver prerelease identifier, got ${values.prerelease}`)
  364. }
  365. planned = planPerPackage(family, members, values.prerelease)
  366. }
  367. if (planned.length === 0) {
  368. console.log(`release bump: family ${family.id}, nothing changed since publication`)
  369. return
  370. }
  371. const dryRun = values['dry-run']
  372. if (!dryRun) {
  373. for (const entry of planned) writeVersion(root, entry.manifestPath, entry.from, entry.to)
  374. capture('pnpm', ['install', '--lockfile-only'])
  375. }
  376. const summary = sharedVersion
  377. ?? planned.map(entry => `${entry.label.replace('vendor/', '')} ${entry.to}`).join(', ')
  378. console.log(`release bump: family ${family.id} -> ${summary}`)
  379. for (const entry of planned) console.log(` ${entry.label}: ${entry.from} -> ${entry.to}`)
  380. if (dryRun) {
  381. console.log('release bump: dry run, nothing written')
  382. return
  383. }
  384. capture('git', ['add', 'pnpm-lock.yaml', ...planned.map(entry => entry.manifestPath)])
  385. capture('git', ['commit', '-m', `release(${family.id}): ${summary}`])
  386. console.log('release bump: committed. After this merges to master, tag it:')
  387. for (const tag of [...new Set(planned.map(entry => entry.tag).filter(tag => tag !== undefined))]) {
  388. console.log(` git tag ${tag} <merge commit> && git push origin ${tag}`)
  389. }
  390. }
  391. if (isEntry(import.meta.url)) main()