diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ac5464..9a088c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,3 +87,8 @@ jobs: - name: Schema façade check run: pnpm run check:facade + + # Preparation never uploads and is permitted on detached PR checkouts. + # The publish mode rejects CI and requires an interactive confirmation. + - name: SDK release preparation (no publication) + run: pnpm run release diff --git a/CLAUDE.md b/CLAUDE.md index 6557957..6003a05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,6 +34,7 @@ pnpm typecheck # pnpm -r typecheck pnpm test # pnpm -r test pnpm lint # biome check . pnpm run check:facade # scripts/check-facade.mjs +pnpm run release # validate, build and pack; never uploads by default ``` Prefer `pnpm exec` over `npx` for one-off CLI invocations in this workspace. @@ -83,12 +84,24 @@ Prefer `pnpm exec` over `npx` for one-off CLI invocations in this workspace. ## Publish order -`pnpm publish` per package, human-run only — never executed by an agent: +`pnpm run release` is the canonical SDK preparation entrypoint. It installs +locked dependencies, validates, builds, tests and packs all four packages. +Agents may run this default/dry-run mode. + +`pnpm run release -- --publish` is human-run only — never executed by an +agent. It requires a clean, current `main`, an interactive terminal outside CI, +and explicit confirmation after the package plan is displayed. It invokes +`pnpm publish` for verified tarballs in this order: ``` plugin-manifest-schema → plugin-api → plugin-cli → create-motrix-plugin ``` +See [the release guide](docs/releasing.md) and its +[Chinese counterpart](docs/releasing.zh-CN.md) for requirements, artifacts and +partial-release recovery. The script does not create tags, merge PRs or sign +plugin bundles. + ## Conventions - Conversation language is Chinese; code, commits, identifiers, and file diff --git a/README.md b/README.md index 72bbabc..ad02b9f 100644 --- a/README.md +++ b/README.md @@ -291,7 +291,7 @@ public commands — ask for the minimum you need; broad host patterns and pnpm install pnpm build # tsup, all packages pnpm typecheck -pnpm test # vitest, all packages +pnpm test # release-tool tests + package suites pnpm lint # biome pnpm run check:facade # façade-purity guard ``` @@ -302,6 +302,13 @@ in `packages/plugin-manifest-schema` only (`plugin-cli`'s always ships together with a matching CLI release, because the CLI embeds the schema at build time. +## SDK releases + +`pnpm run release` validates, builds and packs all four SDK packages without +uploading. Publication is a separate, human-confirmed mode; CI only prepares +artifacts. See the [release guide](docs/releasing.md) for requirements, the +fixed package order and recovery from a partial release. + ## License [MIT](./LICENSE) diff --git a/README.zh-CN.md b/README.zh-CN.md index 51632a0..47961ca 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -273,7 +273,7 @@ Plugins 页安装(**Install from .moext**)。安装时 Motrix 会弹出 consent pnpm install pnpm build # tsup, all packages pnpm typecheck -pnpm test # vitest, all packages +pnpm test # release-tool tests + package suites pnpm lint # biome pnpm run check:facade # façade-purity guard ``` @@ -283,6 +283,10 @@ pnpm run check:facade # façade-purity guard 是受守护的纯 re-export);schema 发新版时必须同批发布配套的 CLI 版本, 因为 CLI 在构建时内嵌了 schema。 +## SDK 发布 + +`pnpm run release` 统一校验、构建和打包四个 SDK 包,默认不上传。正式发布使用需要人工确认的独立模式,CI 只准备产物。前置条件、固定发布顺序和部分发布恢复方式见[发布指南](docs/releasing.zh-CN.md)。 + ## License [MIT](./LICENSE) diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..1cf5ce7 --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,134 @@ +# Releasing the SDK + +English | [简体中文](releasing.zh-CN.md) + +The repository's release entrypoint is `pnpm run release`. Its default mode +validates, builds and packs the four npm packages without publishing. Uploading +requires an explicit maintainer action in an interactive terminal. CI and agents +may run preparation; agents must not run the publish mode. + +This workflow releases the SDK npm packages. It does not change versions, merge +PRs, create Git tags, publish Motrix, sign `.moext` plugins or update the registry. + +## Requirements + +- Node.js 20 or later, Git, `tar` with gzip support, and the exact pnpm version + specified by the root `package.json`. On Windows, use standalone `pnpm.exe` + (as CI does) or a pnpm launcher that supplies its JavaScript `npm_execpath`. +- Install the versions intended for release in the four package manifests through + a reviewed PR first. The script accepts stable `x.y.z` versions only and uses + the public npm registry with the `latest` tag. Schema and CLI versions must + match because the CLI embeds the schema. API and create-wrapper versions may + differ; all four packages are checked together. +- For publication, a clean `main` checkout, including no untracked files, whose + HEAD equals the current `origin/main`. Keep the checkout and artifacts unchanged + for the whole run. Publishing requires network access to GitHub and npm and an + npm account authorized to publish these packages. Authentication and any OTP + prompts remain with pnpm; the script does not read or store credentials. + +## Prepare without publishing + +From the SDK repository root: + +```bash +pnpm run release +# Explicit equivalent: +pnpm run release -- --dry-run +``` + +Preparation supports feature branches, detached CI checkouts and local changes. +The report records the source commit and whether the checkout was dirty. A dirty +preparation is useful for development, but cannot authorize a publication. + +The script runs these gates in order, stopping at the first failure: + +1. Validate package identities, stable versions, publication configuration, the + schema/CLI version pair, and the pinned package manager. +2. `pnpm install --frozen-lockfile`. +3. `pnpm run lint` and `pnpm run check:facade`. +4. `pnpm run build`, then `pnpm run typecheck`, then `pnpm run test`. +5. Pack each of the four packages with pnpm and inspect the actual tarballs. + +Packing must finish for the entire batch before any upload is considered. The +archive checks verify package identities, required entrypoints/files and rewritten +workspace dependencies. Published dependencies cannot contain `workspace:`, +`link:` or `file:` references, and the CLI cannot retain runtime `@motrix/` +dependencies instead of embedding its SDK code. + +Each run creates a fresh ignored `dist/release/sdk-*/` directory containing the +four `.tgz` archives and `release.json`. The report includes source Git state, +pnpm version, package versions, sizes, SHA-256 digests, npm SHA-512 integrity +strings, progress and any failure. Earlier runs are retained for investigation. +Preparation performs no npm metadata lookup or upload; installing locked +build dependencies can still access the package registry. + +## Publish manually + +After the version/tooling PRs are merged, use a clean, current `main` checkout and +run this command yourself: + +```bash +pnpm run release -- --publish +``` + +This reruns the complete preparation pipeline. Publish mode rejects CI and +non-interactive terminals before running the pipeline. There is no `--yes`, +`--force` or validation-skip option. + +Before uploading, the script checks all four exact versions on npm. A 404 means +that a version is available for publication; an authentication, rate-limit, +network or other registry error stops the run. An existing version is skipped +only if its SHA-512 integrity matches the newly prepared archive. A conflicting +version stops the whole batch before the first upload. + +The terminal displays the package versions, integrity values, destination and +which packages are pending or already published. Type exactly +`publish SDK packages to npm` to authorize the pending uploads. Declining leaves +the packages unpublished. An entirely identical, already-published batch finishes +without asking for confirmation or sending uploads. + +Publication order is fixed: + +```text +@motrix/plugin-manifest-schema +@motrix/plugin-api +@motrix/plugin-cli +create-motrix-plugin +``` + +The script rechecks Git state and archive integrity after confirmation and before +each upload. It invokes pnpm with the verified tarball, explicit public registry, +public access and `latest` tag, preserving Git checks and interactive OTP support. +Each package must become visible with the matching integrity before the next is +published. Missing metadata is polled up to 15 times at two-second intervals; +each HTTP request has a 15-second timeout. Other registry errors stop immediately. + +## Failure and partial-release recovery + +npm publication across four packages is not atomic. If upload or verification +fails, later packages are not attempted, and nothing is unpublished or retried +automatically. Preserve the run directory and inspect `release.json` and npm. +A `publishing` status is uncertain: the server may have accepted an upload even +if the client failed or metadata was not yet visible. + +Once the cause is resolved, rerun from the same reviewed source with the pinned +build tools. The script rebuilds and compares exact published integrity values; +matching packages are skipped, and only the missing packages are submitted after +confirmation. It never overwrites an immutable version. If rebuilding changes the +bytes of a published version, stop and investigate; do not force the upload or +silently skip the mismatch. Any version correction belongs in a new reviewed PR, +keeping schema/CLI versions aligned. + +Keep consumers blocked until the coordinated SDK batch is verified. Only then +update Motrix and official-plugin dependencies and lockfiles and rerun their clean +CI. Publishing an SDK version does not prove that a compatible host or plugin +release is available; verify those separately. + +## Tests and CI + +`pnpm test` runs the release script's Node tests and the existing SDK suites. +Publication tests inject command and registry substitutes; they never upload to +npm. Tests cover ordering, failed gates, archive inspection, registry conflicts, +confirmation, changed artifacts, partial release and uncertain upload results. +CI also runs the actual default preparation command on each supported OS/Node +combination. No workflow automatically publishes packages. diff --git a/docs/releasing.zh-CN.md b/docs/releasing.zh-CN.md new file mode 100644 index 0000000..fa8faf8 --- /dev/null +++ b/docs/releasing.zh-CN.md @@ -0,0 +1,74 @@ +# 发布 SDK + +[English](releasing.md) | 简体中文 + +仓库统一入口为 `pnpm run release`,默认仅校验、构建和打包四个 npm 包,不执行发布。上传必须由维护者在交互式终端明确触发。CI 和代理可以运行准备模式;代理不得执行发布模式。 + +这套流程只发布 SDK npm 包,不修改版本号、不合并 PR、不创建 Git tag、不发布 Motrix、不签名 `.moext` 插件,也不更新插件注册表。 + +## 前置条件 + +- Node.js 20 或更高版本、Git、支持 gzip 的 `tar`,以及根 `package.json` 指定的精确 pnpm 版本。Windows 使用独立的 `pnpm.exe`(与 CI 一致),或能够提供 JavaScript `npm_execpath` 的 pnpm 启动器。 +- 先通过评审的 PR 在四个 package manifest 中设置目标版本。脚本首版只接受稳定的 `x.y.z` 版本,目标固定为公共 npm registry 和 `latest` tag。CLI 内嵌 schema,因此两者版本必须一致;API 和 create wrapper 可以使用不同版本,但每次均核对四个包。 +- 正式发布要求干净的 `main`,包括没有未跟踪文件,且 HEAD 与当前 `origin/main` 完全一致。运行期间保持源码和产物不变。需要能访问 GitHub 和 npm,并使用有权发布这些包的 npm 账号。登录和 OTP 交互由 pnpm 处理;脚本不读取或保存凭据。 + +## 仅准备,不发布 + +在 SDK 仓库根目录执行: + +```bash +pnpm run release +# 显式等价命令: +pnpm run release -- --dry-run +``` + +准备模式允许功能分支、CI detached checkout 和本地修改。报告记录源码提交及工作树是否有修改;带修改的准备结果可以用于开发验证,但不能作为发布授权。 + +脚本按以下顺序执行,任一步失败立即停止: + +1. 核对包身份、稳定版本、发布配置、schema/CLI 版本配对及固定 pnpm 版本。 +2. 执行 `pnpm install --frozen-lockfile`。 +3. 执行 `pnpm run lint` 和 `pnpm run check:facade`。 +4. 依次执行 `pnpm run build`、`pnpm run typecheck`、`pnpm run test`。 +5. 使用 pnpm 打包四个包,并检查实际 tarball。 + +四个包全部打包完成后才会考虑上传。归档检查覆盖包身份、必需入口和文件、workspace 依赖重写。发布依赖中不能残留 `workspace:`、`link:` 或 `file:`;CLI 必须内嵌 SDK 代码,不能残留运行时 `@motrix/` 依赖。 + +每次运行都会创建新的 ignored 目录 `dist/release/sdk-*/`,包含四个 `.tgz` 和 `release.json`。报告记录 Git 状态、pnpm 版本、包版本、大小、SHA-256、npm SHA-512 integrity、进度和失败信息。历史运行目录保留,便于排查。准备模式不查询 npm 发布元数据,也不上传;安装锁定的构建依赖仍可能访问包 registry。 + +## 人工发布 + +版本和工具 PR 合并后,在干净且已同步的 `main` 上,由维护者本人执行: + +```bash +pnpm run release -- --publish +``` + +该命令会重新完成整个准备流程。发布模式会在运行流程前拒绝 CI 和非交互式终端,没有 `--yes`、`--force` 或跳过校验选项。 + +上传前先核对 npm 上四个精确版本。404 表示尚未发布;认证、限流、网络或其他 registry 错误都会使流程停止。仅当已有版本的 SHA-512 integrity 与本次归档一致时才会跳过。任一版本冲突都会在首次上传前阻止整个批次。 + +终端会展示包版本、integrity、目标 registry,以及哪些包待发布、哪些包已存在。必须准确输入 `publish SDK packages to npm` 才能授权待发布项。拒绝确认不会上传。如果整个批次都已发布且摘要一致,则直接结束,不要求确认,也不重复上传。 + +发布顺序固定为: + +```text +@motrix/plugin-manifest-schema +@motrix/plugin-api +@motrix/plugin-cli +create-motrix-plugin +``` + +确认后及每次上传前,脚本都会重新核对 Git 状态和归档摘要。发布时向 pnpm 传入已验证 tarball、明确的公共 registry、public access 和 `latest` tag,保留 Git 检查及交互式 OTP 支持。每个包必须在 npm 上可查询且摘要一致,才会继续下一个。元数据缺失时最多查询 15 次,间隔两秒;单次 HTTP 请求超时为 15 秒。其他 registry 错误立即停止。 + +## 失败与部分发布恢复 + +四个 npm 包的发布不具备原子性。上传或发布后校验失败时,后续包不再尝试,不自动撤销已发布包,也不自动重试上传。请保留运行目录,检查 `release.json` 和 npm 实际状态。报告中的 `publishing` 属于不确定状态:即使客户端失败或元数据尚不可见,服务端也可能已接收包。 + +解决原因后,使用同一份经过评审的源码和固定构建工具重新运行。脚本重新构建并核对已发布包的精确 integrity;完全一致的包会跳过,只对缺少的包请求确认并上传。不会覆盖不可变版本。如果重建结果与已发布版本不同,应停止并查明原因,不能强制上传或静默忽略冲突。需要调整版本时,提交新的评审 PR,并保持 schema/CLI 版本一致。 + +在整个 SDK 批次核验完成前,消费者仍保持阻塞。完成后再更新 Motrix 和官方插件的依赖及锁文件,并复跑干净 CI。SDK 发布不代表兼容的宿主或插件也已发布,二者仍需独立核验。 + +## 测试与 CI + +`pnpm test` 会运行发布脚本的 Node 测试及原有 SDK 测试。发布测试注入命令和 registry 替身,不向 npm 上传,覆盖顺序、检查失败、归档验证、版本冲突、确认、产物变化、部分发布及上传结果不确定等情况。CI 还会在各操作系统与 Node 组合上运行真实的默认准备命令,没有任何 workflow 会自动发布包。 diff --git a/package.json b/package.json index 2a5f50d..c362d49 100644 --- a/package.json +++ b/package.json @@ -9,9 +9,10 @@ "scripts": { "build": "pnpm -r build", "typecheck": "pnpm -r typecheck", - "test": "pnpm -r test", + "test": "node --test scripts/release.test.mjs && pnpm -r test", "lint": "biome check .", - "check:facade": "node scripts/check-facade.mjs" + "check:facade": "node scripts/check-facade.mjs", + "release": "node scripts/release.mjs" }, "devDependencies": { "@biomejs/biome": "^2.5.11" diff --git a/scripts/release.mjs b/scripts/release.mjs new file mode 100644 index 0000000..ad13cdb --- /dev/null +++ b/scripts/release.mjs @@ -0,0 +1,479 @@ +#!/usr/bin/env node +import { execFile, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { createInterface } from 'node:readline/promises' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' + +const execFileAsync = promisify(execFile) +const ROOT = path.resolve(fileURLToPath(new URL('..', import.meta.url))) +export const REGISTRY = 'https://registry.npmjs.org/' +export const PACKAGES = [ + ['plugin-manifest-schema', '@motrix/plugin-manifest-schema'], + ['plugin-api', '@motrix/plugin-api'], + ['plugin-cli', '@motrix/plugin-cli'], + ['create-motrix-plugin', 'create-motrix-plugin'], +] +const CONFIRMATION = 'publish SDK packages to npm' +const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/ + +export function parseArgs(args) { + const flags = args.filter((arg) => arg !== '--') + if (flags.length === 0) return { publish: false } + if (flags.length !== 1) + throw new Error('Choose --dry-run or --publish, not both.') + if (flags[0] === '--help' || flags[0] === '-h') return { help: true } + if (flags[0] === '--dry-run') return { publish: false } + if (flags[0] === '--publish') return { publish: true } + throw new Error(`Unknown argument: ${flags[0]}`) +} + +async function execute(command, args, { cwd, capture = false }) { + let program = command + let parameters = args + if (command === 'pnpm') { + // Reuse the invoking package manager, including corepack's JS entrypoint. + // Standalone pnpm.exe also works when npm_execpath is not supplied. + const entry = process.env.npm_execpath + if (entry && /pnpm/i.test(path.basename(entry))) { + if (/\.[cm]?js$/i.test(entry)) { + program = process.execPath + parameters = [entry, ...args] + } else { + program = entry + } + } else if (process.platform === 'win32') { + program = 'pnpm.exe' + } + } + if (capture) { + const { stdout } = await execFileAsync(program, parameters, { + cwd, + encoding: 'utf8', + maxBuffer: 4 * 1024 * 1024, + windowsHide: true, + }) + return stdout.trim() + } + await new Promise((resolve, reject) => { + const child = spawn(program, parameters, { cwd, stdio: 'inherit' }) + child.on('error', reject) + child.on('exit', (code, signal) => { + if (code === 0) resolve() + else + reject(new Error(`${command} ${args[0]} failed (${signal ?? code}).`)) + }) + }) + return '' +} + +async function readVersion(name, version) { + const response = await fetch( + new URL( + `${encodeURIComponent(name)}/${encodeURIComponent(version)}`, + REGISTRY + ), + { redirect: 'error', signal: AbortSignal.timeout(15_000) } + ) + if (response.status === 404) return null + if (!response.ok) { + throw new Error( + `Registry lookup failed for ${name}@${version}: HTTP ${response.status}.` + ) + } + return response.json() +} + +async function confirm(message) { + const terminal = createInterface({ + input: process.stdin, + output: process.stdout, + }) + try { + return (await terminal.question(`${message}\n> `)) === CONFIRMATION + } finally { + terminal.close() + } +} + +function integrity(bytes) { + return `sha512-${createHash('sha512').update(bytes).digest('base64')}` +} + +export function matchesPublished(pkg, metadata) { + if ( + metadata?.name !== pkg.name || + metadata?.version !== pkg.version || + !metadata.dist?.integrity?.split(/\s+/).includes(pkg.integrity) + ) { + throw new Error( + `Published ${pkg.name}@${pkg.version} does not match the packed SHA-512 integrity; it will not be overwritten.` + ) + } +} + +async function manifests(root) { + const result = [] + for (const [directory, name] of PACKAGES) { + const folder = path.join(root, 'packages', directory) + const manifest = JSON.parse( + await readFile(path.join(folder, 'package.json'), 'utf8') + ) + if ( + manifest.name !== name || + manifest.private || + !STABLE_VERSION.test(manifest.version) + ) { + throw new Error(`Expected public ${name} with a stable x.y.z version.`) + } + if ( + manifest.publishConfig?.access !== 'public' || + (manifest.publishConfig.registry && + manifest.publishConfig.registry !== REGISTRY) || + (manifest.publishConfig.tag && manifest.publishConfig.tag !== 'latest') || + manifest.publishConfig.directory + ) { + throw new Error(`Unexpected publish configuration in ${name}.`) + } + result.push({ folder, manifest }) + } + if (result[0].manifest.version !== result[2].manifest.version) { + throw new Error( + 'Schema and CLI versions must match for their coordinated release.' + ) + } + return result +} + +async function gitState(run, root, publish) { + const git = (args) => run('git', args, { cwd: root, capture: true }) + const commit = await git(['rev-parse', 'HEAD']) + const branch = await git(['branch', '--show-current']) + const dirty = + (await git(['status', '--porcelain', '--untracked-files=normal'])).length > + 0 + if (publish) { + if (branch !== 'main' || dirty) + throw new Error( + 'Publication requires a clean main checkout, including untracked files.' + ) + const remote = await git([ + 'ls-remote', + '--exit-code', + 'origin', + 'refs/heads/main', + ]) + if (remote.split(/\s+/)[0] !== commit) + throw new Error( + 'Local HEAD must equal origin/main; fetch and reconcile main first.' + ) + } + return { commit, branch: branch || '(detached)', dirty } +} + +export async function inspectArchive(archive, source, versions, run = execute) { + const cwd = path.dirname(archive) + const entries = ( + await run('tar', ['-tzf', archive], { cwd, capture: true }) + ).split(/\r?\n/) + if ( + entries.some( + (entry) => + !entry.startsWith('package/') || entry.split('/').includes('..') + ) + ) { + throw new Error(`Unexpected archive path in ${source.name}.`) + } + const packed = JSON.parse( + await run('tar', ['-xOzf', archive, 'package/package.json'], { + cwd, + capture: true, + }) + ) + if ( + packed.name !== source.name || + packed.version !== source.version || + packed.private + ) { + throw new Error(`Packed identity differs from source: ${source.name}.`) + } + if ( + packed.publishConfig?.registry && + packed.publishConfig.registry !== REGISTRY + ) { + throw new Error(`Unexpected packed registry in ${source.name}.`) + } + if ( + packed.publishConfig?.access !== source.publishConfig?.access || + (packed.publishConfig?.tag && packed.publishConfig.tag !== 'latest') || + packed.publishConfig?.directory + ) { + throw new Error( + `Unexpected packed publish configuration in ${source.name}.` + ) + } + const required = [ + source.main, + source.types, + ...(typeof source.bin === 'string' + ? [source.bin] + : Object.values(source.bin ?? {})), + ...(source.files ?? []).filter((file) => path.extname(file)), + ].filter(Boolean) + for (const file of required) { + if (!entries.includes(`package/${file}`)) + throw new Error(`Missing packed file ${source.name}: ${file}.`) + } + for (const field of [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + for (const [name, range] of Object.entries(packed[field] ?? {})) { + if (/^(workspace|link|file):/.test(range)) + throw new Error(`Unresolved ${field} in ${source.name}: ${name}.`) + if ( + source[field]?.[name] === 'workspace:*' && + range !== versions.get(name) + ) { + throw new Error( + `Incorrect packed workspace dependency ${name} in ${source.name}.` + ) + } + } + for (const [name, range] of Object.entries(source[field] ?? {})) { + if ( + range === 'workspace:*' && + packed[field]?.[name] !== versions.get(name) + ) { + throw new Error( + `Missing packed workspace dependency ${name} in ${source.name}.` + ) + } + } + } + if ( + source.name === '@motrix/plugin-cli' && + Object.keys(packed.dependencies ?? {}).some((name) => + name.startsWith('@motrix/') + ) + ) { + throw new Error('The packed CLI must inline its Motrix SDK dependencies.') + } + const bytes = await readFile(archive) + return { + name: source.name, + version: source.version, + file: path.basename(archive), + bytes: bytes.length, + sha256: createHash('sha256').update(bytes).digest('hex'), + integrity: integrity(bytes), + status: 'prepared', + } +} + +export async function runRelease( + { publish = false, root = ROOT } = {}, + dependencies = {} +) { + const run = dependencies.execute ?? execute + const lookup = dependencies.readVersion ?? readVersion + const ask = dependencies.confirm ?? confirm + const wait = + dependencies.wait ?? + ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) + const log = dependencies.log ?? console.log + const env = dependencies.env ?? process.env + const interactive = + dependencies.interactive ?? + Boolean(process.stdin.isTTY && process.stdout.isTTY) + if (publish && (env.CI || !interactive)) + throw new Error( + 'Publication is human-run only: use an interactive terminal outside CI.' + ) + const rootManifest = JSON.parse( + await readFile(path.join(root, 'package.json'), 'utf8') + ) + const expectedPnpm = /^pnpm@([^+]+)(?:\+.*)?$/.exec( + rootManifest.packageManager + )?.[1] + const pnpmVersion = await run('pnpm', ['--version'], { + cwd: root, + capture: true, + }) + if (!expectedPnpm || pnpmVersion !== expectedPnpm) + throw new Error( + `Use the pinned package manager ${rootManifest.packageManager}; received pnpm ${pnpmVersion}.` + ) + const source = await gitState(run, root, publish) + const packages = await manifests(root) + const versions = new Map( + packages.map(({ manifest }) => [manifest.name, manifest.version]) + ) + const releaseRoot = path.join(root, 'dist', 'release') + await mkdir(releaseRoot, { recursive: true }) + const directory = await mkdtemp(path.join(releaseRoot, 'sdk-')) + const reportPath = path.join(directory, 'release.json') + const report = { + mode: publish ? 'publish' : 'dry-run', + source, + pnpmVersion, + registry: REGISTRY, + phase: 'checking', + packages: [], + } + const save = () => + writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`) + await save() + try { + for (const args of [ + ['install', '--frozen-lockfile'], + ['run', 'lint'], + ['run', 'check:facade'], + ['run', 'build'], + ['run', 'typecheck'], + ['run', 'test'], + ]) + await run('pnpm', args, { cwd: root }) + report.phase = 'packing' + await save() + for (const { folder, manifest } of packages) { + await run('pnpm', ['pack', '--pack-destination', directory], { + cwd: folder, + }) + const archive = path.join( + directory, + `${manifest.name.replace('@', '').replace('/', '-')}-${manifest.version}.tgz` + ) + report.packages.push( + await inspectArchive(archive, manifest, versions, run) + ) + await save() + } + log(`Release artifacts: ${directory}`) + for (const pkg of report.packages) + log(`${pkg.name}@${pkg.version} ${pkg.integrity}`) + if (!publish) { + report.phase = 'prepared' + await save() + log('Dry run complete. No registry lookup or publication was performed.') + return report + } + const unchanged = async () => { + const current = await gitState(run, root, true) + if (current.commit !== source.commit) + throw new Error('Source commit changed during release preparation.') + for (const pkg of report.packages) { + if ( + integrity(await readFile(path.join(directory, pkg.file))) !== + pkg.integrity + ) { + throw new Error(`Archive changed after validation: ${pkg.file}.`) + } + } + } + await unchanged() + // Preflight the entire batch before uploading even its first package. + report.phase = 'registry-preflight' + for (const pkg of report.packages) { + const existing = await lookup(pkg.name, pkg.version) + if (existing) matchesPublished(pkg, existing) + pkg.status = existing ? 'already-published' : 'pending' + log(`${pkg.name}@${pkg.version}: ${pkg.status}`) + } + await save() + if (report.packages.every((pkg) => pkg.status === 'already-published')) { + report.phase = 'complete' + await save() + return report + } + if ( + !(await ask( + `Type "${CONFIRMATION}" to upload the pending packages above to ${REGISTRY}` + )) + ) { + throw new Error('Publication cancelled; no packages were uploaded.') + } + await unchanged() + report.phase = 'publishing' + for (const pkg of report.packages) { + if (pkg.status === 'already-published') continue + await unchanged() + // A version may have appeared during confirmation. Never overwrite it. + const existing = await lookup(pkg.name, pkg.version) + if (existing) { + matchesPublished(pkg, existing) + pkg.status = 'already-published' + await save() + continue + } + pkg.status = 'publishing' + await save() + await run( + 'pnpm', + [ + 'publish', + path.join(directory, pkg.file), + '--access', + 'public', + '--registry', + REGISTRY, + '--tag', + 'latest', + '--publish-branch', + 'main', + ], + { cwd: root } + ) + let verified = false + for (let attempt = 0; attempt < 15; attempt++) { + const metadata = await lookup(pkg.name, pkg.version) + if (metadata) { + matchesPublished(pkg, metadata) + verified = true + break + } + if (attempt < 14) await wait(2000) + } + if (!verified) + throw new Error( + `Publication of ${pkg.name}@${pkg.version} is not yet verifiable. Check npm before retrying.` + ) + pkg.status = 'published' + await save() + } + report.phase = 'complete' + await save() + log('All four package versions are verified on npm.') + return report + } catch (error) { + report.phase = 'failed' + report.error = error.message + await save() + log( + `Release stopped. Preserve artifacts and inspect ${reportPath} before retrying.` + ) + throw error + } +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + try { + const options = parseArgs(process.argv.slice(2)) + if (options.help) { + console.log( + 'Usage: pnpm run release [-- --dry-run | -- --publish]\nDefault: validate, build and pack only. --publish requires a human terminal and confirmation.' + ) + } else { + await runRelease(options) + } + } catch (error) { + console.error(error.message) + process.exitCode = 1 + } +} diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs new file mode 100644 index 0000000..27b044f --- /dev/null +++ b/scripts/release.test.mjs @@ -0,0 +1,497 @@ +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + mkdir, + mkdtemp, + readdir, + readFile, + rm, + writeFile, +} from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { + inspectArchive, + PACKAGES, + parseArgs, + REGISTRY, + runRelease, +} from './release.mjs' + +const execFileAsync = promisify(execFile) +const hash = (bytes) => + `sha512-${createHash('sha512').update(bytes).digest('base64')}` + +async function fixture(t) { + const root = await mkdtemp(path.join(os.tmpdir(), 'sdk-release-test-')) + t.after(() => rm(root, { recursive: true, force: true })) + await writeFile( + path.join(root, 'package.json'), + JSON.stringify({ packageManager: 'pnpm@11.22.0' }) + ) + for (const [directory, name] of PACKAGES) { + const folder = path.join(root, 'packages', directory) + await mkdir(folder, { recursive: true }) + await writeFile( + path.join(folder, 'package.json'), + JSON.stringify({ + name, + version: '2.2.0', + main: 'dist/index.js', + types: 'dist/index.d.ts', + files: ['dist'], + publishConfig: { access: 'public' }, + ...(name === 'create-motrix-plugin' + ? { dependencies: { '@motrix/plugin-cli': 'workspace:*' } } + : {}), + }) + ) + } + const state = { + commands: [], + archives: new Map(), + published: new Map(), + uploads: [], + commit: 'a'.repeat(40), + branch: 'main', + dirty: '', + remote: 'a'.repeat(40), + askCount: 0, + lookups: 0, + fail: null, + packMutation: null, + onPublish: null, + } + const metadata = (name) => { + const entry = [...state.archives.values()].find( + (value) => value.packed.name === name + ) + return { + name, + version: entry.packed.version, + dist: { integrity: hash(entry.bytes) }, + } + } + const execute = async (command, args, { cwd }) => { + const label = [command, ...args].join(' ') + state.commands.push(label) + if (state.fail && label.startsWith(state.fail)) + throw new Error('simulated command failure') + if (command === 'git') { + if (args[0] === 'rev-parse') return state.commit + if (args[0] === 'branch') return state.branch + if (args[0] === 'status') return state.dirty + if (args[0] === 'ls-remote') return `${state.remote}\trefs/heads/main` + } + if (command === 'tar') { + const entry = state.archives.get(args[1]) + return args[0] === '-tzf' + ? entry.files.join('\n') + : JSON.stringify(entry.packed) + } + if (command === 'pnpm') { + if (args[0] === '--version') return '11.22.0' + if (args[0] === 'pack') { + const packed = JSON.parse( + await readFile(path.join(cwd, 'package.json'), 'utf8') + ) + if (packed.dependencies) + packed.dependencies['@motrix/plugin-cli'] = '2.2.0' + const file = path.join( + args[2], + `${packed.name.replace('@', '').replace('/', '-')}-${packed.version}.tgz` + ) + const bytes = Buffer.from(JSON.stringify(packed)) + const entry = { + packed, + bytes, + file, + files: [ + 'package/package.json', + 'package/dist/index.js', + 'package/dist/index.d.ts', + ], + } + if (state.packMutation) state.packMutation(entry) + await writeFile(file, bytes) + state.archives.set(file, entry) + } + if (args[0] === 'publish') { + const { packed } = state.archives.get(args[1]) + state.uploads.push(packed.name) + if (state.onPublish) await state.onPublish(packed.name) + else state.published.set(packed.name, metadata(packed.name)) + } + return '' + } + throw new Error(`Unexpected command ${label}`) + } + const dependencies = { + execute, + env: {}, + interactive: true, + log: () => {}, + wait: async () => {}, + readVersion: async (name) => { + state.lookups++ + return state.published.get(name) ?? null + }, + confirm: async () => { + state.askCount++ + return true + }, + } + const report = async () => { + const dirs = await readdir(path.join(root, 'dist/release')) + return JSON.parse( + await readFile( + path.join(root, 'dist/release', dirs.at(-1), 'release.json'), + 'utf8' + ) + ) + } + return { root, state, dependencies, metadata, report } +} + +test('CLI defaults to dry-run and has no confirmation or validation bypass flags', () => { + assert.deepEqual(parseArgs([]), { publish: false }) + assert.deepEqual(parseArgs(['--', '--dry-run']), { publish: false }) + assert.deepEqual(parseArgs(['--', '--publish']), { publish: true }) + for (const args of [ + ['--yes'], + ['--force'], + ['--skip-checks'], + ['--dry-run', '--publish'], + ]) { + assert.throws(() => parseArgs(args)) + } +}) + +test('CLI help exits without running the release pipeline', async () => { + const script = new URL('./release.mjs', import.meta.url) + const { stdout } = await execFileAsync(process.execPath, [ + fileURLToPath(script), + '--help', + ]) + assert.match(stdout, /Default: validate, build and pack only/) +}) + +test('dry-run in CI checks and packs every package without registry access or confirmation', async (t) => { + const f = await fixture(t) + const result = await runRelease( + { root: f.root }, + { ...f.dependencies, env: { CI: 'true' }, interactive: false } + ) + assert.equal(result.phase, 'prepared') + assert.equal(result.packages.length, 4) + assert.equal(f.state.lookups, 0) + assert.equal(f.state.askCount, 0) + assert.deepEqual(f.state.uploads, []) + const steps = f.state.commands.filter((s) => s.startsWith('pnpm ')) + assert.deepEqual(steps.slice(1, 7), [ + 'pnpm install --frozen-lockfile', + 'pnpm run lint', + 'pnpm run check:facade', + 'pnpm run build', + 'pnpm run typecheck', + 'pnpm run test', + ]) + assert.match(steps[7], /^pnpm pack /) + assert.equal( + (await f.report()).packages[3].integrity, + result.packages[3].integrity + ) +}) + +for (const [label, values] of [ + ['CI', { env: { CI: 'true' } }], + ['non-interactive input', { interactive: false }], +]) { + test(`publication refuses ${label} before any command executes`, async (t) => { + const f = await fixture(t) + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, ...values } + ), + /human-run only/ + ) + assert.deepEqual(f.state.commands, []) + }) +} + +for (const [key, value] of [ + ['branch', 'feature'], + ['dirty', ' M package.json'], + ['remote', 'b'.repeat(40)], +]) { + test(`publication refuses invalid Git state: ${key}`, async (t) => { + const f = await fixture(t) + f.state[key] = value + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + /clean main|origin\/main/ + ) + assert.equal( + f.state.commands.some((s) => s.startsWith('pnpm install')), + false + ) + }) +} + +test('a failed quality gate prevents packing and publication', async (t) => { + const f = await fixture(t) + f.state.fail = 'pnpm run typecheck' + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + /simulated/ + ) + assert.equal(f.state.archives.size, 0) + assert.equal(f.state.lookups, 0) + assert.deepEqual(f.state.uploads, []) + assert.equal((await f.report()).phase, 'failed') +}) + +test('a mismatched schema/CLI version fails before installation', async (t) => { + const f = await fixture(t) + const p = path.join(f.root, 'packages/plugin-cli/package.json') + const manifest = JSON.parse(await readFile(p, 'utf8')) + manifest.version = '2.3.0' + await writeFile(p, JSON.stringify(manifest)) + await assert.rejects( + runRelease({ root: f.root }, f.dependencies), + /Schema and CLI/ + ) + assert.equal( + f.state.commands.some((s) => s.startsWith('pnpm install')), + false + ) +}) + +for (const [label, mutate, message] of [ + [ + 'missing type entrypoint', + (entry) => { + entry.files = entry.files.filter((f) => !f.endsWith('.d.ts')) + }, + /Missing packed file/, + ], + [ + 'unexpected publish registry', + (entry) => { + entry.packed.publishConfig.registry = 'https://invalid.example/' + }, + /Unexpected packed registry/, + ], + [ + 'unexpected publish tag', + (entry) => { + entry.packed.publishConfig.tag = 'next' + }, + /Unexpected packed publish configuration/, + ], + [ + 'wrong identity', + (entry) => { + entry.packed.name = 'unexpected-package' + }, + /Packed identity/, + ], + [ + 'workspace dependency', + (entry) => { + entry.packed.dependencies = { test: 'workspace:*' } + }, + /Unresolved/, + ], + [ + 'wrong wrapper CLI dependency', + (entry) => { + if (entry.packed.name === 'create-motrix-plugin') + entry.packed.dependencies['@motrix/plugin-cli'] = '2.1.1' + }, + /workspace dependency/, + ], +]) { + test(`archive validation rejects ${label} before registry access`, async (t) => { + const f = await fixture(t) + f.state.packMutation = mutate + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + message + ) + assert.equal(f.state.lookups, 0) + assert.deepEqual(f.state.uploads, []) + }) +} + +test('a conflict in the last registry version prevents the entire upload batch', async (t) => { + const f = await fixture(t) + f.state.published.set('create-motrix-plugin', { + name: 'create-motrix-plugin', + version: '2.2.0', + dist: { integrity: 'sha512-wrong' }, + }) + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + /will not be overwritten/ + ) + assert.deepEqual(f.state.uploads, []) + assert.equal(f.state.askCount, 0) +}) + +test('registry errors are not treated as absent versions', async (t) => { + const f = await fixture(t) + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { + ...f.dependencies, + readVersion: async () => { + throw new Error('registry unavailable') + }, + } + ), + /registry unavailable/ + ) + assert.deepEqual(f.state.uploads, []) +}) + +test('declining confirmation uploads nothing', async (t) => { + const f = await fixture(t) + await assert.rejects( + runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, confirm: async () => false } + ), + /cancelled/ + ) + assert.deepEqual(f.state.uploads, []) +}) + +test('confirmation cannot authorize archives modified after validation', async (t) => { + const f = await fixture(t) + const confirm = async () => { + await writeFile([...f.state.archives.keys()][3], 'tampered') + return true + } + await assert.rejects( + runRelease({ publish: true, root: f.root }, { ...f.dependencies, confirm }), + /Archive changed/ + ) + assert.deepEqual(f.state.uploads, []) +}) + +test('source changes during confirmation prevent uploads', async (t) => { + const f = await fixture(t) + const confirm = async () => { + f.state.dirty = ' M source.ts' + return true + } + await assert.rejects( + runRelease({ publish: true, root: f.root }, { ...f.dependencies, confirm }), + /clean main/ + ) + assert.deepEqual(f.state.uploads, []) +}) + +test('publishes in dependency order and verifies each version before the next', async (t) => { + const f = await fixture(t) + const result = await runRelease( + { publish: true, root: f.root }, + f.dependencies + ) + assert.deepEqual( + f.state.uploads, + PACKAGES.map(([, name]) => name) + ) + assert.equal(result.phase, 'complete') + assert.equal(f.state.askCount, 1) + assert.ok(result.packages.every((p) => p.status === 'published')) + assert.ok( + f.state.commands + .filter((s) => s.startsWith('pnpm publish')) + .every((s) => + s.includes(`--registry ${REGISTRY} --tag latest --publish-branch main`) + ) + ) +}) + +test('a partial release resumes by skipping only byte-identical published versions', async (t) => { + const f = await fixture(t) + const lookup = async (name) => + name === PACKAGES[0][1] + ? f.metadata(name) + : (f.state.published.get(name) ?? null) + const result = await runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: lookup } + ) + assert.deepEqual( + f.state.uploads, + PACKAGES.slice(1).map(([, name]) => name) + ) + assert.equal(result.packages[0].status, 'already-published') +}) + +test('an already-complete identical batch needs no confirmation or uploads', async (t) => { + const f = await fixture(t) + const result = await runRelease( + { publish: true, root: f.root }, + { ...f.dependencies, readVersion: async (name) => f.metadata(name) } + ) + assert.equal(result.phase, 'complete') + assert.equal(f.state.askCount, 0) + assert.deepEqual(f.state.uploads, []) +}) + +test('a publishing error stops later packages and leaves uncertain progress in the report', async (t) => { + const f = await fixture(t) + f.state.onPublish = async (name) => { + if (name === PACKAGES[1][1]) throw new Error('upload connection lost') + f.state.published.set(name, f.metadata(name)) + } + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + /connection lost/ + ) + assert.deepEqual( + f.state.uploads, + PACKAGES.slice(0, 2).map(([, name]) => name) + ) + assert.deepEqual( + (await f.report()).packages.map((p) => p.status), + ['published', 'publishing', 'pending', 'pending'] + ) +}) + +test('unverifiable publication stops without retrying the upload or later packages', async (t) => { + const f = await fixture(t) + f.state.onPublish = async () => {} + await assert.rejects( + runRelease({ publish: true, root: f.root }, f.dependencies), + /not yet verifiable/ + ) + assert.deepEqual(f.state.uploads, [PACKAGES[0][1]]) +}) + +test('real gzip tar archives are inspected without extracting files to disk', async (t) => { + const root = await mkdtemp(path.join(os.tmpdir(), 'sdk-release-tar-')) + t.after(() => rm(root, { recursive: true, force: true })) + const source = { name: 'sample', version: '1.0.0', main: 'index.js' } + await mkdir(path.join(root, 'package')) + await writeFile( + path.join(root, 'package/package.json'), + JSON.stringify(source) + ) + await writeFile(path.join(root, 'package/index.js'), 'export {}\n') + const archive = path.join(root, 'sample.tgz') + await execFileAsync('tar', ['-czf', archive, 'package'], { cwd: root }) + const result = await inspectArchive(archive, source, new Map()) + assert.equal(result.name, 'sample') + assert.equal(result.integrity, hash(await readFile(archive))) +})