Merge build/1104 into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 9c64f9b, dbfd41b · Browse files · 9 files·+430 added−56 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+430 added−56 removed
- tests:+236 added−0 removed
- other:+194 added−56 removed
Provenance
- Commit
82cc398- Tree
d1fccc5- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
9c64f9b- Parent 2
dbfd41b
9 files changed+430 added−56 removed
modified:apps/cli/src/main.ts+2 added-6 removed
21 unmodified lines22 RemoteClient,23 transportMessage,24 } from "./remote.ts";25 import { commands, mcp, UnknownCommand } from "./surfaces.ts";26+import { cliVersion } from "./version.ts";27 28 /**29 * The three commands that start any contribution, first in `--help`, so a30 * person or an agent who knows nothing else knows where to begin.12 unmodified lines43 Command.withDescription(banner),44 Command.withSubcommands(tree)45 );46 46-/**47- * The CLI's version until the release build stamps its own.48- */49-const version = "0.0.0";50-47 /** The exit code of a usage error, as for a command line effect/cli can't parse. */48 const USAGE = 2;49 50 /**120 unmodified lines171 172 const exit = yield* Effect.exit(173 Command.runWith(root.pipe(Command.provideEffectDiscard(stdout.open)), {174 renderErrors: false,179- version,175+ version: cliVersion,176 })(argv).pipe(177 Effect.provideService(178 CliConfig.CliConfig,179 CliConfig.make({ builtIns: builtInsFor(policy) })28 unmodified linesmodified:apps/cli/src/surfaces.ts+2 added-1 removed
40 unmodified lines41 import { Output } from "./output.ts";42 import { refusalsIn, views } from "./render.ts";43 import { repoContext } from "./repo-context.ts";44 import { today } from "./tui/command.ts";45+import { cliVersion } from "./version.ts";46 47 /** The folder the CLI stands in: the process's own, unless a test says otherwise. */48 export const WorkingDirectory = Context.Reference<string>(49 "cli/WorkingDirectory",265 unmodified lines315 McpProtocol.v2025_06_18,316 McpProtocol.v2025_03_26,317 McpProtocol.v2024_11_05,318 ],318- version: "0.0.0",319+ version: cliVersion,320 })321 )322 );323 11 unmodified linesadded:apps/cli/src/version.ts+26 added
1234567891011121314151617181920212223242526/** * The CLI's version, as its build stamped it: what `--version` prints and * what the stdio MCP server says it is. * * `build.ts` stamps it with a define (`versionDefine`) that both bundlers * apply: tsdown for the npm build, `bun build --compile` for each binary. * Each replaces `import.meta.env.CLI_BUILD_VERSION` with the version as a * string literal at build time. The form is chosen because both bundlers * replace it, it needs no `typeof` guard on an undeclared global and no * `process.env` read, and a run no build stamped (vitest, `bun * src/bin.ts`) leaves it undefined, so it reads as `0.0.0`, the release's * own word for unreleased (`scripts/lib/release.ts`' `UNRELEASED`). Bun * reads `import.meta.env` from the process env, so an unbuilt run under * Bun with `CLI_BUILD_VERSION` set reports that instead; a built one never * looks. */
declare global { interface ImportMeta { /** What a bundler's define replaces; unbuilt, Vite's or Bun's env. */ readonly env: { readonly CLI_BUILD_VERSION?: string }; }}
/** The CLI's version as its build stamped it; `0.0.0` in a run no build stamped. */export const cliVersion: string = import.meta.env.CLI_BUILD_VERSION ?? "0.0.0";added:apps/cli/test/version.test.ts+169 added
1+/**2+ * The CLI's version: `src/version.ts` says it, a run no build stamped says3+ * `0.0.0`, and `build.ts` stamps a release's version into both bundlers'4+ * output through one define. The real build compiles binaries, so it is5+ * run by hand (issue 1104's comments), not here.6+ */7+import { NodeServices } from "@effect/platform-node";8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+import { Client } from "@repo/protocol/contracts";11+import { Effect, FileSystem, Layer, Option, Path, Ref, Schema } from "effect";12+import { CliOutput } from "effect/cli";13+import { TestConsole } from "effect/testing";14+import { build } from "tsdown";15+16+import { compileArgs, parseBuild, versionDefine } from "../build.ts";17+import type { BuildOptions } from "../build.ts";18+import { program } from "../src/main.ts";19+import { OutputPlain } from "../src/output.ts";20+import { cliVersion } from "../src/version.ts";21+import { npm } from "../tsdown.config.ts";22+import { SignedOut } from "./signed-out.ts";23+24+const services = Layer.mergeAll(25+ TestConsole.layer,26+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27+ Layer.mock(Client)({}),28+ OutputPlain,29+ SignedOut30+).pipe(Layer.provideMerge(NodeServices.layer));31+32+/** What a built `version.ts` exports. */33+const Built = Schema.Struct({ cliVersion: Schema.String });34+35+describe("the CLI's version, unbuilt", () => {36+ it.effect("is 0.0.0, and --version prints it", () =>37+ Effect.gen(function* () {38+ yield* program(["--version"]);39+40+ expect({41+ cliVersion,42+ printed: (yield* TestConsole.logLines).map(String),43+ }).toStrictEqual({44+ cliVersion: "0.0.0",45+ printed: [`${Brand.cli} v0.0.0`],46+ });47+ }).pipe(Effect.provide(services))48+ );49+});50+51+describe("the build's version stamp", () => {52+ it.effect(53+ "replaces the expression version.ts reads with the version, as a string literal",54+ () =>55+ Effect.gen(function* () {56+ const fs = yield* FileSystem.FileSystem;57+ const path = yield* Path.Path;58+ const root = yield* path.fromFileUrl(new URL("..", import.meta.url));59+60+ const source = yield* fs.readFileString(61+ path.join(root, "src", "version.ts")62+ );63+64+ const define = versionDefine("9.9.9-test");65+66+ expect({67+ define,68+ unread: Object.keys(define).filter((key) => !source.includes(key)),69+ }).toStrictEqual({70+ define: { "import.meta.env.CLI_BUILD_VERSION": '"9.9.9-test"' },71+ unread: [],72+ });73+ }).pipe(Effect.provide(NodeServices.layer))74+ );75+76+ it("is in every config tsdown.config.ts makes, for the version it is given", () => {77+ expect(npm("9.9.9-test").map((config) => config.define)).toStrictEqual(78+ Array.from({ length: 3 }, () => versionDefine("9.9.9-test"))79+ );80+ });81+82+ it.live(83+ "stamps the npm build: tsdown's build of version.ts reads the version",84+ () =>85+ Effect.gen(function* () {86+ const fs = yield* FileSystem.FileSystem;87+ const path = yield* Path.Path;88+ const root = yield* path.fromFileUrl(new URL("..", import.meta.url));89+90+ const out = yield* fs.makeTempDirectoryScoped({91+ prefix: "cli-version-",92+ });93+94+ const [first] = npm("9.9.9-test");95+96+ yield* Effect.tryPromise(() =>97+ build({98+ ...first,99+ config: false,100+ cwd: root,101+ entry: { version: path.join(root, "src", "version.ts") },102+ logLevel: "silent",103+ outDir: out,104+ })105+ );106+107+ const built = yield* Effect.tryPromise(108+ () => import(path.join(out, "version.js"))109+ ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Built)));110+111+ expect(built.cliVersion).toBe("9.9.9-test");112+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))113+ );114+115+ it("stamps each compiled binary with the same define", () => {116+ expect(117+ compileArgs({118+ entry: "/b/main.ts",119+ outfile: "/b/out",120+ target: "linux-x64",121+ version: "9.9.9-test",122+ })123+ ).toStrictEqual([124+ "build",125+ "--compile",126+ "--minify",127+ "--define",128+ 'import.meta.env.CLI_BUILD_VERSION="9.9.9-test"',129+ "--target=bun-linux-x64",130+ "/b/main.ts",131+ "--outfile",132+ "/b/out",133+ ]);134+ });135+});136+137+/** What the build would run with for `argv`, if it would run. */138+const parsed = (argv: readonly string[]) =>139+ Effect.gen(function* () {140+ const seen = yield* Ref.make(Option.none<BuildOptions>());141+142+ yield* parseBuild(argv, (options) => Ref.set(seen, Option.some(options)));143+144+ return yield* Ref.get(seen);145+ }).pipe(Effect.provide(services));146+147+describe("the build's flags", () => {148+ it.effect(149+ "read --version and --targets, and build 0.0.0 without a version",150+ () =>151+ Effect.gen(function* () {152+ expect({153+ stamped: yield* parsed([154+ "--targets",155+ "bun-linux-x64,darwin-arm64",156+ "--version",157+ "9.9.9-test",158+ ]),159+ unstamped: yield* parsed([]),160+ }).toStrictEqual({161+ stamped: Option.some({162+ targets: ["linux-x64", "darwin-arm64"],163+ version: "9.9.9-test",164+ }),165+ unstamped: Option.some({ targets: [], version: "0.0.0" }),166+ });167+ })168+ );169+});modified:apps/cli/build.ts+116 added-38 removed
15 unmodified lines16 * 4. Beside each binary, `git-credential-<slug>` links to it: the binary17 * sees the name it was started by (`src/bin.ts`), so the link is git's18 * credential helper.19 *20+ * `--version <semver>` stamps both builds (`versionDefine`): it is what21+ * the CLI's `--version` prints. Without it the build says `0.0.0`.22+ *23 * A Bun script, outside every Worker's graph. Names come from `Brand`.24+ * Importing it builds nothing (`tsdown.config.ts` and the tests read its25+ * pure parts): only `bun build.ts` runs the build.26 */27 import { BunRuntime, BunServices } from "@effect/platform-bun";28 import { Brand } from "@repo/brand";29 import {3 unmodified lines33 Option,34 Path,35 Predicate,36 Schema,37+ Stdio,38 } from "effect";33-import { Command, Flag } from "effect/cli";39+import { CliConfig, Command, Flag, GlobalFlag } from "effect/cli";40 import { ChildProcess, ChildProcessSpawner } from "effect/process";41 import { build } from "tsdown";42 43 import { NATIVE, npmMachineOf } from "./build-targets.ts";44 import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";39-import { declarations, library } from "./tsdown.config.ts";45+import {46+ declarations,47+ library,48+ npm,49+ UNSTAMPED,50+ versionDefine,51+} from "./tsdown.config.ts";52 53+// The one define both bundlers get, kept beside tsdown's configs, which54+// this module imports (lint refuses an import cycle).55+export { versionDefine } from "./tsdown.config.ts";56+57+/** What one build is asked for. */58+export interface BuildOptions {59+ /** Bun targets to cross-compile for, without `bun-`; none builds for this machine. */60+ readonly targets: readonly string[];61+ /** The version both builds are stamped with. */62+ readonly version: string;63+}64+65+/**66+ * `bun build --compile`'s arguments for one binary: `entry` compiled to67+ * `outfile`, for `target` (this machine when absent), stamped with `version`.68+ */69+export const compileArgs = (input: {70+ readonly entry: string;71+ readonly outfile: string;72+ readonly target?: string;73+ readonly version: string;74+}) => [75+ "build",76+ "--compile",77+ "--minify",78+ ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [79+ "--define",80+ `${key}=${value}`,81+ ]),82+ ...(input.target === undefined ? [] : [`--target=bun-${input.target}`]),83+ input.entry,84+ "--outfile",85+ input.outfile,86+];87+88 class BuildFailed extends Data.TaggedError("BuildFailed")<{89 readonly step: string;90 readonly detail: string;91 }> {}71 unmodified lines163 catch: (cause) => new BuildFailed({ detail: String(cause), step }),164 try: () => build(config),165 });166 120-const make = (targets: readonly string[]) =>167+const make = ({ targets, version }: BuildOptions) =>168 Effect.gen(function* () {169 const fs = yield* FileSystem.FileSystem;170 const path = yield* Path.Path;171 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));36 unmodified lines208 fs.writeFileString(path.join(dir, name), JSON.stringify(config)),209 path.join(dir, name)210 );211 165- // 1. The npm build.166- yield* tsdown("tsdown", {167- config: path.join(root, "tsdown.config.ts"),168- cwd: root,169- });212+ // 1. The npm build, one entry at a time: the first cleans `dist/`.213+ for (const config of npm(version)) {214+ yield* tsdown(`tsdown ${Object.keys(config.entry).join(", ")}`, {215+ ...config,216+ config: false,217+ cwd: root,218+ });219+ }220 221 // 2. The library entries' types. tsgo declares them in a folder at a222 // fixed path, removed once the build ends: the bundled `.d.ts` files keep223 // each source's path in a comment, so a temp folder's random name would171 unmodified lines395 396 yield* run(397 "bun build --compile",398 "bun",349- [350- "build",351- "--compile",352- "--minify",399+ compileArgs({400+ entry: path.join(compile, "main.ts"),401+ outfile: path.join(dir, Brand.cli),402+ version,403 ...Option.match(target, {354- onNone: () => [],355- onSome: (name) => [`--target=bun-${name}`],404+ onNone: () => ({}),405+ onSome: (name) => ({ target: name }),406 }),357- path.join(compile, "main.ts"),358- "--outfile",359- path.join(dir, Brand.cli),360- ],407+ }),408 { env }409 );410 411 yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));6 unmodified lines418 ),419 Flag.optional420 );421 375-const command = Command.make("build", { targets }, (flags) =>376- make(377- Option.match(flags.targets, {378- onNone: () => [],379- onSome: (list) =>380- list381- .split(",")382- .map((target) => target.trim().replace(/^bun-/u, ""))383- .filter((target) => target.length > 0),384- })385- )386-).pipe(387- Command.withDescription(388- "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."389- )422+const version = Flag.String("version").pipe(423+ Flag.withDescription(424+ `The version both builds are stamped with, which the CLI's --version prints (default ${UNSTAMPED}).`425+ ),426+ Flag.optional427 );428 392-BunRuntime.runMain(393- Command.run(command, { version: "0.0.0" }).pipe(394- Effect.provide(BunServices.layer)395- )396-);429+/** The build's command line, running `then` with what it asks for. */430+const command = <E, R>(431+ then: (options: BuildOptions) => Effect.Effect<void, E, R>432+) =>433+ Command.make("build", { targets, version }, (flags) =>434+ then({435+ targets: Option.match(flags.targets, {436+ onNone: () => [],437+ onSome: (list) =>438+ list439+ .split(",")440+ .map((target) => target.trim().replace(/^bun-/u, ""))441+ .filter((target) => target.length > 0),442+ }),443+ version: Option.getOrElse(flags.version, () => UNSTAMPED),444+ })445+ ).pipe(446+ Command.withDescription(447+ "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."448+ )449+ );450+451+/**452+ * The build's own `--version` takes a value, so effect/cli's built-in453+ * `--version` (a boolean that prints and exits) is left out.454+ */455+const builtIns = CliConfig.make({456+ builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),457+});458+459+/** Runs `then` with what `argv`, the build's arguments, asks for. */460+export const parseBuild = <E, R>(461+ argv: readonly string[],462+ then: (options: BuildOptions) => Effect.Effect<void, E, R>463+) =>464+ Command.runWith(command(then), { version: UNSTAMPED })(argv).pipe(465+ Effect.provideService(CliConfig.CliConfig, builtIns)466+ );467+468+if (import.meta.main) {469+ BunRuntime.runMain(470+ Stdio.Stdio.use(({ args }) =>471+ Effect.flatMap(args, (argv) => parseBuild(argv, make))472+ ).pipe(Effect.provide(BunServices.layer))473+ );474+}modified:apps/cli/tsdown.config.ts+33 added-7 removed
2 unmodified lines34567789101112131415161718192021222324252627282931 unmodified lines616263646566676869707172515253545556737475767778798081822 unmodified lines * command line under Node or Bun, and two library entries, `./rules` (the * sdk a config folder imports) and `./protocol` (the types its data has). * Workspace packages are inlined, so the published package names none of * them; `effect` and `@effect/platform-bun`, the package's own * dependencies, stay imports. * dependencies, stay imports. Each entry is stamped with the version * `build.ts` is given (`npm`). */import { defineConfig } from "tsdown";import type { UserConfig } from "tsdown";
/** What a build no release stamped says it is (the release's `UNRELEASED`). */export const UNSTAMPED = "0.0.0";
/** * What each bundler replaces so `cliVersion` (`src/version.ts`) reads * `version`: the expression it reads, onto the version as a string literal. * `build.ts` hands it to tsdown here (`npm`) and to every `bun build * --compile` (`compileArgs`). */export const versionDefine = (version: string) => ({ "import.meta.env.CLI_BUILD_VERSION": JSON.stringify(version),});
/** The library entries, by the name each is published under. */export const library = { protocol: "src/entries/protocol.ts", rules: "src/entries/rules.ts",31 unmodified lines dts: { dtsInput: true, emitDtsOnly: true, tsconfig }, entry, }) satisfies UserConfig;
/** * The npm build stamped with `version` (`src/version.ts`): one define for * all three entries, so they agree. `build.ts` builds them in order; only * the first cleans `dist/`, so a build one at a time keeps the others' files. */export const npm = (version: string) => { const stamped = { ...shared, define: versionDefine(version), dts: false };
export default defineConfig([ { ...shared, dts: false, entry: { bin: "src/bin.ts" } }, { ...shared, dts: false, entry: library }, // The pi extension, which the publish manifest's `"pi"` key names. { ...shared, dts: false, entry: { pi: "src/pi.ts" } },]); return [ { ...stamped, entry: { bin: "src/bin.ts" } }, { ...stamped, clean: false, entry: library }, // The pi extension, which the publish manifest's `"pi"` key names. { ...stamped, clean: false, entry: { pi: "src/pi.ts" } }, ] satisfies UserConfig[];};
/** `tsdown` run here by hand builds what no release stamped. */export default defineConfig(npm(UNSTAMPED));modified:packages/config/test/release.test.ts+67 added
9 unmodified lines10 Array as Arr,11 Crypto,12 Effect,13 FileSystem,14+ Layer,15 Option,16 Order,17 Path,18+ Ref,19 Result,20 Schema,21+ Sink,22 Stream,23 } from "effect";24 import { ChildProcess, ChildProcessSpawner } from "effect/process";25 18 unmodified lines44 uploads,45 VersionNeeded,46 VersionReleased,47 } from "../../../scripts/lib/release.ts";48+import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";49 import { Brand } from "../../brand/src/index.ts";50 import { repoRoot } from "./root.ts";51 52 /** What the test reads of a package manifest. */378 unmodified lines431 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },432 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },433 };434 435+/**436+ * A spawner that runs nothing and exits 0: each command it was asked for,437+ * as `<folder>$ <command> <args>`, its folder relative to the repo root.438+ */439+const recordingSpawner = Effect.gen(function* () {440+ const path = yield* Path.Path;441+ const root = yield* repoRoot;442+ const lines = yield* Ref.make<readonly string[]>([]);443+444+ const spawner = ChildProcessSpawner.make((command) =>445+ Effect.gen(function* () {446+ if (!ChildProcess.isStandardCommand(command)) {447+ return yield* Effect.die("the release pipes no commands");448+ }449+450+ yield* Ref.update(lines, (all) => [451+ ...all,452+ `${path.relative(root, command.options.cwd ?? root)}$ ${[command.command, ...command.args].join(" ")}`,453+ ]);454+455+ return ChildProcessSpawner.makeHandle({456+ all: Stream.empty,457+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),458+ getInputFd: () => Sink.drain,459+ getOutputFd: () => Stream.empty,460+ isRunning: Effect.succeed(false),461+ kill: () => Effect.void,462+ pid: ChildProcessSpawner.ProcessId(1),463+ stderr: Stream.empty,464+ stdin: Sink.drain,465+ stdout: Stream.empty,466+ unref: Effect.succeed(Effect.void),467+ });468+ })469+ );470+471+ return {472+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),473+ spawned: Ref.get(lines),474+ };475+});476+477+describe("a release's build step", () => {478+ it.effect(479+ "builds the CLI stamped with the release's version, for both targets",480+ () =>481+ Effect.gen(function* () {482+ const { layer, spawned } = yield* recordingSpawner;483+ const layout = yield* layoutOf(yield* repoRoot);484+485+ yield* runStep("tsdown", layout, {486+ origin: "https://platform.example",487+ stage: Option.none(),488+ version: "0.2.0-demo.1",489+ }).pipe(Effect.provide(layer));490+491+ expect(yield* spawned).toStrictEqual([492+ "apps/cli$ bun run build -- --targets bun-linux-x64,bun-darwin-arm64 --version 0.2.0-demo.1",493+ ]);494+ }).pipe(Effect.provide(NodeServices.layer))495+ );496+});497+498 describe("the release manifest", () => {499 it.effect(500 "keeps every earlier version, makes the new one latest, and is what the platform decodes",501 () =>259 unmodified linesmodified:scripts/lib/release/steps.ts+11 added-2 removed
1 unmodified line2 * 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);6+ * (`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`'s603 unmodified lines615 Match.when("tsdown", () =>616 run(617 "tsdown",618 "bun",618- ["run", "build", "--", "--targets", targets.join(",")],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)),8 unmodified linesmodified:scripts/lib/release.ts+4 added-2 removed
388 unmodified lines389 })390 );391 392 /**393- * What the CLI reports itself as until a build stamps it (`main.ts`394- * says `0.0.0`), and so what a build that neither uploads nor publishes is.393+ * What a build that neither uploads nor publishes is stamped with. The394+ * 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`).397 */398 const UNRELEASED = "0.0.0";399 400 /**136 unmodified lines