Skip to content
Myr

release.test.ts

This file

Path

packages/config/test/release.test.ts

741 lines · 20.9 KiB · TypeScript

Last changed by

Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4  Array as Arr,5  Crypto,6  Effect,7  FileSystem,8  Layer,9  Option,10  Order,11  Path,12  Ref,13  Result,14  Schema,15  Sink,16  Stream,17} from "effect";18import { ChildProcess, ChildProcessSpawner } from "effect/process";1920import { ReleaseManifest } from "../../../apps/platform/src/releases.ts";21import { NoStage, UnknownStage } from "../../../infra/stages.ts";22import {23  agentMarkers,24  checksumsFile,25  importedPackages,26  installScript,27  namedFiles,28  pinnedDependencies,29  publishManifest,30  PublishNeedsAPerson,31  releaseManifest,32  releasePlan,33  releaseRun,34  releaseVersion,35  targets,36  Unpinned,37  unreleased,38  uploads,39  VersionNeeded,40  VersionReleased,41} from "../../../scripts/lib/release.ts";42import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";43import { Brand } from "../../brand/src/index.ts";44import { repoRoot } from "./root.ts";4546const PackageJson = Schema.fromJsonString(47  Schema.Struct({48    dependencies: Schema.optionalKey(49      Schema.Record(Schema.String, Schema.String)50    ),51    workspaces: Schema.optionalKey(52      Schema.Struct({53        catalog: Schema.optionalKey(54          Schema.Record(Schema.String, Schema.String)55        ),56      })57    ),58  })59);6061const runtime = { "@effect/platform-bun": "4.0.1", effect: "4.0.1" };6263describe("the npm package's manifest", () => {64  const manifest = publishManifest(Brand, {65    dependencies: runtime,66    version: "0.1.0",67  });6869  it("is the brand's CLI package, with both names as bins", () => {70    expect({71      bin: manifest.bin,72      license: manifest.license,73      name: manifest.name,74      version: manifest.version,75    }).toStrictEqual({76      bin: {77        [Brand.cli]: "./dist/bin.js",78        [Brand.gitCredentialHelper]: "./dist/bin.js",79      },80      license: "MIT",81      name: Brand.cliPackage,82      version: "0.1.0",83    });84  });8586  it("exports the command line, the sdk a config folder imports, and its types", () => {87    expect(manifest.exports).toStrictEqual({88      ".": "./dist/bin.js",89      "./protocol": {90        default: "./dist/protocol.js",91        types: "./dist/protocol.d.ts",92      },93      "./rules": { default: "./dist/rules.js", types: "./dist/rules.d.ts" },94    });95  });9697  it("lists each library entry's types first and its code last, the order Node and TypeScript match conditions in", () => {98    expect(99      [manifest.exports["./rules"], manifest.exports["./protocol"]].map(100        (entry) => Object.keys(entry ?? {})101      )102    ).toStrictEqual([103      ["types", "default"],104      ["types", "default"],105    ]);106  });107108  it("is a pi package whose host is an optional peer, never a dependency", () => {109    expect({110      dependencies: manifest.dependencies,111      keywords: manifest.keywords.includes("pi-package"),112      peerDependencies: manifest.peerDependencies,113      peerDependenciesMeta: manifest.peerDependenciesMeta,114      pi: manifest.pi,115    }).toStrictEqual({116      dependencies: runtime,117      keywords: true,118      peerDependencies: { "@earendil-works/pi-coding-agent": "*" },119      peerDependenciesMeta: {120        "@earendil-works/pi-coding-agent": { optional: true },121      },122      pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },123    });124  });125126  it("ships the build, the platform's skill, a README and the licence", () => {127    expect(manifest.files).toStrictEqual([128      "dist/",129      "skills/",130      "README.md",131      "LICENSE",132    ]);133  });134});135136/** The top of a tsdown build, as rolldown writes it, with prose that only looks like imports. */137const built = [138  "#!/usr/bin/env node",139  'import { createRequire } from "node:module";',140  'import { BunRuntime, BunServices } from "@effect/platform-bun";',141  'import { Effect, Schema } from "effect";',142  'import { Command, Flag } from "effect/cli";',143  'import "./chunk-a1.js";',144  "/**",145  ' * `import("x")` and `require("x")`, and `… from "y"`.',146  " */",147  'const source = `import { project } from "some-sdk/rules";`;',148  "",149].join("\n");150151describe("the npm package's dependencies", () => {152  it("are the packages the build imports, by package name", () => {153    expect(importedPackages(built)).toStrictEqual([154      "@effect/platform-bun",155      "effect",156    ]);157  });158159  it.live(160    "are pinned from the CLI's own manifest and the catalog, with no workspace package",161    () =>162      Effect.gen(function* () {163        const fs = yield* FileSystem.FileSystem;164        const path = yield* Path.Path;165        const root = yield* repoRoot;166167        const read = (file: string) =>168          fs169            .readFileString(path.join(root, file))170            .pipe(Effect.flatMap(Schema.decodeEffect(PackageJson)));171172        const cli = yield* read("apps/cli/package.json");173        const workspace = yield* read("package.json");174175        const pinned = pinnedDependencies({176          catalog: workspace.workspaces?.catalog ?? {},177          declared: cli.dependencies ?? {},178          imported: importedPackages(built),179        });180181        expect(182          Result.map(pinned, (dependencies) => ({183            exact: Object.values(dependencies).every((version) =>184              /^\d+\.\d+\.\d+$/u.test(version)185            ),186            names: Object.keys(dependencies),187          }))188        ).toStrictEqual(189          Result.succeed({190            exact: true,191            names: ["@effect/platform-bun", "effect"],192          })193        );194      }).pipe(Effect.provide(NodeServices.layer))195  );196197  it("refuses a package the build imports that the CLI doesn't declare, or one from the workspace", () => {198    expect(199      pinnedDependencies({200        catalog: { effect: "4.0.1" },201        declared: { "@repo/brand": "workspace:*", effect: "catalog:" },202        imported: ["@repo/brand", "effect", "yaml"],203      })204    ).toStrictEqual(205      Result.fail(new Unpinned({ packages: ["@repo/brand", "yaml"] }))206    );207  });208209  it("leave out pi, which the pi adapter imports from its host, never from a dependency", () => {210    expect(211      pinnedDependencies({212        catalog: { effect: "4.0.1" },213        declared: { effect: "catalog:" },214        imported: ["@earendil-works/pi-coding-agent", "effect"],215      })216    ).toStrictEqual(Result.succeed({ effect: "4.0.1" }));217  });218});219220describe("a release's plan", () => {221  it("builds for exactly linux-x64 and darwin-arm64", () => {222    expect(targets).toStrictEqual(["bun-linux-x64", "bun-darwin-arm64"]);223  });224225  it("reads an agent from any harness's marker in the env, and nothing else", () => {226    expect({227      agent: agentMarkers({228        AI_AGENT: "",229        CLAUDECODE: "1",230        HOME: "/home/someone",231        PI_SESSION_ID: "s1",232      }),233      person: agentMarkers({ HOME: "/home/someone", PATH: "/usr/bin" }),234    }).toStrictEqual({ agent: ["CLAUDECODE", "PI_SESSION_ID"], person: [] });235  });236237  it("refuses to publish under an agent, naming what marked it", () => {238    expect(239      releasePlan({240        build: false,241        env: { CLAUDECODE: "1" },242        publish: true,243        upload: false,244      })245    ).toStrictEqual(246      Result.fail(new PublishNeedsAPerson({ markers: ["CLAUDECODE"] }))247    );248  });249250  it("under an agent, still runs every other step it was asked for, and hands only the publish to a person", () => {251    expect({252      agent: releaseRun({253        build: true,254        env: { CLAUDECODE: "1" },255        publish: true,256        stage: "dev-oscabriel",257        upload: true,258      }),259      alone: releaseRun({260        build: false,261        env: { CLAUDECODE: "1" },262        publish: true,263        upload: false,264      }),265      person: releaseRun({266        build: false,267        env: {},268        publish: true,269        upload: false,270      }),271    }).toStrictEqual({272      agent: Result.succeed({273        handOver: ["CLAUDECODE"],274        steps: [275          "tsdown",276          "manifest",277          "copySkills",278          "compile",279          "installScript",280          "checksums",281          "upload",282        ],283      }),284      alone: Result.succeed({ handOver: ["CLAUDECODE"], steps: [] }),285      person: Result.succeed({ handOver: [], steps: ["publish"] }),286    });287  });288289  it("refuses an unknown stage under an agent too, before it hands anything over", () => {290    expect(291      releaseRun({292        build: false,293        env: { CLAUDECODE: "1" },294        publish: true,295        stage: "staging",296        upload: true,297      })298    ).toStrictEqual(Result.fail(new UnknownStage({ stage: "staging" })));299  });300301  it("publishes last when a person runs it", () => {302    expect(303      Result.map(304        releasePlan({ build: false, env: {}, publish: true, upload: false }),305        Arr.last306      )307    ).toStrictEqual(Result.succeed(Option.some("publish")));308  });309310  it("builds the package and the binaries, and writes the install script and checksums", () => {311    expect(312      releasePlan({ build: true, env: {}, publish: false, upload: false })313    ).toStrictEqual(314      Result.succeed([315        "tsdown",316        "manifest",317        "copySkills",318        "compile",319        "installScript",320        "checksums",321      ])322    );323  });324325  it("uploads to a stage's own release storage after the checksums", () => {326    expect(327      releasePlan({328        build: true,329        env: {},330        publish: true,331        stage: "dev-oscabriel",332        upload: true,333      })334    ).toStrictEqual(335      Result.succeed([336        "tsdown",337        "manifest",338        "copySkills",339        "compile",340        "installScript",341        "checksums",342        "upload",343        "publish",344      ])345    );346  });347348  it("uploads what was built, for the stage's own origin", () => {349    expect(350      releasePlan({351        build: false,352        env: { CLAUDECODE: "1" },353        publish: false,354        stage: "dev-oscabriel",355        upload: true,356      })357    ).toStrictEqual(Result.succeed(["installScript", "checksums", "upload"]));358  });359360  it("names its version when it uploads or publishes, and only a version the platform serves", () => {361    expect({362      build: releaseVersion({ publish: false, upload: false }),363      named: releaseVersion({364        publish: true,365        upload: true,366        version: "0.2.0-rc.1",367      }),368      unnamed: releaseVersion({ publish: false, upload: true }),369      wrong: releaseVersion({370        publish: false,371        upload: true,372        version: "latest",373      }),374    }).toStrictEqual({375      build: Result.succeed("0.0.0"),376      named: Result.succeed("0.2.0-rc.1"),377      unnamed: Result.fail(new VersionNeeded({})),378      wrong: Result.fail(new VersionNeeded({ given: "latest" })),379    });380  });381382  it("refuses an upload to a stage the repo doesn't declare, or to none", () => {383    expect({384      none: releasePlan({385        build: false,386        env: {},387        publish: false,388        upload: true,389      }),390      unknown: releasePlan({391        build: false,392        env: {},393        publish: false,394        stage: "staging",395        upload: true,396      }),397    }).toStrictEqual({398      none: Result.fail(new NoStage()),399      unknown: Result.fail(new UnknownStage({ stage: "staging" })),400    });401  });402});403404const digest = (fill: string) => fill.repeat(64);405406const first = {407  latest: "0.1.0",408  versions: {409    "0.1.0": {410      assets: {411        [`${Brand.slug}-darwin-arm64`]: {412          bytes: 62_722_290,413          sha256: digest("a"),414        },415        [`${Brand.slug}-linux-x64`]: { bytes: 81_806_816, sha256: digest("b") },416      },417    },418  },419};420421const second = {422  "install.sh": { bytes: 2048, sha256: digest("c") },423  [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },424  [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },425};426427const recordingSpawner = Effect.gen(function* () {428  const path = yield* Path.Path;429  const root = yield* repoRoot;430  const lines = yield* Ref.make<readonly string[]>([]);431432  const spawner = ChildProcessSpawner.make((command) =>433    Effect.gen(function* () {434      if (!ChildProcess.isStandardCommand(command)) {435        return yield* Effect.die("the release pipes no commands");436      }437438      yield* Ref.update(lines, (all) => [439        ...all,440        `${path.relative(root, command.options.cwd ?? root)}$ ${[command.command, ...command.args].join(" ")}`,441      ]);442443      return ChildProcessSpawner.makeHandle({444        all: Stream.empty,445        exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),446        getInputFd: () => Sink.drain,447        getOutputFd: () => Stream.empty,448        isRunning: Effect.succeed(false),449        kill: () => Effect.void,450        pid: ChildProcessSpawner.ProcessId(1),451        stderr: Stream.empty,452        stdin: Sink.drain,453        stdout: Stream.empty,454        unref: Effect.succeed(Effect.void),455      });456    })457  );458459  return {460    layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),461    spawned: Ref.get(lines),462  };463});464465describe("a release's build step", () => {466  it.effect(467    "builds the CLI stamped with the release's version, for both targets",468    () =>469      Effect.gen(function* () {470        const { layer, spawned } = yield* recordingSpawner;471        const layout = yield* layoutOf(yield* repoRoot);472473        yield* runStep("tsdown", layout, {474          origin: "https://platform.example",475          stage: Option.none(),476          version: "0.2.0-rc.1",477        }).pipe(Effect.provide(layer));478479        expect(yield* spawned).toStrictEqual([480          "apps/cli$ bun run build -- --targets bun-linux-x64,bun-darwin-arm64 --version 0.2.0-rc.1",481        ]);482      }).pipe(Effect.provide(NodeServices.layer))483  );484});485486describe("the release manifest", () => {487  it.effect(488    "keeps every earlier version, makes the new one latest, and is what the platform decodes",489    () =>490      Effect.gen(function* () {491        const manifest = releaseManifest({492          assets: second,493          previous: first,494          version: "0.2.0",495        });496497        expect(498          yield* Schema.decodeEffect(ReleaseManifest)(manifest)499        ).toStrictEqual({500          latest: "0.2.0",501          versions: { ...first.versions, "0.2.0": { assets: second } },502        });503      })504  );505506  it("starts the list with the first release", () => {507    expect(508      releaseManifest({ assets: second, previous: undefined, version: "0.1.0" })509    ).toStrictEqual({510      latest: "0.1.0",511      versions: { "0.1.0": { assets: second } },512    });513  });514515  it("refuses to release a version again with other bytes, since its files are cached for good", () => {516    expect({517      again: unreleased({518        assets: first.versions["0.1.0"].assets,519        previous: first,520        version: "0.1.0",521      }),522      changed: unreleased({523        assets: second,524        previous: first,525        version: "0.1.0",526      }),527      next: unreleased({ assets: second, previous: first, version: "0.2.0" }),528    }).toStrictEqual({529      again: Result.void,530      changed: Result.fail(new VersionReleased({ version: "0.1.0" })),531      next: Result.void,532    });533  });534});535536const sha256 = (content: string) =>537  Effect.flatMap(Crypto.Crypto, (crypto) =>538    crypto.digest("SHA-256", new TextEncoder().encode(content))539  ).pipe(540    Effect.map((bytes) =>541      [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")542    ),543    Effect.provide(NodeServices.layer)544  );545546const origin = "https://platform-dev-oscabriel.example.workers.dev";547548const base = `${origin}/releases/0.1.0`;549550describe("the install script", () => {551  const script = installScript({552    baseUrl: base,553    brand: Brand,554    version: "0.1.0",555  });556557  it("fetches the release and its checksums from the platform, and never from GitHub", () => {558    expect({559      base: script.includes(`'${base}'`),560      checksums: script.includes('"$base/SHA256SUMS"'),561      github: /github/iu.test(script),562      posix: script.startsWith("#!/bin/sh\n"),563    }).toStrictEqual({564      base: true,565      checksums: true,566      github: false,567      posix: true,568    });569  });570571  const install = (files: Readonly<Record<string, string>>) =>572    Effect.gen(function* () {573      const fs = yield* FileSystem.FileSystem;574      const path = yield* Path.Path;575      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;576      const dir = yield* fs.makeTempDirectoryScoped({ prefix: "install-715-" });577      const served = path.join(dir, "served");578      const tools = path.join(dir, "tools");579      const home = path.join(dir, "home");580581      yield* Effect.forEach([served, tools, home], (folder) =>582        fs.makeDirectory(folder, { recursive: true })583      );584585      yield* Effect.forEach(Object.entries(files), ([name, content]) =>586        fs.writeFileString(path.join(served, name), content)587      );588589      yield* fs.writeFileString(590        path.join(tools, "curl"),591        [592          "#!/bin/sh",593          'out=""; url=""',594          "while [ $# -gt 0 ]; do",595          '  case "$1" in -o) out="$2"; shift 2 ;; -*) shift ;; *) url="$1"; shift ;; esac',596          "done",597          'case "$url" in "$RELEASE_BASE"/*) ;; *) exit 22 ;; esac',598          'name="$(basename "$url")"',599          '[ -f "$SERVED/$name" ] || exit 22',600          'cp "$SERVED/$name" "$out"',601          "",602        ].join("\n")603      );604605      yield* fs.chmod(path.join(tools, "curl"), 0o755);606      yield* fs.writeFileString(path.join(dir, "install.sh"), script);607608      const child = yield* spawner.spawn(609        ChildProcess.make("sh", [path.join(dir, "install.sh")], {610          env: {611            HOME: home,612            PATH: `${tools}:/usr/bin:/bin`,613            RELEASE_BASE: base,614            SERVED: served,615          },616          extendEnv: false,617        })618      );619620      const [stderr, exitCode] = yield* Effect.all(621        [Stream.mkString(Stream.decodeText(child.stderr)), child.exitCode],622        { concurrency: "unbounded" }623      );624625      const bin = path.join(home, ".local", "bin");626627      const installed = (yield* fs.exists(bin))628        ? Arr.sort(yield* fs.readDirectory(bin), Order.String)629        : [];630631      return {632        exitCode: Number(exitCode),633        helper: installed.includes(Brand.gitCredentialHelper)634          ? yield* fs.readLink(path.join(bin, Brand.gitCredentialHelper))635          : "",636        installed,637        stderr,638      };639    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));640641  const binaries = Object.fromEntries(642    ["linux-x64", "darwin-arm64"].map((target) => [643      `${Brand.slug}-${target}`,644      `#!/bin/sh\necho ${target}\n`,645    ])646  );647648  const sums = <E, R>(649    digestOf: (content: string) => Effect.Effect<string, E, R>650  ) =>651    Effect.map(652      Effect.forEach(Object.entries(binaries), ([name, content]) =>653        Effect.map(digestOf(content), (sum) => `${sum}  ${name}\n`)654      ),655      (lines) => lines.join("")656    );657658  it.live(659    "installs the binary that matches SHA256SUMS, with git's credential helper beside it",660    () =>661      Effect.gen(function* () {662        const ran = yield* install({663          ...binaries,664          SHA256SUMS: yield* sums(sha256),665        });666667        expect({ ...ran, stderr: ran.stderr.trim() }).toStrictEqual({668          exitCode: 0,669          helper: Brand.cli,670          installed: Arr.sort(671            [Brand.cli, Brand.gitCredentialHelper],672            Order.String673          ),674          stderr: "",675        });676      })677  );678679  it.live("installs nothing when the download doesn't match SHA256SUMS", () =>680    Effect.gen(function* () {681      const ran = yield* install({682        ...binaries,683        SHA256SUMS: yield* sums(() => Effect.succeed(digest("0"))),684      });685686      expect({687        exitCode: ran.exitCode,688        installed: ran.installed,689        said: ran.stderr.includes("does not match SHA256SUMS"),690      }).toStrictEqual({ exitCode: 1, installed: [], said: true });691    })692  );693});694695describe("what a release hands the platform", () => {696  it("lists each file's digest as sha256sum does, sorted by name", () => {697    expect(checksumsFile(second)).toStrictEqual(698      [699        `${digest("c")}  install.sh`,700        `${digest("d")}  ${Brand.slug}-darwin-arm64`,701        `${digest("e")}  ${Brand.slug}-linux-x64`,702        "",703      ].join("\n")704    );705  });706707  it("uploads every file of the version first and the manifest last, so it never names a missing file", () => {708    expect(709      uploads({ files: Object.keys(second), version: "0.2.0" })710    ).toStrictEqual([711      { file: "install.sh", key: "releases/0.2.0/install.sh" },712      {713        file: `${Brand.slug}-darwin-arm64`,714        key: `releases/0.2.0/${Brand.slug}-darwin-arm64`,715      },716      {717        file: `${Brand.slug}-linux-x64`,718        key: `releases/0.2.0/${Brand.slug}-linux-x64`,719      },720      { file: "manifest.json", key: "releases/manifest.json" },721    ]);722  });723724  it("names every file the npm package's manifest points at, so a package missing one is never published", () => {725    expect(726      namedFiles(727        publishManifest(Brand, { dependencies: runtime, version: "0.1.0" })728      )729    ).toStrictEqual([730      "LICENSE",731      "README.md",732      "dist/bin.js",733      "dist/pi.js",734      "dist/protocol.d.ts",735      "dist/protocol.js",736      "dist/rules.d.ts",737      "dist/rules.js",738      "skills",739    ]);740  });741});