Skip to content
Myr

release.ts

This file

Path

scripts/lib/release.ts

393 lines · 11.8 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 1–18why, one step back
1import type { Brand } from "@repo/brand";
2import { detectHarness } from "@repo/protocol/audit";3import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";45import { ReleaseManifest } from "../../apps/platform/src/releases.ts";6import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";7import { installScriptFor } from "./release/install-script.ts";89export type Target = "bun-linux-x64" | "bun-darwin-arm64";1011export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];1213export const machineOf = (target: Target) => target.replace(/^bun-/u, "");1415export const binaryName = (brand: typeof Brand, target: Target) =>16 `${brand.slug}-${machineOf(target)}`;1718/**

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 19–21why, one step back
19 * A module statement as rolldown writes one, at the start of a line. A
20 * template literal's line that starts with `import` and names a package is21 * read as an import too, which fails the pin loudly rather than slip through.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 22–33why, one step back
22 */
23const STATEMENT =24 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;2526const packageOf = (specifier: string) =>27 specifier28 .split("/")29 .slice(0, specifier.startsWith("@") ? 2 : 1)30 .join("/");3132const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);33

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 34why, one step back
34/** Static imports only: a package reached only by a dynamic `import()` is not listed. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 35–46why, one step back
35export const importedPackages = (source: string): readonly string[] =>
36 Arr.sort(37 Arr.dedupe(38 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {39 const specifier = groups?.from ?? groups?.bare ?? "";4041 return isPackage(specifier) ? [packageOf(specifier)] : [];42 })43 ),44 Order.String45 );46

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 47why, one step back
47/** The host the package plugs into: an optional peer, never bundled or depended on. */

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 48–133why, one step back
48const PI_HOST = "@earendil-works/pi-coding-agent";
4950export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {51 packages: Schema.Array(Schema.String),52}) {}5354const pinOf = (55 specifier: string | undefined,56 catalogued: string | undefined57) => {58 const version = specifier === "catalog:" ? catalogued : specifier;5960 return version === undefined || /^(?:workspace|catalog):/u.test(version)61 ? undefined62 : version;63};6465export const pinnedDependencies = (input: {66 readonly imported: readonly string[];67 readonly declared: Readonly<Record<string, string>>;68 readonly catalog: Readonly<Record<string, string>>;69}): Result.Result<Readonly<Record<string, string>>, Unpinned> => {70 const pins = input.imported71 .filter((name) => name !== PI_HOST)72 .map(73 (name) =>74 [75 name,76 name.startsWith("@repo/")77 ? undefined78 : pinOf(input.declared[name], input.catalog[name]),79 ] as const80 );8182 const unpinned = pins.flatMap(([name, version]) =>83 version === undefined ? [name] : []84 );8586 return unpinned.length > 087 ? Result.fail(new Unpinned({ packages: unpinned }))88 : Result.succeed(89 Object.fromEntries(90 pins.flatMap(([name, version]) =>91 version === undefined ? [] : [[name, version]]92 )93 )94 );95};9697const BIN = "./dist/bin.js";9899interface LibraryEntry {100 readonly types: string;101 readonly default: string;102}103104export interface PublishManifest {105 readonly bin: Readonly<Record<string, string>>;106 readonly dependencies: Readonly<Record<string, string>>;107 readonly description: string;108 readonly exports: Readonly<Record<string, string | LibraryEntry>>;109 readonly files: readonly string[];110 readonly keywords: readonly string[];111 readonly license: "MIT";112 readonly name: string;113 readonly peerDependencies: Readonly<Record<string, string>>;114 readonly peerDependenciesMeta: Readonly<115 Record<string, { readonly optional: boolean }>116 >;117 readonly pi: {118 readonly extensions: readonly string[];119 readonly skills: readonly string[];120 };121 readonly publishConfig: { readonly access: "public" };122 readonly type: "module";123 readonly version: string;124}125126const library = (name: "protocol" | "rules"): LibraryEntry =>127 // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it128 ({129 types: `./dist/${name}.d.ts`,130 default: `./dist/${name}.js`,131 });132133/**

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 134–135why, one step back
134 * Both bins point at one entry, which reads its own name to act as git's
135 * credential helper. The `pi` key and `pi-package` keyword make it a pi package.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 136–197why, one step back
136 */
137export const publishManifest = (138 brand: typeof Brand,139 input: {140 readonly version: string;141 readonly dependencies: Readonly<Record<string, string>>;142 }143): PublishManifest => ({144 bin: { [brand.cli]: BIN, [brand.gitCredentialHelper]: BIN },145 dependencies: input.dependencies,146 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.`,147 exports: {148 ".": BIN,149 "./protocol": library("protocol"),150 "./rules": library("rules"),151 },152 files: ["dist/", "skills/", "README.md", "LICENSE"],153 keywords: [brand.slug, "cli", "git", "pi-package"],154 license: "MIT",155 name: brand.cliPackage,156 peerDependencies: { [PI_HOST]: "*" },157 peerDependenciesMeta: { [PI_HOST]: { optional: true } },158 pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },159 publishConfig: { access: "public" },160 type: "module",161 version: input.version,162});163164const fromRoot = (file: string) =>165 file.replace(/^\.\//u, "").replace(/\/$/u, "");166167export const namedFiles = (manifest: PublishManifest): readonly string[] =>168 Arr.sort(169 Arr.dedupe(170 [171 ...Object.values(manifest.bin),172 ...Object.values(manifest.exports).flatMap((entry) =>173 Predicate.isString(entry) ? [entry] : [entry.default, entry.types]174 ),175 ...manifest.pi.extensions,176 ...manifest.pi.skills,177 ...manifest.files.filter((file) => !file.endsWith("/")),178 ].map(fromRoot)179 ),180 Order.String181 );182183export type ReleaseStep =184 | "tsdown"185 | "manifest"186 | "copySkills"187 | "compile"188 | "installScript"189 | "checksums"190 | "upload"191 | "publish";192193export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(194 "PublishNeedsAPerson",195 { markers: Schema.Array(Schema.String) }196) {}197

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 198why, one step back
198// Reads `detectHarness`'s table rather than copying it.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 199–263why, one step back
199export const agentMarkers = (
200 env: Readonly<Record<string, string | undefined>>201): readonly string[] =>202 Arr.sort(203 Object.keys(env).filter(204 (key) => detectHarness({ [key]: env[key] }).harness !== undefined205 ),206 Order.String207 );208209const BUILD: readonly ReleaseStep[] = [210 "tsdown",211 "manifest",212 "copySkills",213 "compile",214];215216const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];217218export interface ReleaseFlags {219 readonly build: boolean;220 readonly upload: boolean;221 readonly stage?: string;222 readonly publish: boolean;223 readonly env: Readonly<Record<string, string | undefined>>;224}225226const stepsOf = (227 flags: ReleaseFlags228): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {229 if (flags.stage === undefined && flags.upload) {230 return Result.fail(new NoStage());231 }232233 if (flags.stage !== undefined && Option.isNone(declaredStage(flags.stage))) {234 return Result.fail(new UnknownStage({ stage: flags.stage }));235 }236237 return Result.succeed([238 ...(flags.build ? BUILD : []),239 ...(flags.build || flags.upload ? RELEASE_FILES : []),240 ...(flags.upload ? (["upload"] as const) : []),241 ...(flags.publish ? (["publish"] as const) : []),242 ]);243};244245export const releasePlan = (246 flags: ReleaseFlags247): Result.Result<248 readonly ReleaseStep[],249 PublishNeedsAPerson | NoStage | UnknownStage250> => {251 const markers = flags.publish ? agentMarkers(flags.env) : [];252253 return markers.length > 0254 ? Result.fail(new PublishNeedsAPerson({ markers }))255 : stepsOf(flags);256};257258export interface ReleaseRun {259 readonly steps: readonly ReleaseStep[];260 readonly handOver: readonly string[];261}262263/**

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 264–265why, one step back
264 * Under an agent, a run that publishes still runs every other step it names
265 * and hands the publish to a person instead of running it.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 266–376why, one step back
266 */
267export const releaseRun = (268 flags: ReleaseFlags269): Result.Result<ReleaseRun, NoStage | UnknownStage> => {270 const handOver = flags.publish ? agentMarkers(flags.env) : [];271272 return Result.map(273 stepsOf({ ...flags, publish: flags.publish && handOver.length === 0 }),274 (steps) => ({ handOver, steps })275 );276};277278export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(279 "VersionNeeded",280 { given: Schema.optionalKey(Schema.String) }281) {282 override get message() {283 return this.given === undefined284 ? "an upload or a publish names its --version (semver, such as 0.1.0)"285 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;286 }287}288289const served = (version: string) =>290 Option.isSome(291 Schema.decodeOption(ReleaseManifest)({292 latest: version,293 versions: { [version]: { assets: {} } },294 })295 );296297const UNRELEASED = "0.0.0";298299export const releaseVersion = (input: {300 readonly version?: string;301 readonly upload: boolean;302 readonly publish: boolean;303}): Result.Result<string, VersionNeeded> => {304 if (input.version === undefined) {305 return input.upload || input.publish306 ? Result.fail(new VersionNeeded({}))307 : Result.succeed(UNRELEASED);308 }309310 return served(input.version)311 ? Result.succeed(input.version)312 : Result.fail(new VersionNeeded({ given: input.version }));313};314315export interface ReleaseAsset {316 readonly sha256: string;317 readonly bytes: number;318}319320export { ReleaseManifest } from "../../apps/platform/src/releases.ts";321322export const releaseManifest = (input: {323 readonly version: string;324 readonly previous: ReleaseManifest | undefined;325 readonly assets: Readonly<Record<string, ReleaseAsset>>;326}): ReleaseManifest => ({327 latest: input.version,328 versions: {329 ...input.previous?.versions,330 [input.version]: { assets: input.assets },331 },332});333334export class VersionReleased extends Schema.TaggedError<VersionReleased>()(335 "VersionReleased",336 { version: Schema.String }337) {338 override get message() {339 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;340 }341}342343const sameAssets = (344 one: Readonly<Record<string, ReleaseAsset>>,345 other: Readonly<Record<string, ReleaseAsset>>346) =>347 Object.keys(one).length === Object.keys(other).length &&348 Object.entries(one).every(349 ([name, { bytes, sha256 }]) =>350 other[name]?.bytes === bytes && other[name]?.sha256 === sha256351 );352353export const unreleased = (input: {354 readonly version: string;355 readonly previous: ReleaseManifest | undefined;356 readonly assets: Readonly<Record<string, ReleaseAsset>>;357}): Result.Result<void, VersionReleased> => {358 const released = input.previous?.versions[input.version];359360 return released === undefined || sameAssets(released.assets, input.assets)361 ? Result.void362 : Result.fail(new VersionReleased({ version: input.version }));363};364365export const MANIFEST_KEY = "releases/manifest.json";366367const byName = <A>(record: Readonly<Record<string, A>>) =>368 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);369370export const checksumsFile = (371 assets: Readonly<Record<string, ReleaseAsset>>372): string =>373 byName(assets)374 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)375 .join("");376

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 377why, one step back
377// The manifest goes last, so it never names a file the bucket lacks.

Merge branch 'build/715-release'oscabrielbefore adoption918a2c1

lines 378–393why, one step back
378export const uploads = (input: {
379 readonly version: string;380 readonly files: readonly string[];381}): readonly { readonly file: string; readonly key: string }[] => [382 ...Arr.sort(input.files, Order.String).map((file) => ({383 file,384 key: `releases/${input.version}/${file}`,385 })),386 { file: "manifest.json", key: MANIFEST_KEY },387];388389export const installScript = (input: {390 readonly brand: typeof Brand;391 readonly version: string;392 readonly baseUrl: string;393}): string => installScriptFor({ ...input, machines: targets.map(machineOf) });