Skip to content
Myr

release.ts

This file

Path

scripts/lib/release.ts

536 lines · 18.6 KiB · TypeScript

Last changed by

Merge build/1104 into mainoscabrielbefore adoption82cc398

History of this file

Take it

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

line 1why, one step back
1/**

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 2why, one step back
2 * The release's core: what the CLI's npm package says of

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 3–20why, one step back
3 * itself, which steps a release runs, and what it hands the platform's own
4 * release storage. Pure; `scripts/release.ts` runs it.5 */6import type { Brand } from "@repo/brand";7import { detectHarness } from "@repo/protocol/audit";8import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";910import { ReleaseManifest } from "../../apps/platform/src/releases.ts";11import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";12import { installScriptFor } from "./release/install-script.ts";1314// --- What a release builds for -----------------------------------------------1516/** The machines a release builds a binary for, as Bun names them. */17export type Target = "bun-linux-x64" | "bun-darwin-arm64";1819export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];20

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 21why, one step back
21/** A target as the CLI's build and the platform name it, without Bun's prefix: `linux-x64`. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 22–70why, one step back
22export const machineOf = (target: Target) => target.replace(/^bun-/u, "");
2324/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */25export const binaryName = (brand: typeof Brand, target: Target) =>26 `${brand.slug}-${machineOf(target)}`;2728// --- The npm package's dependencies ------------------------------------------2930/**31 * A module statement as rolldown writes one, at the start of a line: an32 * `import … from "x"` or `export … from "x"`, over any number of lines, or a33 * side-effect `import "x"`. Prose and inline strings are not read, but a34 * template literal's line can start with `import` (`dist/bin.js` holds one:35 * the rules' `/bun` main imports `./job.json`). Such a line naming a36 * package is read as an import, which fails the pin loudly (`Unpinned`)37 * rather than letting an import slip through unpinned.38 */39const STATEMENT =40 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;4142/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */43const packageOf = (specifier: string) =>44 specifier45 .split("/")46 .slice(0, specifier.startsWith("@") ? 2 : 1)47 .join("/");4849/** Whether `specifier` names a package, not a file or a runtime built-in. */50const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);5152/**53 * The packages a built module imports statically, by package name, sorted.54 * A package tsdown keeps external is imported this way; one reached only by55 * a dynamic `import()` would not be listed (none is today).56 */57export const importedPackages = (source: string): readonly string[] =>58 Arr.sort(59 Arr.dedupe(60 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {61 const specifier = groups?.from ?? groups?.bare ?? "";6263 return isPackage(specifier) ? [packageOf(specifier)] : [];64 })65 ),66 Order.String67 );6869/**70 * pi, the harness the package plugs into: a host package, so an optional

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 71why, one step back
71 * peer and never bundled or depended on.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 72–136why, one step back
72 */
73const PI_HOST = "@earendil-works/pi-coding-agent";7475/**76 * Packages the build imports that can't be pinned for npm: the CLI's77 * manifest doesn't declare them, they are workspace packages (tsdown inlines78 * those, so one left is a build fault), or their catalog has no version.79 */80export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {81 packages: Schema.Array(Schema.String),82}) {}8384/** The version a declared specifier pins, with `catalog:` read from the catalog. */85const pinOf = (86 specifier: string | undefined,87 catalogued: string | undefined88) => {89 const version = specifier === "catalog:" ? catalogued : specifier;9091 return version === undefined || /^(?:workspace|catalog):/u.test(version)92 ? undefined93 : version;94};9596/**97 * The published package's `dependencies`: each package the build imports,98 * at the version the CLI's manifest (`declared`) pins, `catalog:` resolved99 * from the workspace's catalog. pi is left out: the adapter imports it from100 * the host that loads it, an optional peer. Every other one is pinned, or101 * none is returned.102 */103export const pinnedDependencies = (input: {104 readonly imported: readonly string[];105 readonly declared: Readonly<Record<string, string>>;106 readonly catalog: Readonly<Record<string, string>>;107}): Result.Result<Readonly<Record<string, string>>, Unpinned> => {108 const pins = input.imported109 .filter((name) => name !== PI_HOST)110 .map(111 (name) =>112 [113 name,114 name.startsWith("@repo/")115 ? undefined116 : pinOf(input.declared[name], input.catalog[name]),117 ] as const118 );119120 const unpinned = pins.flatMap(([name, version]) =>121 version === undefined ? [name] : []122 );123124 return unpinned.length > 0125 ? Result.fail(new Unpinned({ packages: unpinned }))126 : Result.succeed(127 Object.fromEntries(128 pins.flatMap(([name, version]) =>129 version === undefined ? [] : [[name, version]]130 )131 )132 );133};134135// --- The npm package's manifest ----------------------------------------------136

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 137why, one step back
137/** The command line, under Node or Bun: the CLI's npm build. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 138–168why, one step back
138const BIN = "./dist/bin.js";
139140/** A library entry: its code, and the types tsgo declared for it. */141interface LibraryEntry {142 readonly types: string;143 readonly default: string;144}145146/** The npm package's manifest, as `npm publish` reads it. */147export interface PublishManifest {148 readonly bin: Readonly<Record<string, string>>;149 readonly dependencies: Readonly<Record<string, string>>;150 readonly description: string;151 readonly exports: Readonly<Record<string, string | LibraryEntry>>;152 readonly files: readonly string[];153 readonly keywords: readonly string[];154 readonly license: "MIT";155 readonly name: string;156 readonly peerDependencies: Readonly<Record<string, string>>;157 readonly peerDependenciesMeta: Readonly<158 Record<string, { readonly optional: boolean }>159 >;160 readonly pi: {161 readonly extensions: readonly string[];162 readonly skills: readonly string[];163 };164 readonly publishConfig: { readonly access: "public" };165 readonly type: "module";166 readonly version: string;167}168

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 169why, one step back
169/** A library entry of the CLI's build, by the name it is published under. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 170–179why, one step back
170const library = (name: "protocol" | "rules"): LibraryEntry =>
171 // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it172 ({173 types: `./dist/${name}.d.ts`,174 default: `./dist/${name}.js`,175 });176177/**178 * The npm package's manifest for `version`. Every name comes from `brand`:179 * the package, and one bin for each name the one entry answers to (as git's

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 180why, one step back
180 * credential helper, it reads its own name; `apps/cli/src/bin.ts`).

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 181–183why, one step back
181 * `dependencies` are the packages the build imports, pinned
182 * (`pinnedDependencies`). The `pi` key and the `pi-package` keyword make it183 * a pi package (`pi install npm:<package>`): pi loads the adapter at

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 184why, one step back
184 * `dist/pi.js` and the platform's skill under `skills/`.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 185–259why, one step back
185 */
186export const publishManifest = (187 brand: typeof Brand,188 input: {189 readonly version: string;190 readonly dependencies: Readonly<Record<string, string>>;191 }192): PublishManifest => ({193 bin: { [brand.cli]: BIN, [brand.gitCredentialHelper]: BIN },194 dependencies: input.dependencies,195 description: `The ${brand.name} command line: find an ask, claim it, check your answer, and read its verdict; also git's credential helper, and a pi package.`,196 exports: {197 ".": BIN,198 "./protocol": library("protocol"),199 "./rules": library("rules"),200 },201 files: ["dist/", "skills/", "README.md", "LICENSE"],202 keywords: [brand.slug, "cli", "git", "pi-package"],203 license: "MIT",204 name: brand.cliPackage,205 peerDependencies: { [PI_HOST]: "*" },206 peerDependenciesMeta: { [PI_HOST]: { optional: true } },207 pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },208 publishConfig: { access: "public" },209 type: "module",210 version: input.version,211});212213/** A path in the package, as the manifest writes it, from the package's root. */214const fromRoot = (file: string) =>215 file.replace(/^\.\//u, "").replace(/\/$/u, "");216217/**218 * Every path the npm package's manifest points at (its bins, exports, pi's219 * extension and skills folder, and the README and licence it ships), from220 * the package's root, sorted: a staged package missing any of them is not221 * published.222 */223export const namedFiles = (manifest: PublishManifest): readonly string[] =>224 Arr.sort(225 Arr.dedupe(226 [227 ...Object.values(manifest.bin),228 ...Object.values(manifest.exports).flatMap((entry) =>229 Predicate.isString(entry) ? [entry] : [entry.default, entry.types]230 ),231 ...manifest.pi.extensions,232 ...manifest.pi.skills,233 ...manifest.files.filter((file) => !file.endsWith("/")),234 ].map(fromRoot)235 ),236 Order.String237 );238239// --- The plan ----------------------------------------------------------------240241/** One step of a release, in the order a release runs them. */242export type ReleaseStep =243 | "tsdown"244 | "manifest"245 | "copySkills"246 | "compile"247 | "installScript"248 | "checksums"249 | "upload"250 | "publish";251252/** `npm publish` runs only when a person runs the release (H2). */253export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(254 "PublishNeedsAPerson",255 { markers: Schema.Array(Schema.String) }256) {}257258/**259 * The env names that say an agent runs this process: each one that alone

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 260why, one step back
260 * makes `@repo/protocol/audit`'s `detectHarness` name a harness (it

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 261–272why, one step back
261 * keeps that table once; this reads it, never copies it), sorted.
262 */263export const agentMarkers = (264 env: Readonly<Record<string, string | undefined>>265): readonly string[] =>266 Arr.sort(267 Object.keys(env).filter(268 (key) => detectHarness({ [key]: env[key] }).harness !== undefined269 ),270 Order.String271 );272

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 273why, one step back
273/** What a build makes: the CLI's build, then the package and the binaries beside it. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 274–293why, one step back
274const BUILD: readonly ReleaseStep[] = [
275 "tsdown",276 "manifest",277 "copySkills",278 "compile",279];280281/** What a build or an upload ends with: the install script for its origin, and the digests. */282const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];283284/** What `bun run release` was asked to do, and the env it runs in. */285export interface ReleaseFlags {286 readonly build: boolean;287 readonly upload: boolean;288 readonly stage?: string;289 readonly publish: boolean;290 readonly env: Readonly<Record<string, string | undefined>>;291}292293/**

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 294why, one step back
294 * The steps `flags` name, in order: `build` (the CLI's build with both

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 295–381why, one step back
295 * targets, the npm package and the binaries), the install script and the
296 * checksums, `upload` to the stage's own release storage, and `publish`297 * last. An upload names a stage the repo declares (`dev-oscabriel` or298 * `demo`); a stage given to a build only says whose origin the install299 * script fetches from, and is checked the same way.300 */301const stepsOf = (302 flags: ReleaseFlags303): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {304 if (flags.stage === undefined && flags.upload) {305 return Result.fail(new NoStage());306 }307308 if (flags.stage !== undefined && Option.isNone(declaredStage(flags.stage))) {309 return Result.fail(new UnknownStage({ stage: flags.stage }));310 }311312 return Result.succeed([313 ...(flags.build ? BUILD : []),314 ...(flags.build || flags.upload ? RELEASE_FILES : []),315 ...(flags.upload ? (["upload"] as const) : []),316 ...(flags.publish ? (["publish"] as const) : []),317 ]);318};319320/**321 * The steps a release runs, in order (`stepsOf`). Under any agent's env, a322 * plan that publishes is refused (H2); `releaseRun` says what the script323 * then does instead.324 */325export const releasePlan = (326 flags: ReleaseFlags327): Result.Result<328 readonly ReleaseStep[],329 PublishNeedsAPerson | NoStage | UnknownStage330> => {331 const markers = flags.publish ? agentMarkers(flags.env) : [];332333 return markers.length > 0334 ? Result.fail(new PublishNeedsAPerson({ markers }))335 : stepsOf(flags);336};337338/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */339export interface ReleaseRun {340 readonly steps: readonly ReleaseStep[];341 /** The agent markers that refused the publish (H2); none when a person runs it. */342 readonly handOver: readonly string[];343}344345/**346 * What the script runs for `flags`. A person's run is the plan. Under an347 * agent, a run that publishes still runs every other step it names, so a348 * `--build --publish` builds, and hands the publish to a person in place349 * of running it: the script checks the staged package and prints the350 * command (H2), rather than ending well with nothing done.351 */352export const releaseRun = (353 flags: ReleaseFlags354): Result.Result<ReleaseRun, NoStage | UnknownStage> => {355 const handOver = flags.publish ? agentMarkers(flags.env) : [];356357 return Result.map(358 stepsOf({ ...flags, publish: flags.publish && handOver.length === 0 }),359 (steps) => ({ handOver, steps })360 );361};362363// --- The version -------------------------------------------------------------364365/**366 * An upload or a publish names its `--version`, and it is one the platform367 * serves: semver, never `latest` (`given` is the one that isn't).368 */369export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(370 "VersionNeeded",371 { given: Schema.optionalKey(Schema.String) }372) {373 override get message() {374 return this.given === undefined375 ? "an upload or a publish names its --version (semver, such as 0.1.0)"376 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;377 }378}379380/**381 * Whether the platform serves `version`: its manifest decodes with it as

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 382why, one step back
382 * the latest release (the platform's schema holds the one rule for a version).

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 383–392why, one step back
383 */
384const served = (version: string) =>385 Option.isSome(386 Schema.decodeOption(ReleaseManifest)({387 latest: version,388 versions: { [version]: { assets: {} } },389 })390 );391392/**

Merge build/1104 into mainoscabrielbefore adoption82cc398

lines 393–396why, one step back
393 * What a build that neither uploads nor publishes is stamped with. The
394 * build stamps the release's version into the CLI (`apps/cli/build.ts`'s395 * `--version`, which the `tsdown` step passes), and a run no build stamped396 * reports this too (`apps/cli/src/version.ts`).

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 397–432why, one step back
397 */
398const UNRELEASED = "0.0.0";399400/**401 * The release's version: `version` as given, which an upload or a publish402 * must name, and which must be one the platform serves.403 */404export const releaseVersion = (input: {405 readonly version?: string;406 readonly upload: boolean;407 readonly publish: boolean;408}): Result.Result<string, VersionNeeded> => {409 if (input.version === undefined) {410 return input.upload || input.publish411 ? Result.fail(new VersionNeeded({}))412 : Result.succeed(UNRELEASED);413 }414415 return served(input.version)416 ? Result.succeed(input.version)417 : Result.fail(new VersionNeeded({ given: input.version }));418};419420// --- The platform's release storage ------------------------------------------421422/** One file of a release, as the manifest lists it. */423export interface ReleaseAsset {424 readonly sha256: string;425 readonly bytes: number;426}427428export { ReleaseManifest } from "../../apps/platform/src/releases.ts";429430/**431 * `releases/manifest.json` once `version` is released with `assets`: every432 * version `previous` lists, kept, and `version`, now latest. It is the shape

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 433why, one step back
433 * the platform decodes and serves from (`ReleaseManifest`, the one

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 434–498why, one step back
434 * schema both sides use).
435 */436export const releaseManifest = (input: {437 readonly version: string;438 readonly previous: ReleaseManifest | undefined;439 readonly assets: Readonly<Record<string, ReleaseAsset>>;440}): ReleaseManifest => ({441 latest: input.version,442 versions: {443 ...input.previous?.versions,444 [input.version]: { assets: input.assets },445 },446});447448/**449 * `version` is already released with other bytes. The platform serves a450 * version's files as immutable, so a client may keep the old ones for good:451 * a changed release needs a new `--version`.452 */453export class VersionReleased extends Schema.TaggedError<VersionReleased>()(454 "VersionReleased",455 { version: Schema.String }456) {457 override get message() {458 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;459 }460}461462/** Two releases hold the same files, by name, size and digest. */463const sameAssets = (464 one: Readonly<Record<string, ReleaseAsset>>,465 other: Readonly<Record<string, ReleaseAsset>>466) =>467 Object.keys(one).length === Object.keys(other).length &&468 Object.entries(one).every(469 ([name, { bytes, sha256 }]) =>470 other[name]?.bytes === bytes && other[name]?.sha256 === sha256471 );472473/**474 * Whether `assets` may be released as `version`: it is new, or it is475 * released already with exactly these files (an upload run again).476 */477export const unreleased = (input: {478 readonly version: string;479 readonly previous: ReleaseManifest | undefined;480 readonly assets: Readonly<Record<string, ReleaseAsset>>;481}): Result.Result<void, VersionReleased> => {482 const released = input.previous?.versions[input.version];483484 return released === undefined || sameAssets(released.assets, input.assets)485 ? Result.void486 : Result.fail(new VersionReleased({ version: input.version }));487};488489/** Where the manifest is kept: every release file is under `releases/`. */490export const MANIFEST_KEY = "releases/manifest.json";491492/** Files by name, sorted (`Order.String`), as both sides list them. */493const byName = <A>(record: Readonly<Record<string, A>>) =>494 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);495496/**497 * `SHA256SUMS`: one `<sha256> <name>` line per file, sorted by name, as498 * `sha256sum` prints them and as the platform makes the one it serves from

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 499why, one step back
499 * the manifest.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 500–510why, one step back
500 */
501export const checksumsFile = (502 assets: Readonly<Record<string, ReleaseAsset>>503): string =>504 byName(assets)505 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)506 .join("");507508/**509 * What an upload puts where, in order: every file of `version` under510 * `releases/<version>/`, sorted, and `releases/manifest.json` last, so the

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 511why, one step back
511 * manifest never names a file the bucket lacks.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 512–527why, one step back
512 */
513export const uploads = (input: {514 readonly version: string;515 readonly files: readonly string[];516}): readonly { readonly file: string; readonly key: string }[] => [517 ...Arr.sort(input.files, Order.String).map((file) => ({518 file,519 key: `releases/${input.version}/${file}`,520 })),521 { file: "manifest.json", key: MANIFEST_KEY },522];523524// --- The install script ------------------------------------------------------525526/**527 * `curl -fsSL <origin>/install.sh | sh` for `version`, whose files the

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 528why, one step back
528 * platform serves at `baseUrl` (`<origin>/releases/<version>`):

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 529–536why, one step back
529 * the binary for the machine, checked against `SHA256SUMS` before it is
530 * installed as `brand.cli`, with `brand.gitCredentialHelper` linked to it.531 */532export const installScript = (input: {533 readonly brand: typeof Brand;534 readonly version: string;535 readonly baseUrl: string;536}): string => installScriptFor({ ...input, machines: targets.map(machineOf) });