/** Build a tagged release on the Gitea host and distribute its signed artifacts. */ import { execFileSync, execSync } from 'node:child_process'; import { existsSync } from 'node:fs'; import { access, copyFile, mkdir, mkdtemp, open, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises'; import { join, relative, resolve } from 'node:path'; import { parseArgs } from 'node:util'; import { packFileNames, packVersionOfTag } from '../packages/patcher/src/patch-pack/manifest.ts'; import { GiteaReleaseClient } from './gitea/release.ts'; import type { ReleaseEntry } from './r2/download-page.ts'; const REPOSITORY = resolve(import.meta.dirname, '..'); const RELEASES = join(REPOSITORY, 'build', 'vps-releases'); const USAGE = `Usage: node scripts/release-vps.ts [--publish] Run from a clean checkout of the tag already pushed to Gitea. Prepare a signed Gitea draft by default. With --publish, sync R2 and publish the draft. Set GITEA_TOKEN and PATCH_SIGNING_KEY in the release environment, plus the R2 credentials for --publish.`; interface ReleaseBuild { readonly tag: string; readonly version: string; readonly commit: string; readonly pack: boolean; readonly names: readonly string[]; } // Keep release credentials out of dependency installation, type checks and builders. const buildEnv = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^(?:GITEA_TOKEN$|PATCH_SIGNING_KEY$|R2_)/i.test(name))); async function main(): Promise { const { positionals, values } = parseArgs({ allowPositionals: true, options: { publish: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } }, }); if (values.help) { console.info(USAGE); return; } const [tag] = positionals; const packVersion = tag ? packVersionOfTag(tag) : null; const launcherVersion = tag?.match(/^v(\d+\.\d+\.\d+)$/)?.[1]; const version = packVersion ?? launcherVersion; if (positionals.length !== 1 || !tag || !version) throw new Error(USAGE); const pack = packVersion !== null; const gitea = new GiteaReleaseClient( process.env['GITEA_URL'] ?? 'http://127.0.0.1:3000', process.env['GITEA_REPOSITORY'] ?? 'Sh3ll_in_Sh3ll/WT-Offline', requiredEnv('GITEA_TOKEN'), ); const commit = taggedCommit(tag); const tagObject = git(['rev-parse', '--verify', `refs/tags/${tag}`]); await gitea.verifyTag(tag, tagObject); await mkdir(RELEASES, { recursive: true }); if (relative(RELEASES, await realpath(RELEASES)) !== '') throw new Error('The VPS releases directory is redirected.'); const lockPath = join(RELEASES, 'release.lock'); const lock = await open(lockPath, 'wx').catch((error: NodeJS.ErrnoException) => { if (error.code === 'EEXIST') throw new Error(`A VPS release is already running or left a lock at ${lockPath}.`); throw error; }); try { await lock.writeFile(`${process.pid}\n`); const folder = join(RELEASES, tag); const prepared = existsSync(folder); if (prepared && (await readFile(join(folder, 'source-commit'), 'utf8')).trim() !== commit) { throw new Error(`The saved artifacts for ${tag} came from a different commit.`); } let release = await gitea.findRelease(tag); if (!prepared && release && (!release.draft || release.assets?.length)) { throw new Error(`Gitea already has a release for ${tag}. Restore its prepared artifacts to ${folder}.`); } if (release && release.prerelease !== pack) throw new Error(`Gitea release ${tag} has a different prerelease setting.`); const signingKey = prepared ? null : requiredEnv('PATCH_SIGNING_KEY'); console.info(`${tag} at ${commit}: ${prepared ? 'using saved artifacts' : 'preparing signed artifacts'}.`); npm('ci', { ...buildEnv, ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }); const build = { tag, version, commit, pack, names: await artifactNames(version, pack) }; const entry = signingKey ? await prepare(build, signingKey, folder) : await stage(build, folder); if (taggedCommit(tag) !== commit) throw new Error('The checkout changed during release preparation.'); await gitea.verifyTag(tag, tagObject); release ??= await gitea.createDraft({ tag_name: tag, target_commitish: commit, name: entry.name, body: entry.body, prerelease: entry.prerelease, }); const files = build.names.map((name) => join(artifactFolder(folder, tag), name)); await gitea.syncAttachments(release, files); if (!values.publish) { console.info(`Gitea release ${tag} is ${release.draft ? 'ready for draft review' : 'published'}.`); return; } await withTemporaryFolder('r2-', async (output) => { const r2Env = Object.fromEntries(Object.entries(process.env).filter(([name]) => /^R2_/i.test(name))); runNode('publish-r2-releases.ts', [ ...r2Arguments(build, folder, output), '--upload', '--immutable-assets', ], { ...buildEnv, ...r2Env }); }); if (release.draft) await gitea.publish(release.id); console.info(`Published ${tag} on Gitea and R2.`); } finally { await lock.close(); await unlink(lockPath); } } async function artifactNames(version: string, pack: boolean): Promise { if (pack) return Object.values(packFileNames(version)); const packagePath = join(REPOSITORY, 'apps', 'launcher', 'package.json'); const manifest = JSON.parse(await readFile(packagePath, 'utf8')) as { version: string }; if (manifest.version !== version) throw new Error(`Launcher version ${manifest.version} does not match v${version}.`); await access(join(REPOSITORY, '.github', 'release-notes', `v${version}.md`)); const { launcherReleaseFiles, portableLauncherReleaseFiles } = await import('../apps/launcher/src/shared/schemas/app-update.ts'); return [...Object.values(launcherReleaseFiles(version)), ...Object.values(portableLauncherReleaseFiles(version))]; } async function prepare(build: ReleaseBuild, signingKey: string, folder: string): Promise { return withTemporaryFolder('prepare-', async (temp) => { const assets = artifactFolder(temp, build.tag); await mkdir(assets, { recursive: true }); const signingEnv = { ...buildEnv, PATCH_SIGNING_KEY: signingKey }; if (build.pack) { runNode('build-patch-pack.ts', ['--version', build.version, '--out', assets], signingEnv); } else { execFileSync(process.execPath, ['node_modules/electron/install.js'], { cwd: REPOSITORY, stdio: 'inherit', env: { ...buildEnv, ELECTRON_SKIP_BINARY_DOWNLOAD: undefined }, }); npm('run typecheck'); npm('run typecheck --workspace @wto/launcher'); npm('--workspace @wto/launcher run package:win'); runNode('sign-launcher-release.ts', [], signingEnv); for (const name of build.names) { await copyFile(join(REPOSITORY, 'build', 'windows-installer', name), join(assets, name)); } } const entry = await stage(build, temp); await writeFile(join(temp, 'source-commit'), `${build.commit}\n`, 'utf8'); await rename(temp, folder); return entry; }); } async function stage(build: ReleaseBuild, folder: string): Promise { runNode('publish-r2-releases.ts', r2Arguments(build, folder, folder)); const entries = JSON.parse(await readFile(join(folder, 'releases'), 'utf8')) as ReleaseEntry[]; const entry = entries.find((candidate) => candidate.tag_name === build.tag); if (!entry || entry.assets.length !== build.names.length || !build.names.every((name) => entry.assets.some((asset) => asset.name === name))) { throw new Error(`The staged release for ${build.tag} is missing expected signed files.`); } return entry; } function r2Arguments(build: ReleaseBuild, folder: string, output: string): string[] { const assets = artifactFolder(folder, build.tag); return build.pack ? ['--add-pack', join(assets, packFileNames(build.version).zip), '--out', output] : ['--add-launcher', assets, '--out', output]; } function artifactFolder(folder: string, tag: string): string { return join(folder, 'files', tag); } async function withTemporaryFolder(prefix: string, work: (folder: string) => Promise): Promise { const folder = await mkdtemp(join(RELEASES, prefix)); try { return await work(folder); } finally { await rm(folder, { recursive: true, force: true }); } } function taggedCommit(tag: string): string { if (git(['status', '--porcelain'])) throw new Error('Use a clean checkout for VPS releases.'); const commit = git(['rev-parse', '--verify', 'HEAD']); if (git(['rev-parse', '--verify', `refs/tags/${tag}^{commit}`]) !== commit) { throw new Error(`Check out the Gitea tag ${tag} before running this script.`); } return commit; } function git(args: string[]): string { return execFileSync('git', args, { cwd: REPOSITORY, encoding: 'utf8', env: buildEnv }).trim(); } function npm(command: 'ci' | 'run typecheck' | 'run typecheck --workspace @wto/launcher' | '--workspace @wto/launcher run package:win', env = buildEnv): void { execSync(`npm ${command}`, { cwd: REPOSITORY, stdio: 'inherit', env }); } function runNode(script: string, args: string[], env = buildEnv): void { execFileSync(process.execPath, [join('scripts', script), ...args], { cwd: REPOSITORY, stdio: 'inherit', env }); } function requiredEnv(name: string): string { const value = process.env[name]?.trim(); if (!value) throw new Error(`Missing ${name} in the VPS release environment.`); return value; } await main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });