Skip to content
Myr

build.ts

This file

Path

apps/cli/build.ts

408 lines · 11.7 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Brand } from "@repo/brand";3import {4  Data,5  Effect,6  FileSystem,7  Option,8  Path,9  Predicate,10  Schema,11  Stdio,12} from "effect";13import { CliConfig, Command, Flag, GlobalFlag } from "effect/cli";14import { ChildProcess, ChildProcessSpawner } from "effect/process";15import { build } from "tsdown";1617import { NATIVE, npmMachineOf } from "./build-targets.ts";18import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";19import {20  declarations,21  library,22  npm,23  UNSTAMPED,24  versionDefine,25} from "./tsdown.config.ts";2627// Re-exported: tsdown.config.ts defines it, as importing this module would be a cycle.28export { versionDefine } from "./tsdown.config.ts";2930export interface BuildOptions {31  readonly targets: readonly string[];32  readonly version: string;33}3435export const compileArgs = (input: {36  readonly entry: string;37  readonly outfile: string;38  readonly target?: string;39  readonly version: string;40}) => [41  "build",42  "--compile",43  "--minify",44  ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [45    "--define",46    `${key}=${value}`,47  ]),48  ...(input.target === undefined ? [] : [`--target=bun-${input.target}`]),49  input.entry,50  "--outfile",51  input.outfile,52];5354class BuildFailed extends Data.TaggedError("BuildFailed")<{55  readonly step: string;56  readonly detail: string;57}> {}5859interface Tsconfig {60  readonly compilerOptions: {61    readonly declaration?: boolean;62    readonly emitDeclarationOnly?: boolean;63    readonly noCheck?: boolean;64    readonly noEmit?: boolean;65    readonly outDir?: string;66    readonly paths: Readonly<Record<string, readonly string[]>>;67    readonly rootDir?: string;68  };69  readonly extends?: string;70  readonly files: readonly string[];71  readonly include?: readonly string[];72}7374const NativeManifest = Schema.fromJsonString(75  Schema.Struct({76    optionalDependencies: Schema.Record(Schema.String, Schema.String),77  })78);7980const Manifest = Schema.fromJsonString(81  Schema.Struct({82    exports: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),83    name: Schema.String,84  })85);8687const run = (88  step: string,89  command: string,90  args: readonly string[],91  options: {92    readonly cwd?: string;93    readonly env?: Readonly<Record<string, string>>;94  } = {}95) =>96  Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>97    spawner.exitCode(98      ChildProcess.make(command, args, {99        cwd: options.cwd,100        env: { ...options.env },101        extendEnv: true,102        stderr: "inherit",103        stdin: "ignore",104        stdout: "inherit",105      })106    )107  ).pipe(108    Effect.mapError(109      (failure) => new BuildFailed({ detail: failure.message, step })110    ),111    Effect.filterOrFail(112      (exitCode) => exitCode === 0,113      (exitCode) => new BuildFailed({ detail: `exit code ${exitCode}`, step })114    ),115    Effect.asVoid116  );117118const tsdown = (step: string, config: Parameters<typeof build>[0]) =>119  Effect.tryPromise({120    catch: (cause) => new BuildFailed({ detail: String(cause), step }),121    try: () => build(config),122  });123124const make = ({ targets, version }: BuildOptions) =>125  Effect.gen(function* () {126    const fs = yield* FileSystem.FileSystem;127    const path = yield* Path.Path;128    const root = yield* path.fromFileUrl(new URL(".", import.meta.url));129    const repo = path.join(root, "..", "..");130    const dist = path.join(root, "dist");131132    const workspacePaths = (onto: (file: string) => string) =>133      Effect.gen(function* () {134        const packages = path.join(repo, "packages");135        const paths: Record<string, readonly string[]> = {};136137        for (const folder of yield* fs.readDirectory(packages)) {138          const manifest = path.join(packages, folder, "package.json");139140          if (yield* fs.exists(manifest)) {141            const { exports = {}, name } = yield* fs142              .readFileString(manifest)143              .pipe(Effect.flatMap(Schema.decodeEffect(Manifest)));144145            for (const [subpath, file] of Object.entries(exports)) {146              if (Predicate.isString(file)) {147                paths[`${name}${subpath.slice(1)}`] = [148                  onto(path.join(packages, folder, file)),149                ];150              }151            }152          }153        }154155        return paths;156      });157158    const tsconfigIn = (dir: string, name: string, config: Tsconfig) =>159      Effect.as(160        fs.writeFileString(path.join(dir, name), JSON.stringify(config)),161        path.join(dir, name)162      );163164    for (const config of npm(version)) {165      yield* tsdown(`tsdown ${Object.keys(config.entry).join(", ")}`, {166        ...config,167        config: false,168        cwd: root,169      });170    }171172    // A fixed path, not a temp folder: the bundled .d.ts files keep each173    // source path in a comment, so a random name would change every build.174    const scratch = path.join(dist, ".types");175176    yield* Effect.acquireRelease(177      fs.makeDirectory(scratch, { recursive: true }),178      () => Effect.orDie(fs.remove(scratch, { recursive: true }))179    );180181    const declared = path.join(scratch, "declared");182183    const declaration = (file: string) =>184      path.join(declared, path.relative(repo, file)).replace(/\.ts$/u, ".d.ts");185186    const emit = yield* tsconfigIn(scratch, "emit.json", {187      compilerOptions: {188        declaration: true,189        emitDeclarationOnly: true,190        // Typecheck has checked these sources; this only declares them.191        noCheck: true,192        noEmit: false,193        outDir: declared,194        paths: yield* workspacePaths((file) => file),195        rootDir: repo,196      },197      extends: path.join(root, "tsconfig.json"),198      files: Object.values(library).map((entry) => path.join(root, entry)),199      include: [],200    });201202    yield* run("tsgo", "bun", [203      path.join(root, "node_modules", "typescript", "bin", "tsc"),204      "--project",205      emit,206    ]);207208    const types = yield* tsconfigIn(scratch, "types.json", {209      compilerOptions: { paths: yield* workspacePaths(declaration) },210      files: [],211    });212213    yield* tsdown("declarations", {214      ...declarations(215        {216          protocol: declaration(path.join(root, library.protocol)),217          rules: declaration(path.join(root, library.rules)),218        },219        types220      ),221      config: false,222      cwd: root,223    });224225    // Bundled whole (a machine with only the binary has no node_modules);226    // runtime.ts sets their embedded paths before src/bin.ts runs.227    const compile = path.join(dist, ".compile");228229    yield* Effect.acquireRelease(230      fs.makeDirectory(compile, { recursive: true }),231      () => Effect.orDie(fs.remove(compile, { recursive: true }))232    );233234    for (const [name, source] of [235      ["sdk.js", path.join(repo, "packages", "sdk", "src", "index.ts")],236      ["entry.js", path.join(repo, "packages", "rules", "src", "entry.ts")],237    ] as const) {238      yield* run(`bundle ${name}`, "bun", [239        "build",240        "--no-macros",241        "--target=browser",242        "--format=esm",243        source,244        "--outfile",245        path.join(compile, name),246      ]);247    }248249    yield* fs.writeFileString(250      path.join(compile, "runtime.ts"),251      [252        'import entry from "./entry.js" with { type: "file" };',253        'import sdk from "./sdk.js" with { type: "file" };',254        "",255        `Object.assign(globalThis, { ${EMBEDDED_KEY}: { entry, sdk } });`,256        "",257      ].join("\n")258    );259260    yield* fs.writeFileString(261      path.join(compile, "main.ts"),262      [263        'import "./runtime.ts";',264        `import ${JSON.stringify(path.join(root, "src", "bin.ts"))};`,265        "",266      ].join("\n")267    );268269    /** `bun install` installed only this machine's native packages. */270    const nativeFor = (target: string) =>271      Effect.gen(function* () {272        const machine = yield* Effect.fromOption(npmMachineOf(target)).pipe(273          Effect.mapError(274            () =>275              new BuildFailed({276                detail: `Bun names no machine ${target}`,277                step: "native packages",278              })279          )280        );281282        const dependencies: Record<string, string> = {};283284        for (const name of NATIVE) {285          const manifest = yield* path.fromFileUrl(286            new URL(import.meta.resolve(`${name}/package.json`))287          );288289          const { optionalDependencies } = yield* fs290            .readFileString(manifest)291            .pipe(Effect.flatMap(Schema.decodeEffect(NativeManifest)));292293          Object.assign(dependencies, optionalDependencies);294        }295296        const folder = yield* fs.makeTempDirectoryScoped({297          prefix: `${Brand.slug}-native-`,298        });299300        yield* fs.writeFileString(301          path.join(folder, "package.json"),302          JSON.stringify({ dependencies, name: "native", private: true })303        );304305        yield* run(306          `native packages for ${target}`,307          "bun",308          [309            "install",310            "--no-save",311            `--os=${machine.os}`,312            `--cpu=${machine.cpu}`,313          ],314          { cwd: folder }315        );316317        return path.join(folder, "node_modules");318      });319320    const outputs =321      targets.length === 0322        ? [{ dir: path.join(dist, "bin"), target: Option.none<string>() }]323        : targets.map((target) => ({324            dir: path.join(dist, "bin", target),325            target: Option.some(target),326          }));327328    for (const { dir, target } of outputs) {329      const env = yield* Option.match(target, {330        onNone: () => Effect.succeed({}),331        onSome: (name) =>332          Effect.map(nativeFor(name), (modules) => ({ NODE_PATH: modules })),333      });334335      yield* run(336        "bun build --compile",337        "bun",338        compileArgs({339          entry: path.join(compile, "main.ts"),340          outfile: path.join(dir, Brand.cli),341          version,342          ...Option.match(target, {343            onNone: () => ({}),344            onSome: (name) => ({ target: name }),345          }),346        }),347        { env }348      );349350      yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));351    }352  }).pipe(Effect.scoped);353354const targets = Flag.String("targets").pipe(355  Flag.withDescription(356    "Cross-compile for these Bun targets, comma-separated (linux-x64,darwin-arm64); each binary goes to dist/bin/<target>/."357  ),358  Flag.optional359);360361const version = Flag.String("version").pipe(362  Flag.withDescription(363    `The version both builds are stamped with, which the CLI's --version prints (default ${UNSTAMPED}).`364  ),365  Flag.optional366);367368const command = <E, R>(369  then: (options: BuildOptions) => Effect.Effect<void, E, R>370) =>371  Command.make("build", { targets, version }, (flags) =>372    then({373      targets: Option.match(flags.targets, {374        onNone: () => [],375        onSome: (list) =>376          list377            .split(",")378            .map((target) => target.trim().replace(/^bun-/u, ""))379            .filter((target) => target.length > 0),380      }),381      version: Option.getOrElse(flags.version, () => UNSTAMPED),382    })383  ).pipe(384    Command.withDescription(385      "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."386    )387  );388389// The build's `--version` takes a value, so effect/cli's boolean one is dropped.390const builtIns = CliConfig.make({391  builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),392});393394export const parseBuild = <E, R>(395  argv: readonly string[],396  then: (options: BuildOptions) => Effect.Effect<void, E, R>397) =>398  Command.runWith(command(then), { version: UNSTAMPED })(argv).pipe(399    Effect.provideService(CliConfig.CliConfig, builtIns)400  );401402if (import.meta.main) {403  BunRuntime.runMain(404    Stdio.Stdio.use(({ args }) =>405      Effect.flatMap(args, (argv) => parseBuild(argv, make))406    ).pipe(Effect.provide(BunServices.layer))407  );408}