steps.ts
This file
Path
scripts/lib/release/steps.ts
639 lines · 18.9 KiB · TypeScript
Last changed by
Merge build/1104 into mainoscabrielbefore adoption82cc398
History of this fileTake it
1/**2 * What each step of a release does on this machine, over the3 * plan `scripts/lib/release.ts` makes:4 *5 * - `tsdown`: the CLI's `bun run build` in `apps/cli`, with both targets6 * (`dist/`, and `dist/bin/<target>/` per target), stamped with the7 * release's version (what `--version` prints);8 * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the9 * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its10 * README and the repo's licence;11 * - `copySkills`: the platform's skill (`@repo/agent-kit`'s12 * `platformSkill` over `commandDocs(Contracts)`) into its `skills/`;13 * - `compile`: each target's binary, copied to `apps/cli/release/<slug>-<target>`;14 * - `installScript` and `checksums`: `apps/cli/release/install.sh` and15 * `SHA256SUMS`;16 * - `upload`: the version's files into the stage's `releases-<stage>`17 * bucket with Wrangler's own login, then `releases/manifest.json` last;18 * - `publish`: `npm publish` of the staged package, which the plan allows19 * only when a person runs it (H2).20 *21 * The package is staged beside the binaries rather than in `dist/`: its22 * manifest names `./dist/…` and `./skills` from the package's root, and23 * `dist/bin/` holds the binaries, which npm must not ship.24 */25import { commandDocs } from "@repo/agent-kit/command-doc";26import { platformSkill } from "@repo/agent-kit/platform";27import { Brand } from "@repo/brand";28import { Contracts } from "@repo/protocol/contracts";29import {30 Array as Arr,31 Console,32 Crypto,33 Effect,34 FileSystem,35 Match,36 Option,37 Order,38 Path,39 Schema,40 Stream,41} from "effect";42import { ChildProcess, ChildProcessSpawner } from "effect/process";4344import { resources } from "../../../infra/stages.ts";45import type { Stage } from "../../../infra/stages.ts";46import {47 binaryName,48 checksumsFile,49 importedPackages,50 installScript,51 machineOf,52 MANIFEST_KEY,53 namedFiles,54 pinnedDependencies,55 publishManifest,56 ReleaseManifest,57 releaseManifest,58 targets,59 unreleased,60 uploads,61} from "../release.ts";62import type { ReleaseAsset, ReleaseStep } from "../release.ts";63import { packageReadme } from "./readme.ts";6465/** A step could not finish; nothing after it ran. */66export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(67 "ReleaseFailed",68 { reason: Schema.String, step: Schema.String }69) {70 override get message() {71 return `${this.step}: ${this.reason}`;72 }73}7475/** Where a release reads and writes, from the repo root. */76export interface Layout {77 readonly root: string;78 /** `apps/cli`, where the CLI's build runs. */79 readonly cli: string;80 /** `apps/cli/dist`, the CLI's build. */81 readonly dist: string;82 /** `apps/cli/release`: the binaries, the install script and the checksums. */83 readonly release: string;84 /** `apps/cli/release/npm`: the npm package, as `npm publish` takes it. */85 readonly npm: string;86}8788export const layoutOf = (root: string) =>89 Effect.map(Path.Path, (path): Layout => {90 const cli = path.join(root, "apps", "cli");91 const release = path.join(cli, "release");9293 return {94 cli,95 dist: path.join(cli, "dist"),96 npm: path.join(release, "npm"),97 release,98 root,99 };100 });101102/** One release: its version, and the origin its install script fetches from. */103export interface Release {104 readonly version: string;105 /** The platform's public origin, without a trailing `/`. */106 readonly origin: string;107 /** The stage an upload goes to. */108 readonly stage: Option.Option<Stage>;109}110111/** The command a person runs from the repo root to publish the staged package. */112export const publishCommand = (layout: Layout, path: Path.Path) =>113 `npm publish ${path.relative(layout.root, layout.npm)} --access public`;114115const failed = (step: ReleaseStep, reason: string) =>116 new ReleaseFailed({ reason, step });117118/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */119const run = (120 step: ReleaseStep,121 command: string,122 args: readonly string[],123 cwd: string124) =>125 Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>126 spawner.exitCode(127 ChildProcess.make(command, args, {128 cwd,129 stderr: "inherit",130 stdin: "inherit",131 stdout: "inherit",132 })133 )134 ).pipe(135 Effect.mapError(({ message }) => failed(step, message)),136 Effect.filterOrFail(137 (exitCode) => exitCode === 0,138 (exitCode) =>139 failed(step, `${command} ${args.join(" ")} exited ${exitCode}`)140 ),141 Effect.asVoid142 );143144/** What the release reads of a package manifest. */145const PackageJson = Schema.fromJsonString(146 Schema.Struct({147 dependencies: Schema.optionalKey(148 Schema.Record(Schema.String, Schema.String)149 ),150 version: Schema.optionalKey(Schema.String),151 workspaces: Schema.optionalKey(152 Schema.Struct({153 catalog: Schema.optionalKey(154 Schema.Record(Schema.String, Schema.String)155 ),156 })157 ),158 })159);160161const readPackage = (step: ReleaseStep, file: string) =>162 Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(file)).pipe(163 Effect.flatMap(Schema.decodeEffect(PackageJson)),164 Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))165 );166167/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */168const builtFiles = (layout: Layout) =>169 Effect.gen(function* () {170 const fs = yield* FileSystem.FileSystem;171 const path = yield* Path.Path;172 const names = yield* fs.readDirectory(layout.dist);173174 const files = yield* Effect.filter(175 names.filter((name) => /\.(?:js|d\.ts)$/u.test(name)),176 (name) =>177 Effect.map(178 fs.stat(path.join(layout.dist, name)),179 ({ type }) => type === "File"180 )181 );182183 return Arr.sort(files, Order.String);184 });185186/** `manifest`: the npm package, staged afresh from the build. */187const stagePackage = (layout: Layout, release: Release) =>188 Effect.gen(function* () {189 const fs = yield* FileSystem.FileSystem;190 const path = yield* Path.Path;191192 const files = yield* builtFiles(layout).pipe(193 Effect.filterOrFail(194 (names) => names.includes("bin.js"),195 () =>196 failed(197 "manifest",198 "apps/cli/dist has no bin.js: build first (--build)"199 )200 )201 );202203 yield* fs.remove(layout.npm, { force: true, recursive: true });204 yield* fs.makeDirectory(path.join(layout.npm, "dist"), { recursive: true });205206 const sources = yield* Effect.forEach(files, (name) =>207 fs208 .copyFile(209 path.join(layout.dist, name),210 path.join(layout.npm, "dist", name)211 )212 .pipe(Effect.andThen(fs.readFileString(path.join(layout.dist, name))))213 );214215 const cli = yield* readPackage(216 "manifest",217 path.join(layout.cli, "package.json")218 );219220 const workspace = yield* readPackage(221 "manifest",222 path.join(layout.root, "package.json")223 );224225 const dependencies = yield* Effect.fromResult(226 pinnedDependencies({227 catalog: workspace.workspaces?.catalog ?? {},228 declared: cli.dependencies ?? {},229 imported: Arr.sort(230 Arr.dedupe(sources.flatMap(importedPackages)),231 Order.String232 ),233 })234 ).pipe(235 Effect.mapError(({ packages }) =>236 failed(237 "manifest",238 `the build imports ${packages.join(", ")}, which apps/cli/package.json doesn't pin`239 )240 )241 );242243 const manifest = publishManifest(Brand, {244 dependencies,245 version: release.version,246 });247248 yield* fs.writeFileString(249 path.join(layout.npm, "package.json"),250 `${JSON.stringify(manifest, undefined, 2)}\n`251 );252253 yield* fs.writeFileString(254 path.join(layout.npm, "README.md"),255 packageReadme({ brand: Brand, version: release.version })256 );257258 yield* fs.copyFile(259 path.join(layout.root, "LICENSE"),260 path.join(layout.npm, "LICENSE")261 );262263 return manifest;264 });265266/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */267const writeSkills = (layout: Layout) =>268 Effect.gen(function* () {269 const fs = yield* FileSystem.FileSystem;270 const path = yield* Path.Path;271 const skills = yield* platformSkill({ commands: commandDocs(Contracts) });272273 yield* Effect.forEach(skills, ({ content, path: file }) =>274 Effect.andThen(275 fs.makeDirectory(path.dirname(path.join(layout.npm, file)), {276 recursive: true,277 }),278 fs.writeFileString(path.join(layout.npm, file), content)279 )280 );281 });282283/** `compile`: each target's binary, as the release folder and the platform name it. */284const collectBinaries = (layout: Layout) =>285 Effect.gen(function* () {286 const fs = yield* FileSystem.FileSystem;287 const path = yield* Path.Path;288289 yield* fs.makeDirectory(layout.release, { recursive: true });290291 return yield* Effect.forEach(targets, (target) =>292 Effect.gen(function* () {293 const built = path.join(294 layout.dist,295 "bin",296 machineOf(target),297 Brand.cli298 );299300 const released = path.join(layout.release, binaryName(Brand, target));301302 yield* fs.exists(built).pipe(303 Effect.filterOrFail(304 (exists) => exists,305 () =>306 failed(307 "compile",308 `${path.relative(layout.root, built)} is missing: build first (--build)`309 )310 )311 );312313 yield* fs.copyFile(built, released);314 yield* fs.chmod(released, 0o755);315316 return released;317 })318 );319 });320321/** The files a release serves under its version: each binary, and the install script. */322const releasedFiles = [323 ...targets.map((target) => binaryName(Brand, target)),324 "install.sh",325];326327/** A file's sha256, as `sha256sum` prints it, and its size. */328const assetOf = (file: string) =>329 Effect.gen(function* () {330 const fs = yield* FileSystem.FileSystem;331 const crypto = yield* Crypto.Crypto;332 const bytes = yield* fs.readFile(file);333 const digest = yield* crypto.digest("SHA-256", bytes);334335 return {336 bytes: bytes.length,337 sha256: [...digest]338 .map((byte) => byte.toString(16).padStart(2, "0"))339 .join(""),340 } satisfies ReleaseAsset;341 });342343/** Each released file in the release folder, by name. */344const assetsIn = (layout: Layout) =>345 Effect.flatMap(Path.Path, (path) =>346 Effect.forEach(releasedFiles, (name) =>347 Effect.map(348 assetOf(path.join(layout.release, name)),349 (asset) => [name, asset] as const350 )351 )352 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));353354/** `checksums`: `SHA256SUMS` beside the files it lists. */355const writeChecksums = (layout: Layout) =>356 Effect.gen(function* () {357 const fs = yield* FileSystem.FileSystem;358 const path = yield* Path.Path;359 const assets = yield* assetsIn(layout);360361 yield* fs.writeFileString(362 path.join(layout.release, "SHA256SUMS"),363 checksumsFile(assets)364 );365 });366367/** How the bucket keeps each file: the platform sets its own reply headers. */368const contentTypes = new Map([369 ["install.sh", "text/x-shellscript; charset=utf-8"],370 ["manifest.json", "application/json"],371]);372373/** A binary is bytes; the install script and the manifest are text. */374const contentTypeOf = (file: string) =>375 contentTypes.get(file) ?? "application/octet-stream";376377/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */378const wranglerOf = (layout: Layout, path: Path.Path) =>379 path.join(380 layout.root,381 "apps",382 "platform",383 "node_modules",384 ".bin",385 "wrangler"386 );387388/**389 * Runs Wrangler in `cwd` with its own login (never the read-mostly infra390 * token; `infra/.env.schema`), and gives its exit code and everything it391 * printed.392 */393const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>394 Effect.gen(function* () {395 const path = yield* Path.Path;396 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;397398 const child = yield* spawner.spawn(399 ChildProcess.make(wranglerOf(layout, path), args, {400 cwd,401 env: {402 CLOUDFLARE_API_TOKEN: undefined,403 WRANGLER_SEND_METRICS: "false",404 },405 extendEnv: true,406 })407 );408409 const [output, exitCode] = yield* Effect.all(410 [Stream.mkString(Stream.decodeText(child.all)), child.exitCode],411 { concurrency: "unbounded" }412 );413414 return { exitCode: Number(exitCode), output };415 }).pipe(416 Effect.scoped,417 Effect.mapError(({ message }) =>418 failed("upload", `wrangler didn't run: ${message}`)419 )420 );421422/** What Wrangler prints when a bucket holds no object under a key. */423const NO_SUCH_KEY = "The specified key does not exist";424425/** The manifest the stage's bucket holds, if it holds one. */426const previousManifest = (layout: Layout, bucket: string, scratch: string) =>427 Effect.gen(function* () {428 const fs = yield* FileSystem.FileSystem;429 const path = yield* Path.Path;430 const file = path.join(scratch, "previous.json");431432 const got = yield* wrangler(layout, scratch, [433 "r2",434 "object",435 "get",436 `${bucket}/${MANIFEST_KEY}`,437 "--remote",438 "--file",439 file,440 ]);441442 if (got.exitCode !== 0) {443 return got.output.includes(NO_SUCH_KEY)444 ? Option.none()445 : yield* failed(446 "upload",447 `wrangler r2 object get ${bucket}/${MANIFEST_KEY} failed:\n${got.output.trim()}`448 );449 }450451 const text = yield* fs.readFileString(file);452453 return Option.some(454 yield* Schema.decodeEffect(Schema.fromJsonString(ReleaseManifest))(455 text456 ).pipe(457 Effect.mapError(({ message }) =>458 failed(459 "upload",460 `${bucket}/${MANIFEST_KEY} doesn't decode, so the platform answers 503 until it is fixed by hand: ${message}`461 )462 )463 )464 );465 });466467/** `upload`: the version's files into the stage's own bucket, and the manifest last. */468const upload = (layout: Layout, release: Release) =>469 Effect.gen(function* () {470 const fs = yield* FileSystem.FileSystem;471 const path = yield* Path.Path;472473 const stage = yield* Effect.fromOption(release.stage).pipe(474 Effect.mapError(() => failed("upload", "an upload names its --stage"))475 );476477 const bucket = resources(stage).releases;478479 const scratch = yield* fs.makeTempDirectoryScoped({480 prefix: "release-715-",481 });482483 const previous = yield* previousManifest(layout, bucket, scratch);484 const assets = yield* assetsIn(layout);485486 yield* Effect.fromResult(487 unreleased({488 assets,489 previous: Option.getOrUndefined(previous),490 version: release.version,491 })492 ).pipe(Effect.mapError(({ message }) => failed("upload", message)));493494 const manifest = releaseManifest({495 assets,496 previous: Option.getOrUndefined(previous),497 version: release.version,498 });499500 yield* fs.writeFileString(501 path.join(layout.release, "manifest.json"),502 `${yield* Schema.encodeEffect(Schema.fromJsonString(ReleaseManifest))(503 manifest504 ).pipe(Effect.mapError(({ message }) => failed("upload", message)))}\n`505 );506507 for (const { file, key } of uploads({508 files: Object.keys(assets),509 version: release.version,510 })) {511 yield* wrangler(layout, scratch, [512 "r2",513 "object",514 "put",515 `${bucket}/${key}`,516 "--remote",517 "--file",518 path.join(layout.release, file),519 "--content-type",520 contentTypeOf(file),521 ]).pipe(522 Effect.filterOrFail(523 ({ exitCode }) => exitCode === 0,524 ({ output }) =>525 failed(526 "upload",527 `wrangler r2 object put ${bucket}/${key} failed:\n${output.trim()}`528 )529 )530 );531532 yield* Console.log(` uploaded ${bucket}/${key}`);533 }534535 return manifest;536 }).pipe(Effect.scoped);537538/** The paths the staged package's manifest names that it lacks. */539export const missingFromPackage = (layout: Layout, version: string) =>540 Effect.gen(function* () {541 const fs = yield* FileSystem.FileSystem;542 const path = yield* Path.Path;543544 const manifest = publishManifest(Brand, { dependencies: {}, version });545546 return yield* Effect.filter(namedFiles(manifest), (file) =>547 Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)548 );549 });550551/**552 * The staged package is whole and of this release's version, so what553 * `npm publish` ships is what this release built: checked before the554 * publish runs, and before an agent hands its command to a person (H2).555 */556export const publishable = (layout: Layout, release: Release) =>557 Effect.gen(function* () {558 const path = yield* Path.Path;559560 yield* readPackage("publish", path.join(layout.npm, "package.json")).pipe(561 Effect.filterOrFail(562 ({ version }) => version === release.version,563 ({ version }) =>564 failed(565 "publish",566 `the staged package is ${version ?? "unversioned"}, not ${release.version}: run --build --version ${release.version} first`567 )568 )569 );570571 yield* missingFromPackage(layout, release.version).pipe(572 Effect.filterOrFail(573 (missing) => missing.length === 0,574 (missing) =>575 failed("publish", `the staged package lacks ${missing.join(", ")}`)576 )577 );578 });579580/** `publish`: `npm publish` of the staged package, once it is `publishable`. */581const publish = (layout: Layout, release: Release) =>582 Effect.andThen(583 publishable(layout, release),584 run(585 "publish",586 "npm",587 ["publish", layout.npm, "--access", "public"],588 layout.root589 )590 );591592/** `installScript`: the install script for this version, fetching from the release's origin. */593const writeInstallScript = (layout: Layout, release: Release) =>594 Effect.gen(function* () {595 const fs = yield* FileSystem.FileSystem;596 const path = yield* Path.Path;597598 yield* fs.makeDirectory(layout.release, { recursive: true });599600 yield* fs.writeFileString(601 path.join(layout.release, "install.sh"),602 installScript({603 baseUrl: `${release.origin}/releases/${release.version}`,604 brand: Brand,605 version: release.version,606 })607 );608609 yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);610 });611612/** One step, run. */613export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>614 Match.value(step).pipe(615 Match.when("tsdown", () =>616 run(617 "tsdown",618 "bun",619 [620 "run",621 "build",622 "--",623 "--targets",624 targets.join(","),625 "--version",626 release.version,627 ],628 layout.cli629 )630 ),631 Match.when("manifest", () => stagePackage(layout, release)),632 Match.when("copySkills", () => writeSkills(layout)),633 Match.when("compile", () => collectBinaries(layout)),634 Match.when("installScript", () => writeInstallScript(layout, release)),635 Match.when("checksums", () => writeChecksums(layout)),636 Match.when("upload", () => upload(layout, release)),637 Match.when("publish", () => publish(layout, release)),638 Match.exhaustive639 );