Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

release-publish-plan.mjs

177 lines8.1 KB

1import { execFileSync } from 'node:child_process'
2import { appendFileSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
3import { resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5​
6export const packageDirectories = [
7 'packages/create',
8 'packages/cli',
9 'cli-aliases/create-start-app',
10 'cli-aliases/create-tanstack',
11 'cli-aliases/create-tanstack-app',
12 'cli-aliases/create-tsrouter-app',
13 'cli-aliases/ts-create-start',
15​
16export function planStableRelease(manifests, previous, changedPaths) {
17 const changed = manifests.filter((pkg) => previous.get(pkg.dir)?.version !== pkg.version)
18 if (!changed.length) return []
19​
20 const allowed = new Set(changed.flatMap(({ dir }) => [
21 `${dir}/package.json`,
22 `${dir}/CHANGELOG.md`,
23 ]))
24 for (const file of changedPaths) {
25 if (!allowed.has(file) && !/^\.changeset\/[\w-]+\.md$/.test(file)) {
26 throw new Error(`Stable version commit includes an unexpected file: ${file}`)
27 }
28 }
29 for (const pkg of changed) {
30 const { version: oldVersion, ...oldFields } = previous.get(pkg.dir) ?? {}
31 const { version, dir, ...fields } = pkg
32 if (!oldVersion || JSON.stringify(oldFields) !== JSON.stringify(fields)) {
33 throw new Error(`Expected a version-only manifest change in ${dir}`)
34 }
35 }
36​
37 const byName = new Map(manifests.map((pkg, index) => [pkg.name, { pkg, index }]))
38 if (byName.size !== manifests.length) throw new Error('Duplicate release package names')
39 return manifests.map((pkg, index) => {
40 const { name, version, dir } = pkg
41 if (!/^(?:@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(name) || !/^\d+\.\d+\.\d+$/.test(version)) {
42 throw new Error(`Invalid stable package identity in ${dir}`)
43 }
44 const dependencies = {}
45 for (const [dependency, range] of Object.entries(pkg.dependencies ?? {})) {
46 const target = byName.get(dependency)
47 if (!target) {
48 if (range.startsWith('workspace:')) throw new Error(`Unknown release dependency: ${dependency}`)
49 continue
50 }
51 if (target.index >= index || range !== 'workspace:*') {
52 throw new Error(`Unexpected release dependency ${name} -> ${dependency}`)
53 }
54 dependencies[dependency] = target.pkg.version
55 }
56 return { name, version, dir, dependencies, changed: changed.includes(pkg) }
57 })
59​
60export function shouldPublish(pkg, { attempted, registryStatus }) {
61 if (registryStatus !== 200 && registryStatus !== 404) {
62 throw new Error(`Cannot establish publication state for ${pkg.name}: HTTP ${registryStatus}`)
63 }
64 return pkg.changed && registryStatus === 404 && !attempted
66​
67export function priorPhaseWasReached(jobs, directory) {
68 const release = jobs.find((job) => job.name === 'Release')
69 if (!release) return false
70 if (release.status !== 'completed') throw new Error('Prior release job state is unavailable')
71 const name = `Publish and verify ${directory.split('/').at(-1)}`
72 return release.steps.some((step) => step.name === name && step.conclusion !== 'skipped' && step.started_at !== null)
74​
75const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim()
76const readManifest = (dir) => JSON.parse(readFileSync(`${dir}/package.json`, 'utf8'))
77const output = (name, value) => appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`)
78​
79function assertCurrentVersionPlan(plan) {
80 git('fetch', 'origin', 'refs/heads/main')
81 for (const { name, version, dir } of plan) {
82 const live = JSON.parse(git('show', `FETCH_HEAD:${dir}/package.json`))
83 if (live.name !== name || live.version !== version) {
84 throw new Error(`Stable release superseded for ${name}@${version}`)
85 }
86 }
88​
89async function run(command) {
90 const { GITHUB_REPOSITORY: repo, GITHUB_REF: ref, GITHUB_SHA: sha, GITHUB_RUN_ID: runId } = process.env
91 if (repo !== 'TanStack/cli' || ref !== 'refs/heads/main' || sha !== git('rev-parse', 'HEAD') || !/^\d+$/.test(runId ?? '')) {
92 throw new Error('Stable publishing requires the checked-out TanStack/cli main workflow')
93 }
94 if (command === 'plan') {
95 const publicDirectories = ['packages', 'cli-aliases'].flatMap((parent) =>
96 readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
97 const dir = `${parent}/${entry.name}`
98 try { return readManifest(dir).private ? [] : [dir] }
99 catch (error) { if (error.code === 'ENOENT') return []; throw error }
100 }),
101 )
102 if (publicDirectories.sort().join('\n') !== [...packageDirectories].sort().join('\n')) {
103 throw new Error('Update the stable release phase list for the current public workspaces')
104 }
105 const manifests = packageDirectories.map((dir) => ({ ...readManifest(dir), dir }))
106 const previous = new Map(packageDirectories.map((dir) => [dir, JSON.parse(git('show', `HEAD^:${dir}/package.json`))]))
107 const paths = git('diff', '--name-only', 'HEAD^', 'HEAD').split('\n')
108 const plan = planStableRelease(manifests, previous, paths)
109 if (plan.length) assertCurrentVersionPlan(plan)
110 output('active', String(plan.length > 0))
111 output('packages', JSON.stringify(plan))
112 return
113 }
114​
115 const plan = JSON.parse(process.env.STABLE_RELEASE_PLAN)
116 if (command === 'inspect') {
117 const pkg = plan.find(({ dir }) => dir === process.env.RELEASE_PACKAGE_DIR)
118 if (!pkg) throw new Error('Package is missing from the stable release plan')
119 const manifest = readManifest(pkg.dir)
120 if (manifest.name !== pkg.name || manifest.version !== pkg.version) throw new Error('Manifest identity changed')
121 const marker = `npm-upload-${pkg.dir.replaceAll('/', '-')}-${pkg.version}-${sha}`
122 const artifacts = JSON.parse(execFileSync('gh', ['api', `repos/${repo}/actions/runs/${runId}/artifacts?name=${marker}`], { encoding: 'utf8' }))
123 const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/${pkg.version}`, {
124 headers: { 'cache-control': 'no-cache' },
125 signal: AbortSignal.timeout(30_000),
126 })
127 if (response.ok) {
128 const identity = await response.json()
129 if (identity.name !== pkg.name || identity.version !== pkg.version) throw new Error('Registry identity mismatch')
130 }
131 if (!Number.isSafeInteger(artifacts.total_count) || artifacts.total_count < 0) {
132 throw new Error('Upload attempt evidence is unavailable')
133 }
134 let attempted = artifacts.total_count > 0
135 if (!attempted && response.status === 404 && pkg.changed) {
136 const runAttempt = Number(process.env.GITHUB_RUN_ATTEMPT)
137 if (!Number.isSafeInteger(runAttempt) || runAttempt < 1) throw new Error('Unknown workflow attempt')
138 for (let attempt = 1; attempt < runAttempt && !attempted; attempt++) {
139 const pages = JSON.parse(execFileSync('gh', [
140 'api', '--paginate', '--slurp',
141 `repos/${repo}/actions/runs/${runId}/attempts/${attempt}/jobs?per_page=100`,
142 ], { encoding: 'utf8' }))
143 attempted = priorPhaseWasReached(pages.flatMap((page) => page.jobs), pkg.dir)
144 }
145 }
146 const publish = shouldPublish(pkg, { attempted, registryStatus: response.status })
147 if (publish) assertCurrentVersionPlan(plan)
148 const receipt = resolve(process.env.RUNNER_TEMP, `${marker}.json`)
149 writeFileSync(receipt, JSON.stringify({ name: pkg.name, version: pkg.version, sha, runId }))
150 output('publish', String(publish))
151 output('marker', marker)
152 output('receipt', receipt)
153 output('package', JSON.stringify([pkg]))
154 return
155 }
156 if (command === 'tags') {
157 assertCurrentVersionPlan(plan)
158 const refs = []
159 for (const { name, version, changed } of plan) {
160 if (!changed) continue
161 const tag = `${name}@${version}`
162 const ref = `refs/tags/${tag}`
163 const existing = git('tag', '--list', tag)
164 if (existing && git('rev-parse', `${ref}^{commit}`) !== sha) throw new Error(`Tag already points elsewhere: ${tag}`)
165 if (!existing) git('tag', tag, sha)
166 refs.push(`${ref}:${ref}`)
167 }
168 if (refs.length) execFileSync('git', ['push', '--atomic', 'origin', ...refs], { stdio: 'inherit' })
169 output('published', String(refs.length > 0))
170 return
171 }
172 throw new Error(`Unknown stable release command: ${command}`)
174​
175if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
176 await run(process.argv[2])