Skip to content
Myr

cli.ts

This file

Path

packages/protocol/src/cli.ts

609 lines · 18.1 KiB · TypeScript

Last changed by

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

History of this file

Take it

1// Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-command.ts`2// l.14–247, and ours to change since: it projects the contracts' Rpcs, named3// and given positionals by the `Cli` annotation, not Rat Stack's capabilities.4// Rat Stack's licence travels with the code it copied:5//6// MIT License7//8// Copyright (c) 2026 Joel Hooks9//10// Permission is hereby granted, free of charge, to any person obtaining a copy11// of this software and associated documentation files (the "Software"), to deal12// in the Software without restriction, including without limitation the rights13// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell14// copies of the Software, and to permit persons to whom the Software is15// furnished to do so, subject to the following conditions:16//17// The above copyright notice and this permission notice shall be included in all18// copies or substantial portions of the Software.19//20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR21// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,22// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE23// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER24// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,25// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE26// SOFTWARE.2728import {29  Array,30  Config,31  Context,32  Effect,33  Option,34  Predicate,35  Runtime,36  Schema,37  SchemaAST,38} from "effect";39import { Argument, Command, Flag } from "effect/cli";40import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";4142import {43  Cli,44  Description,45  NeedsApproval,46  ReadOnly,47  Surfaces,48} from "./annotations.ts";49import { ExitCode, exitCodeFor } from "./exit-code.ts";50import type { Unauthenticated } from "./principal.ts";51import { Refusal } from "./refusal.ts";5253type CallError = RpcClientError.RpcClientError | Unauthenticated;5455type Plain = Schema.Top & {56  readonly DecodingServices: never;57  readonly EncodingServices: never;58};5960export type CommandRpc = Rpc.AnyWithProps & {61  readonly errorSchema: Plain;62  readonly payloadSchema: Plain;63  readonly successSchema: Plain;64};6566export interface View {67  readonly markdown: string;68  readonly text?: string;69}7071export interface CommandOutput {72  readonly success: (input: {73    readonly command: string;74    readonly json: boolean;75    readonly data: unknown;76    readonly view: View;77  }) => Effect.Effect<void>;78  readonly refused: (input: {79    readonly command: string;80    readonly json: boolean;81    readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;82  }) => Effect.Effect<void>;83  readonly plan: (input: {84    readonly command: string;85    readonly json: boolean;86    readonly payload: unknown;87  }) => Effect.Effect<void>;88}8990export interface Defaults<R> {91  readonly fields: Readonly<Record<string, string>>;92  readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;93}9495export interface ToCommandOptions<Success, OutputR, DefaultsR> {96  readonly output: Effect.Effect<CommandOutput, never, OutputR>;97  readonly defaults?: Defaults<DefaultsR> | undefined;98  readonly render?: ((success: Success) => Option.Option<View>) | undefined;99  readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;100}101102export type Views<Rpcs extends Rpc.Any> = Readonly<103  Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>104>;105106export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(107  "ApprovalNeeded",108  { command: Schema.String }109) {110  override get message() {111    return `${this.command} needs a person's approval: run it again with --yes, or with --dry-run to see what it would send`;112  }113}114115export class MissingValue extends Schema.TaggedError<MissingValue>()(116  "MissingValue",117  { command: Schema.String, flag: Schema.String }118) {119  override get message() {120    return `${this.command} needs ${this.flag}: give it, since nothing here does`;121  }122}123124export class Reported extends Schema.TaggedError<Reported>()("Reported", {125  exitCode: Schema.optionalKey(Schema.Int),126}) {127  override readonly [Runtime.errorExitCode] = this.exitCode ?? ExitCode.failed;128  override readonly [Runtime.errorReported] = false;129130  static readonly of = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>131    new Reported({ exitCode: exitCodeFor(refusals) });132}133134export const endRefused = (135  output: Pick<CommandOutput, "refused">,136  input: Parameters<CommandOutput["refused"]>[0]137): Effect.Effect<never, Reported> =>138  Effect.andThen(139    output.refused(input),140    Effect.fail(Reported.of(input.refusals))141  );142143interface FieldSpec {144  readonly description: string | undefined;145  readonly kind:146    | "string"147    | "number"148    | "boolean"149    | "switch"150    | "literals"151    | "json";152  readonly literals: readonly string[];153  readonly optional: boolean;154}155156const literalOf = (ast: SchemaAST.AST): string | undefined =>157  SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)158    ? ast.literal159    : undefined;160161const primitiveKinds: Partial<162  Record<SchemaAST.AST["_tag"], FieldSpec["kind"]>163> = {164  Boolean: "boolean",165  Number: "number",166  String: "string",167};168169const primitiveKind = (ast: SchemaAST.AST): FieldSpec["kind"] =>170  primitiveKinds[ast._tag] ?? "json";171172const describe = (field: Plain): FieldSpec => {173  let ast: SchemaAST.AST = field.ast;174  let optional = ast.context?.isOptional === true;175176  const description = SchemaAST.resolveDescription(ast);177178  if (SchemaAST.isUnion(ast)) {179    const members = ast.types.filter(180      (member) => !SchemaAST.isUndefined(member)181    );182183    if (members.length < ast.types.length) {184      optional = true;185    }186187    const [only] = members;188189    if (members.length === 1 && only !== undefined) {190      ast = only;191    } else {192      const literals = members.map(literalOf);193194      if (literals.every((literal) => literal !== undefined)) {195        return { description, kind: "literals", literals, optional };196      }197198      return { description, kind: "json", literals: [], optional };199    }200  }201202  // A field that is `true` or absent is a switch: named, it is on.203  if (SchemaAST.isLiteral(ast) && ast.literal === true) {204    return { description, kind: "switch", literals: [], optional };205  }206207  const literal = literalOf(ast);208209  if (literal !== undefined) {210    return { description, kind: "literals", literals: [literal], optional };211  }212213  const kind = primitiveKind(ast);214215  return { description, kind, literals: [], optional };216};217218const fieldsOf = (payload: Plain): readonly (readonly [string, Plain])[] =>219  SchemaAST.isObjects(payload.ast)220    ? payload.ast.propertySignatures.flatMap(({ name, type }) =>221        Predicate.isString(name)222          ? [[name, Schema.make<Schema.Codec<unknown>>(type)] as const]223          : []224      )225    : [];226227const isRequired = (spec: FieldSpec) =>228  !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";229230const jsonFlag = (name: string, field: Plain) =>231  Flag.String(name).pipe(232    Flag.withSchema(Schema.fromJsonString(field)),233    Flag.withMetavar("JSON")234  );235236const flagBuilders = {237  boolean: (name) => Flag.Boolean(name).pipe(Flag.withDefault(false)),238  json: (name, field) => jsonFlag(name, field),239  literals: (name, _field, spec) => Flag.Literals(name, spec.literals),240  number: (name) => Flag.Finite(name),241  // The field's own schema checks the text, so a malformed value is refused242  // by the parser, naming its flag, before anything is called.243  string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),244  switch: (name) =>245    Flag.Boolean(name).pipe(246      Flag.withDefault(false),247      Flag.map((on) => (on ? true : undefined))248    ),249} satisfies Record<250  FieldSpec["kind"],251  (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>252>;253254const helpOf = (spec: FieldSpec, fallback: string | undefined) => {255  if (fallback === undefined) {256    return spec.description;257  }258259  return spec.description === undefined260    ? `Defaults to ${fallback}`261    : `${spec.description}; defaults to ${fallback}`;262};263264const flagFor = (265  name: string,266  field: Plain,267  fallback: string | undefined268): Flag.Flag<unknown> => {269  const spec = describe(field);270  const base = flagBuilders[spec.kind](name, field, spec);271  const help = helpOf(spec, fallback);272273  const described =274    help === undefined ? base : base.pipe(Flag.withDescription(help));275276  return (spec.optional || fallback !== undefined) &&277    spec.kind !== "boolean" &&278    spec.kind !== "switch"279    ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))280    : described;281};282283const schemaArgument = (name: string, field: Plain, metavar: string) =>284  Argument.String(name).pipe(285    Argument.withSchema(Schema.fromJsonString(field)),286    Argument.withMetavar(metavar)287  );288289const argumentBuilders = {290  boolean: (name, field) => schemaArgument(name, field, "BOOLEAN"),291  json: (name, field) => schemaArgument(name, field, "JSON"),292  literals: (name, _field, spec) => Argument.Literals(name, spec.literals),293  number: (name) => Argument.Finite(name),294  string: (name) => Argument.String(name),295  switch: (name, field) => schemaArgument(name, field, "true"),296} satisfies Record<297  FieldSpec["kind"],298  (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>299>;300301/**302 * The former flag may still give the value, so the parser lets the argument303 * be left out and the handler refuses if neither did. Unlike304 * `Argument.optional`, a fallback keeps help showing it as required.305 */306const leftOutForNow = (307  argument: Argument.Argument<unknown>308): Argument.Argument<unknown> =>309  argument.pipe(310    Argument.map(Option.some),311    Argument.withFallbackConfig(Config.succeed(Option.none())),312    Argument.map(Option.getOrUndefined)313  );314315const argumentFor = (316  name: string,317  field: Plain,318  fallback: string | undefined,319  wasFlag: boolean320): Argument.Argument<unknown> => {321  const spec = describe(field);322  const base = argumentBuilders[spec.kind](name, field, spec);323  const help = helpOf(spec, fallback);324325  const described =326    help === undefined ? base : base.pipe(Argument.withDescription(help));327328  if (spec.optional || fallback !== undefined) {329    return described.pipe(330      Argument.optional,331      Argument.map(Option.getOrUndefined)332    );333  }334335  return wasFlag ? leftOutForNow(described) : described;336};337338/** Still parses, checked by the field's schema, but hidden from help. */339const formerFlagFor = (name: string, field: Plain): Flag.Flag<unknown> => {340  const spec = describe(field);341342  return flagBuilders[spec.kind](name, field, spec).pipe(343    Flag.withHidden,344    Flag.optional,345    Flag.map(Option.getOrUndefined)346  );347};348349const controls = (approval: boolean, readOnly: boolean) =>350  Object.fromEntries([351    [352      "json",353      Flag.Boolean("json").pipe(354        Flag.withDefault(false),355        Flag.withDescription(356          "Print one versioned JSON envelope on stdout, and nothing else there"357        )358      ),359    ],360    ...(approval361      ? [362          [363            "yes",364            Flag.Boolean("yes").pipe(365              Flag.withDefault(false),366              Flag.withDescription(367                "Approve it: it runs only with --yes, since a person approves it first"368              )369            ),370          ] as const,371        ]372      : []),373    ...(readOnly374      ? []375      : [376          [377            "dryRun",378            Flag.Boolean("dry-run").pipe(379              Flag.withDefault(false),380              Flag.withDescription(381                "Print the payload it would send, and send nothing"382              )383            ),384          ] as const,385        ]),386  ]);387388const isRefusal = Schema.is(Refusal);389390export const commandName = (rpc: Rpc.AnyWithProps): string =>391  Context.get(rpc.annotations, Cli).name ?? rpc._tag;392393export const commandPath = (394  rpc: Rpc.AnyWithProps395): readonly [string, ...string[]] => {396  const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");397398  return [first, ...rest];399};400401const asJson = (text: string): View => ({402  markdown: ["```json", text, "```"].join("\n"),403  text,404});405406export const toCommand = <407  R extends CommandRpc,408  ClientR,409  OutputR,410  DefaultsR = never,411>(412  rpc: R,413  client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, ClientR>,414  options: ToCommandOptions<Rpc.Success<R>, OutputR, DefaultsR>415) => {416  const cli = Context.get(rpc.annotations, Cli);417  const command = commandName(rpc);418  const positional = new Set(cli.positional);419420  const wasFlag = new Set(421    cli.formerFlags?.filter((name) => positional.has(name))422  );423424  const approval = Context.get(rpc.annotations, NeedsApproval);425  const readOnly = Context.get(rpc.annotations, ReadOnly);426  const filled = options.defaults?.fields ?? {};427  const fields = fieldsOf(rpc.payloadSchema);428429  const required = fields.flatMap(([name, field]) =>430    isRequired(describe(field)) ? [name] : []431  );432433  const payload: Record<434    string,435    Flag.Flag<unknown> | Argument.Argument<unknown>436  > = {};437438  const former: Record<string, Flag.Flag<unknown>> = {};439440  for (const [name, field] of fields) {441    const fallback = required.includes(name) ? filled[name] : undefined;442443    payload[name] = positional.has(name)444      ? argumentFor(name, field, fallback, wasFlag.has(name))445      : flagFor(name, field, fallback);446447    if (wasFlag.has(name)) {448      former[name] = formerFlagFor(name, field);449    }450  }451452  const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);453  const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);454  const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);455456  const complete = (given: readonly (readonly [string, unknown])[]) =>457    Effect.gen(function* () {458      const provided = Object.fromEntries(459        given.filter(([, value]) => value !== undefined)460      );461462      const wanting = required.filter(463        (name) => !Object.hasOwn(provided, name) && Object.hasOwn(filled, name)464      );465466      const values: Readonly<Record<string, string>> =467        wanting.length === 0 || options.defaults === undefined468          ? {}469          : yield* options.defaults.values;470471      const merged = {472        ...provided,473        ...Object.fromEntries(474          wanting.flatMap((name) =>475            values[name] === undefined ? [] : [[name, values[name]] as const]476          )477        ),478      };479480      const missing = required.find((name) => !Object.hasOwn(merged, name));481482      if (missing !== undefined) {483        return yield* new MissingValue({484          command,485          flag: positional.has(missing) ? `<${missing}>` : `--${missing}`,486        });487      }488489      return yield* decodePayload(merged);490    });491492  return Command.make(493    commandPath(rpc).at(-1) ?? rpc._tag,494    { control: controls(approval, readOnly), former, payload },495    ({ control, former: formerly, payload: given }) =>496      Effect.gen(function* () {497        const json = control.json === true;498        const dryRun = control.dryRun === true;499500        if (approval && control.yes !== true && !dryRun) {501          return yield* new ApprovalNeeded({ command });502        }503504        const decoded = yield* complete(505          Object.entries(given).map(506            ([name, value]) => [name, value ?? formerly[name]] as const507          )508        );509510        const output = yield* options.output;511512        if (dryRun) {513          const encoded = yield* Effect.orDie(encodePayload(decoded));514515          return yield* output.plan({ command, json, payload: encoded });516        }517518        const calls = yield* client;519520        // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `decoded` was just decoded with that Rpc's payload schema.521        // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the client's mapped type cannot be indexed by a generic tag; see SAFETY.522        const byTag = calls as Readonly<523          Record<524            string,525            (526              payload: typeof decoded527            ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | CallError>528          >529        >;530531        const call =532          byTag[rpc._tag] ??533          (() => Effect.die(`The client has no method for ${rpc._tag}`));534535        const success = yield* call(decoded).pipe(536          Effect.catchIf(isRefusal, (refusal) =>537            endRefused(output, { command, json, refusals: [refusal] })538          )539        );540541        const carried = options.refusalsIn?.(success) ?? [];542543        if (Array.isReadonlyArrayNonEmpty(carried)) {544          return yield* endRefused(output, {545            command,546            json,547            refusals: carried,548          });549        }550551        const data = yield* Effect.orDie(encodeSuccess(success));552553        const view = Option.getOrElse(554          options.render === undefined555            ? Option.none()556            : options.render(success),557          () => asJson(JSON.stringify(data, null, 2))558        );559560        return yield* output.success({ command, data, json, view });561      }).pipe(Effect.withSpan(`protocol.${rpc._tag}`))562  ).pipe(563    Command.withDescription(564      [565        Context.get(rpc.annotations, Description),566        ...(readOnly ? ["It only reads."] : []),567        ...(approval ? ["It runs only with --yes: a person approves it."] : []),568      ].join(" ")569    )570  );571};572573export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {574  readonly output: Effect.Effect<CommandOutput, never, OutputR>;575  readonly defaults?: Defaults<DefaultsR> | undefined;576  readonly views?: Views<Rpcs> | undefined;577  readonly refusalsIn?:578    | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])579    | undefined;580  readonly exclude: readonly string[];581}582583export const toCommands = <584  Rpcs extends CommandRpc,585  ClientR,586  OutputR,587  DefaultsR = never,588>(589  group: RpcGroup.RpcGroup<Rpcs>,590  client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, ClientR>,591  options: ToCommandsOptions<Rpcs, OutputR, DefaultsR>592) =>593  [...group.requests.values()].flatMap((rpc) =>594    Context.get(rpc.annotations, Surfaces).includes("cli") &&595    !options.exclude.includes(rpc._tag)596      ? [597          {598            command: toCommand(rpc, client, {599              defaults: options.defaults,600              output: options.output,601              refusalsIn: options.refusalsIn,602              render: options.views?.[rpc._tag],603            }),604            path: commandPath(rpc),605            rpc,606          },607        ]608      : []609  );