Skip to content
Myr

cli.ts

This file

Path

packages/protocol/src/cli.ts

598 lines · 18.0 KiB · TypeScript

Last changed by

Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b

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}9495/** A view is pure, or looks around first (the repo the command stands in) with the defaults' services. */96export type Render<Success, R> = (97  success: Success98) => Option.Option<View> | Effect.Effect<Option.Option<View>, never, R>;99100export interface ToCommandOptions<Success, OutputR, DefaultsR> {101  readonly output: Effect.Effect<CommandOutput, never, OutputR>;102  readonly defaults?: Defaults<DefaultsR> | undefined;103  readonly render?: Render<Success, DefaultsR> | undefined;104  readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;105}106107export type Views<Rpcs extends Rpc.Any, R = never> = Readonly<108  Record<string, Render<Rpc.Success<Rpcs>, R>>109>;110111export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(112  "ApprovalNeeded",113  { command: Schema.String }114) {115  override get message() {116    return `${this.command} needs a person's approval: run it again with --yes, or with --dry-run to see what it would send`;117  }118}119120export class MissingValue extends Schema.TaggedError<MissingValue>()(121  "MissingValue",122  { command: Schema.String, flag: Schema.String }123) {124  override get message() {125    return `${this.command} needs ${this.flag}: give it, since nothing here does`;126  }127}128129export class Reported extends Schema.TaggedError<Reported>()("Reported", {130  exitCode: Schema.optionalKey(Schema.Int),131}) {132  override readonly [Runtime.errorExitCode] = this.exitCode ?? ExitCode.failed;133  override readonly [Runtime.errorReported] = false;134135  static readonly of = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>136    new Reported({ exitCode: exitCodeFor(refusals) });137}138139export const endRefused = (140  output: Pick<CommandOutput, "refused">,141  input: Parameters<CommandOutput["refused"]>[0]142): Effect.Effect<never, Reported> =>143  Effect.andThen(144    output.refused(input),145    Effect.fail(Reported.of(input.refusals))146  );147148interface FieldSpec {149  readonly description: string | undefined;150  readonly kind: "string" | "number" | "boolean" | "literals" | "json";151  readonly literals: readonly string[];152  readonly optional: boolean;153}154155const literalOf = (ast: SchemaAST.AST): string | undefined =>156  SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)157    ? ast.literal158    : undefined;159160const primitiveKinds: Partial<161  Record<SchemaAST.AST["_tag"], FieldSpec["kind"]>162> = {163  Boolean: "boolean",164  Number: "number",165  String: "string",166};167168const primitiveKind = (ast: SchemaAST.AST): FieldSpec["kind"] =>169  primitiveKinds[ast._tag] ?? "json";170171const describe = (field: Plain): FieldSpec => {172  let ast: SchemaAST.AST = field.ast;173  let optional = ast.context?.isOptional === true;174175  const description = SchemaAST.resolveDescription(ast);176177  if (SchemaAST.isUnion(ast)) {178    const members = ast.types.filter(179      (member) => !SchemaAST.isUndefined(member)180    );181182    if (members.length < ast.types.length) {183      optional = true;184    }185186    const [only] = members;187188    if (members.length === 1 && only !== undefined) {189      ast = only;190    } else {191      const literals = members.map(literalOf);192193      if (literals.every((literal) => literal !== undefined)) {194        return { description, kind: "literals", literals, optional };195      }196197      return { description, kind: "json", literals: [], optional };198    }199  }200201  const literal = literalOf(ast);202203  if (literal !== undefined) {204    return { description, kind: "literals", literals: [literal], optional };205  }206207  const kind = primitiveKind(ast);208209  return { description, kind, literals: [], optional };210};211212const fieldsOf = (payload: Plain): readonly (readonly [string, Plain])[] =>213  SchemaAST.isObjects(payload.ast)214    ? payload.ast.propertySignatures.flatMap(({ name, type }) =>215        Predicate.isString(name)216          ? [[name, Schema.make<Schema.Codec<unknown>>(type)] as const]217          : []218      )219    : [];220221const isRequired = (spec: FieldSpec) =>222  !spec.optional && spec.kind !== "boolean";223224const jsonFlag = (name: string, field: Plain) =>225  Flag.String(name).pipe(226    Flag.withSchema(Schema.fromJsonString(field)),227    Flag.withMetavar("JSON")228  );229230const flagBuilders = {231  boolean: (name) => Flag.Boolean(name).pipe(Flag.withDefault(false)),232  json: (name, field) => jsonFlag(name, field),233  literals: (name, _field, spec) => Flag.Literals(name, spec.literals),234  number: (name) => Flag.Finite(name),235  // The field's own schema checks the text, so a malformed value is refused236  // by the parser, naming its flag, before anything is called.237  string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),238} satisfies Record<239  FieldSpec["kind"],240  (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>241>;242243const helpOf = (spec: FieldSpec, fallback: string | undefined) => {244  if (fallback === undefined) {245    return spec.description;246  }247248  return spec.description === undefined249    ? `Defaults to ${fallback}`250    : `${spec.description}; defaults to ${fallback}`;251};252253const flagFor = (254  name: string,255  field: Plain,256  fallback: string | undefined257): Flag.Flag<unknown> => {258  const spec = describe(field);259  const base = flagBuilders[spec.kind](name, field, spec);260  const help = helpOf(spec, fallback);261262  const described =263    help === undefined ? base : base.pipe(Flag.withDescription(help));264265  return (spec.optional || fallback !== undefined) && spec.kind !== "boolean"266    ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))267    : described;268};269270const schemaArgument = (name: string, field: Plain, metavar: string) =>271  Argument.String(name).pipe(272    Argument.withSchema(Schema.fromJsonString(field)),273    Argument.withMetavar(metavar)274  );275276const argumentBuilders = {277  boolean: (name, field) => schemaArgument(name, field, "BOOLEAN"),278  json: (name, field) => schemaArgument(name, field, "JSON"),279  literals: (name, _field, spec) => Argument.Literals(name, spec.literals),280  number: (name) => Argument.Finite(name),281  string: (name) => Argument.String(name),282} satisfies Record<283  FieldSpec["kind"],284  (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>285>;286287/**288 * The former flag may still give the value, so the parser lets the argument289 * be left out and the handler refuses if neither did. Unlike290 * `Argument.optional`, a fallback keeps help showing it as required.291 */292const leftOutForNow = (293  argument: Argument.Argument<unknown>294): Argument.Argument<unknown> =>295  argument.pipe(296    Argument.map(Option.some),297    Argument.withFallbackConfig(Config.succeed(Option.none())),298    Argument.map(Option.getOrUndefined)299  );300301const argumentFor = (302  name: string,303  field: Plain,304  fallback: string | undefined,305  wasFlag: boolean306): Argument.Argument<unknown> => {307  const spec = describe(field);308  const base = argumentBuilders[spec.kind](name, field, spec);309  const help = helpOf(spec, fallback);310311  const described =312    help === undefined ? base : base.pipe(Argument.withDescription(help));313314  if (spec.optional || fallback !== undefined) {315    return described.pipe(316      Argument.optional,317      Argument.map(Option.getOrUndefined)318    );319  }320321  return wasFlag ? leftOutForNow(described) : described;322};323324/** Still parses, checked by the field's schema, but hidden from help. */325const formerFlagFor = (name: string, field: Plain): Flag.Flag<unknown> => {326  const spec = describe(field);327328  return flagBuilders[spec.kind](name, field, spec).pipe(329    Flag.withHidden,330    Flag.optional,331    Flag.map(Option.getOrUndefined)332  );333};334335const controls = (approval: boolean, readOnly: boolean) =>336  Object.fromEntries([337    [338      "json",339      Flag.Boolean("json").pipe(340        Flag.withDefault(false),341        Flag.withDescription(342          "Print one versioned JSON envelope on stdout, and nothing else there"343        )344      ),345    ],346    ...(approval347      ? [348          [349            "yes",350            Flag.Boolean("yes").pipe(351              Flag.withDefault(false),352              Flag.withDescription(353                "Approve it: it runs only with --yes, since a person approves it first"354              )355            ),356          ] as const,357        ]358      : []),359    ...(readOnly360      ? []361      : [362          [363            "dryRun",364            Flag.Boolean("dry-run").pipe(365              Flag.withDefault(false),366              Flag.withDescription(367                "Print the payload it would send, and send nothing"368              )369            ),370          ] as const,371        ]),372  ]);373374const isRefusal = Schema.is(Refusal);375376export const commandName = (rpc: Rpc.AnyWithProps): string =>377  Context.get(rpc.annotations, Cli).name ?? rpc._tag;378379export const commandPath = (380  rpc: Rpc.AnyWithProps381): readonly [string, ...string[]] => {382  const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");383384  return [first, ...rest];385};386387const asJson = (text: string): View => ({388  markdown: ["```json", text, "```"].join("\n"),389  text,390});391392export const toCommand = <393  R extends CommandRpc,394  ClientR,395  OutputR,396  DefaultsR = never,397>(398  rpc: R,399  client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, ClientR>,400  options: ToCommandOptions<Rpc.Success<R>, OutputR, DefaultsR>401) => {402  const cli = Context.get(rpc.annotations, Cli);403  const command = commandName(rpc);404  const positional = new Set(cli.positional);405406  const wasFlag = new Set(407    cli.formerFlags?.filter((name) => positional.has(name))408  );409410  const approval = Context.get(rpc.annotations, NeedsApproval);411  const readOnly = Context.get(rpc.annotations, ReadOnly);412  const filled = options.defaults?.fields ?? {};413  const fields = fieldsOf(rpc.payloadSchema);414415  const required = fields.flatMap(([name, field]) =>416    isRequired(describe(field)) ? [name] : []417  );418419  const payload: Record<420    string,421    Flag.Flag<unknown> | Argument.Argument<unknown>422  > = {};423424  const former: Record<string, Flag.Flag<unknown>> = {};425426  for (const [name, field] of fields) {427    const fallback = required.includes(name) ? filled[name] : undefined;428429    payload[name] = positional.has(name)430      ? argumentFor(name, field, fallback, wasFlag.has(name))431      : flagFor(name, field, fallback);432433    if (wasFlag.has(name)) {434      former[name] = formerFlagFor(name, field);435    }436  }437438  const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);439  const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);440  const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);441442  const complete = (given: readonly (readonly [string, unknown])[]) =>443    Effect.gen(function* () {444      const provided = Object.fromEntries(445        given.filter(([, value]) => value !== undefined)446      );447448      const wanting = required.filter(449        (name) => !Object.hasOwn(provided, name) && Object.hasOwn(filled, name)450      );451452      const values: Readonly<Record<string, string>> =453        wanting.length === 0 || options.defaults === undefined454          ? {}455          : yield* options.defaults.values;456457      const merged = {458        ...provided,459        ...Object.fromEntries(460          wanting.flatMap((name) =>461            values[name] === undefined ? [] : [[name, values[name]] as const]462          )463        ),464      };465466      const missing = required.find((name) => !Object.hasOwn(merged, name));467468      if (missing !== undefined) {469        return yield* new MissingValue({470          command,471          flag: positional.has(missing) ? `<${missing}>` : `--${missing}`,472        });473      }474475      return yield* decodePayload(merged);476    });477478  return Command.make(479    commandPath(rpc).at(-1) ?? rpc._tag,480    { control: controls(approval, readOnly), former, payload },481    ({ control, former: formerly, payload: given }) =>482      Effect.gen(function* () {483        const json = control.json === true;484        const dryRun = control.dryRun === true;485486        if (approval && control.yes !== true && !dryRun) {487          return yield* new ApprovalNeeded({ command });488        }489490        const decoded = yield* complete(491          Object.entries(given).map(492            ([name, value]) => [name, value ?? formerly[name]] as const493          )494        );495496        const output = yield* options.output;497498        if (dryRun) {499          const encoded = yield* Effect.orDie(encodePayload(decoded));500501          return yield* output.plan({ command, json, payload: encoded });502        }503504        const calls = yield* client;505506        // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `decoded` was just decoded with that Rpc's payload schema.507        // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the client's mapped type cannot be indexed by a generic tag; see SAFETY.508        const byTag = calls as Readonly<509          Record<510            string,511            (512              payload: typeof decoded513            ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | CallError>514          >515        >;516517        const call =518          byTag[rpc._tag] ??519          (() => Effect.die(`The client has no method for ${rpc._tag}`));520521        const success = yield* call(decoded).pipe(522          Effect.catchIf(isRefusal, (refusal) =>523            endRefused(output, { command, json, refusals: [refusal] })524          )525        );526527        const carried = options.refusalsIn?.(success) ?? [];528529        if (Array.isReadonlyArrayNonEmpty(carried)) {530          return yield* endRefused(output, {531            command,532            json,533            refusals: carried,534          });535        }536537        const data = yield* Effect.orDie(encodeSuccess(success));538539        const rendered =540          options.render === undefined541            ? Option.none<View>()542            : options.render(success);543544        const view = Option.getOrElse(545          Effect.isEffect(rendered) ? yield* rendered : rendered,546          () => asJson(JSON.stringify(data, null, 2))547        );548549        return yield* output.success({ command, data, json, view });550      }).pipe(Effect.withSpan(`protocol.${rpc._tag}`))551  ).pipe(552    Command.withDescription(553      [554        Context.get(rpc.annotations, Description),555        ...(readOnly ? ["It only reads."] : []),556        ...(approval ? ["It runs only with --yes: a person approves it."] : []),557      ].join(" ")558    )559  );560};561562export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {563  readonly output: Effect.Effect<CommandOutput, never, OutputR>;564  readonly defaults?: Defaults<DefaultsR> | undefined;565  readonly views?: Views<Rpcs, DefaultsR> | undefined;566  readonly refusalsIn?:567    | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])568    | undefined;569  readonly exclude: readonly string[];570}571572export const toCommands = <573  Rpcs extends CommandRpc,574  ClientR,575  OutputR,576  DefaultsR = never,577>(578  group: RpcGroup.RpcGroup<Rpcs>,579  client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, ClientR>,580  options: ToCommandsOptions<Rpcs, OutputR, DefaultsR>581) =>582  [...group.requests.values()].flatMap((rpc) =>583    Context.get(rpc.annotations, Surfaces).includes("cli") &&584    !options.exclude.includes(rpc._tag)585      ? [586          {587            command: toCommand(rpc, client, {588              defaults: options.defaults,589              output: options.output,590              refusalsIn: options.refusalsIn,591              render: options.views?.[rpc._tag],592            }),593            path: commandPath(rpc),594            rpc,595          },596        ]597      : []598  );